Merge pull request #178 from BinaryAlley/bugfix/library-cover-image-handling

Bugfix/library cover image handling
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-08-26 09:48:04 -07:00
commit 6080b03ada
22 files changed
+1240 -39

No files matched your search

@@ -39,4 +39,30 @@ public interface IArtworkProviderConfigurationRepository : IRepository<LibraryAr
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> UpsertAsync(LibraryArtworkProviderConfigurationEntity configuration, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the artwork provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the artwork provider configurations referencing the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The Id of the plugin whose artwork provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken);
/// <summary>
/// Deletes the artwork provider configurations of the media library identified by <paramref name="libraryId"/> that reference
/// one of the plugins identified by <paramref name="pluginIds"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork provider configurations are deleted.</param>
/// <param name="pluginIds">The Ids of the plugins whose configurations of the media library are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable<Guid> pluginIds, CancellationToken cancellationToken);
}
@@ -39,4 +39,30 @@ public interface ILibraryMetadataProviderConfigurationRepository : IRepository<L
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> UpsertAsync(LibraryMetadataProviderConfigurationEntity configuration, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the metadata provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the metadata provider configurations referencing the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The Id of the plugin whose metadata provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken);
/// <summary>
/// Deletes the metadata provider configurations of the media library identified by <paramref name="libraryId"/> that reference
/// one of the plugins identified by <paramref name="pluginIds"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are deleted.</param>
/// <param name="pluginIds">The Ids of the plugins whose configurations of the media library are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable<Guid> pluginIds, CancellationToken cancellationToken);
}
@@ -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;
/// <summary>
/// Store of the metadata and artwork provider configurations of the media libraries.
/// </summary>
public interface IMediaLibraryProviderConfigurationStore
{
/// <summary>
/// Gets the metadata provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the configurations, or an error.</returns>
Task<Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>> GetConfigurationsAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// 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 <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose provider configurations are ensured.</param>
/// <param name="libraryType">The type of the media library, used to determine the plugins whose providers apply.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> EnsureProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken);
/// <summary>
/// Replaces the provider configurations of the media library identified by <paramref name="libraryId"/> so that they
/// match the plugins supporting the provided library type.
/// </summary>
/// <param name="libraryId">The Id of the media library whose provider configurations are reconciled.</param>
/// <param name="libraryType">The type of the media library, used to determine the plugins whose providers apply.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> ReconcileProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> RemoveProviderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the provider configurations referencing the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The Id of the plugin whose provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken);
}
@@ -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<AddLibraryCommand, Resul
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IEnvironmentContext _environmentContext;
private readonly IAuthorizationService _authorizationService;
private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore;
private readonly IValidator<AddLibraryCommand> _validator;
/// <summary>
@@ -46,13 +48,15 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="providerConfigurationStore">Injected store of the provider configurations of the media libraries.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public AddLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IEnvironmentContext environmentContext,
IMediaLibraryProviderConfigurationStore providerConfigurationStore,
IUnitOfWork unitOfWork,
IValidator<AddLibraryCommand> validator)
{
@@ -61,6 +65,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
_domainEventsQueue = domainEventsQueue;
_environmentContext = environmentContext;
_authorizationService = authorizationService;
_providerConfigurationStore = providerConfigurationStore;
_validator = validator;
}
@@ -123,10 +128,15 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
// convert the domain library entity to a repository library entity
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
// insert the repository entity and save changes
// insert the repository entity, seed the provider configurations of the new library so that it lists the plugins
// providing metadata or artwork for its type, and save the changes
Result<Created> insertLibraryResult = await _unitOfWork.LibraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
if (insertLibraryResult.IsFailure)
return insertLibraryResult.Errors;
Result<Success> ensureProviderConfigurationsResult = await _providerConfigurationStore.EnsureProviderConfigurationsAsync(
createLibraryResult.Value.Id.Value, Enum.Parse<LibraryType>(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
@@ -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<DeleteLibraryCommand,
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore;
private readonly IValidator<DeleteLibraryCommand> _validator;
/// <summary>
@@ -39,18 +41,21 @@ public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand,
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="providerConfigurationStore">Injected store of the provider configurations of the media libraries.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IMediaLibraryProviderConfigurationStore providerConfigurationStore,
IUnitOfWork unitOfWork,
IValidator<DeleteLibraryCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_providerConfigurationStore = providerConfigurationStore;
_unitOfWork = unitOfWork;
_validator = validator;
}
@@ -100,7 +105,10 @@ public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand,
foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
// perform the deletion
// remove the provider configurations of the library, so that they are not orphaned, and delete the library
Result<Deleted> removeProviderConfigurationsResult = await _providerConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (removeProviderConfigurationsResult.IsFailure)
return removeProviderConfigurationsResult.Errors;
Result<Deleted> deletePersistenceLibraryResult = await _unitOfWork.LibraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (deletePersistenceLibraryResult.IsFailure)
return deletePersistenceLibraryResult.Errors;
@@ -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<UpdateLibraryCommand,
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IEnvironmentContext _environmentContext;
private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore;
private readonly IValidator<UpdateLibraryCommand> _validator;
/// <summary>
@@ -50,13 +52,15 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="providerConfigurationStore">Injected store of the provider configurations of the media libraries.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateLibraryCommandHandler(
IAuthorizationService authorizationService,
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IEnvironmentContext environmentContext,
IMediaLibraryProviderConfigurationStore providerConfigurationStore,
IUnitOfWork unitOfWork,
IValidator<UpdateLibraryCommand> validator)
{
@@ -65,6 +69,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
_unitOfWork = unitOfWork;
_domainEventsQueue = domainEventsQueue;
_environmentContext = environmentContext;
_providerConfigurationStore = providerConfigurationStore;
_validator = validator;
}
@@ -88,8 +93,16 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// make sure the file is an actual supported image
if (command.CoverImage is not null)
// get a library repository and retrieve the library to update
Result<LibraryEntity?> 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<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage);
if (fileSystemPathIdResult.IsFailure)
@@ -102,13 +115,6 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
return DomainErrors.Library.CoverFileMustBeAnImage;
}
// get a library repository and retrieve the library to update
Result<LibraryEntity?> 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<ILibraryOwnershipPolicy>(
@@ -117,11 +123,12 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
return ApplicationErrors.Authorization.NotAuthorized;
// create a domain library object
LibraryType newLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
Result<Library> createLibraryResult = Library.Create(
LibraryId.Create(command.Id),
UserId.Create(command.OwnerId),
command.Title!,
Enum.Parse<LibraryType>(command.LibraryType!),
newLibraryType,
command.ContentLocations!,
command.CoverImage,
command.IsEnabled,
@@ -136,10 +143,17 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
// convert the domain library entity to a repository library entity
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
// update the repository entity and save changes
// update the repository entity, and when the library type changed, reconcile the provider configurations so that
// they match the plugins supporting the new type, and save the changes
Result<Updated> updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
if (updateLibraryResult.IsFailure)
return updateLibraryResult.Errors;
if (getLibraryResult.Value.LibraryType != newLibraryType)
{
Result<Success> 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
@@ -107,6 +107,22 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
return libraryPathResult.Value;
}
/// <summary>
/// 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 <see cref="IPathService.CombinePath"/>, because that method
/// treats the combined name as a directory segment and appends a trailing separator, which would make the file path invalid.
/// </summary>
/// <param name="relativePath">The path relative to the application base directory, with a leading path separator.</param>
/// <returns>An <see cref="Result{TValue}"/> containing the absolute path, or an error.</returns>
private Result<FileSystemPathId> ResolveInternalMediaPathId(string relativePath)
{
string absolutePath = AppContext.BaseDirectory.TrimEnd(_pathService.PathSeparator)
+ _pathService.PathSeparator
+ relativePath.TrimStart(_pathService.PathSeparator);
return FileSystemPathId.Create(absolutePath);
}
/// <summary>
/// Saves the cover image of a media library to the internal media directory.
/// </summary>
@@ -125,8 +141,21 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
Result<bool> 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<FileSystemPathId> internalImagePathIdResult = ResolveInternalMediaPathId(imagePath);
if (internalImagePathIdResult.IsFailure)
return internalImagePathIdResult.Errors;
Result<bool> 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<ImageType> imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false);
@@ -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<GetLibraryM
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore;
private readonly IValidator<GetLibraryMetadataProvidersQuery> _validator;
/// <summary>
@@ -34,12 +36,14 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler<GetLibraryM
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="providerConfigurationStore">Injected store of the provider configurations of the media libraries.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetLibraryMetadataProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<GetLibraryMetadataProvidersQuery> validator)
public GetLibraryMetadataProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IMediaLibraryProviderConfigurationStore providerConfigurationStore, IUnitOfWork unitOfWork, IValidator<GetLibraryMetadataProvidersQuery> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_providerConfigurationStore = providerConfigurationStore;
_unitOfWork = unitOfWork;
_validator = validator;
}
@@ -70,7 +74,7 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler<GetLibraryM
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _providerConfigurationStore.GetConfigurationsAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return getConfigurationsResult.Errors;
@@ -77,4 +77,55 @@ internal sealed class ArtworkProviderConfigurationRepository : IArtworkProviderC
}
return Result.Updated;
}
/// <summary>
/// Deletes all the artwork provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
List<LibraryArtworkProviderConfigurationEntity> configurations = await _luminaDbContext.LibraryArtworkProviderConfigurations
.Where(configuration => configuration.LibraryId == libraryId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
if (configurations.Count > 0)
_luminaDbContext.LibraryArtworkProviderConfigurations.RemoveRange(configurations);
return Result.Deleted;
}
/// <summary>
/// Deletes all the artwork provider configurations referencing the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The Id of the plugin whose artwork provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken)
{
List<LibraryArtworkProviderConfigurationEntity> configurations = await _luminaDbContext.LibraryArtworkProviderConfigurations
.Where(configuration => configuration.PluginId == pluginId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
if (configurations.Count > 0)
_luminaDbContext.LibraryArtworkProviderConfigurations.RemoveRange(configurations);
return Result.Deleted;
}
/// <summary>
/// Deletes the artwork provider configurations of the media library identified by <paramref name="libraryId"/> that reference
/// one of the plugins identified by <paramref name="pluginIds"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork provider configurations are deleted.</param>
/// <param name="pluginIds">The Ids of the plugins whose configurations of the media library are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable<Guid> pluginIds, CancellationToken cancellationToken)
{
List<Guid> pluginIdList = [.. pluginIds];
List<LibraryArtworkProviderConfigurationEntity> 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;
}
}
@@ -77,4 +77,55 @@ internal sealed class LibraryMetadataProviderConfigurationRepository : ILibraryM
}
return Result.Updated;
}
/// <summary>
/// Deletes all the metadata provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
List<LibraryMetadataProviderConfigurationEntity> configurations = await _luminaDbContext.LibraryMetadataProviderConfigurations
.Where(configuration => configuration.LibraryId == libraryId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
if (configurations.Count > 0)
_luminaDbContext.LibraryMetadataProviderConfigurations.RemoveRange(configurations);
return Result.Deleted;
}
/// <summary>
/// Deletes all the metadata provider configurations referencing the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The Id of the plugin whose metadata provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken)
{
List<LibraryMetadataProviderConfigurationEntity> configurations = await _luminaDbContext.LibraryMetadataProviderConfigurations
.Where(configuration => configuration.PluginId == pluginId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
if (configurations.Count > 0)
_luminaDbContext.LibraryMetadataProviderConfigurations.RemoveRange(configurations);
return Result.Deleted;
}
/// <summary>
/// Deletes the metadata provider configurations of the media library identified by <paramref name="libraryId"/> that reference
/// one of the plugins identified by <paramref name="pluginIds"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are deleted.</param>
/// <param name="pluginIds">The Ids of the plugins whose configurations of the media library are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable<Guid> pluginIds, CancellationToken cancellationToken)
{
List<Guid> pluginIdList = [.. pluginIds];
List<LibraryMetadataProviderConfigurationEntity> 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;
}
}
@@ -115,6 +115,7 @@ public static class InfrastructureLayerServices
services.AddSingleton<IPluginManager>(new PluginManager(pluginLoadResult.Plugins));
services.AddScoped<IPluginSettingsStore, PluginSettingsStore>();
services.AddScoped<IPluginInstaller, PluginInstaller>();
services.AddScoped<IMediaLibraryProviderConfigurationStore, MediaLibraryProviderConfigurationStore>();
services.AddSingleton(serviceProvider => new PluginDetectionSyncJob(
serviceProvider.GetRequiredService<IServiceScopeFactory>(),
serviceProvider.GetRequiredService<IPluginManager>(),
@@ -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;
/// <summary>
/// Store of the metadata and artwork provider configurations of the media libraries.
/// </summary>
internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProviderConfigurationStore
{
private readonly IUnitOfWork _unitOfWork;
private readonly IPluginManager _pluginManager;
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryProviderConfigurationStore"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="pluginManager">Injected manager of the plugins loaded by the host application.</param>
/// <param name="serviceProvider">Injected provider used to resolve the providers registered by the plugins.</param>
public MediaLibraryProviderConfigurationStore(IUnitOfWork unitOfWork, IPluginManager pluginManager, IServiceProvider serviceProvider)
{
_unitOfWork = unitOfWork;
_pluginManager = pluginManager;
_serviceProvider = serviceProvider;
}
/// <inheritdoc/>
public async Task<Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>> GetConfigurationsAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<Result<Success>> EnsureProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken)
{
(IReadOnlyList<Guid> metadataProviderPluginIds, IReadOnlyList<Guid> artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType);
Result<Success> ensureMetadataResult = await EnsureMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false);
if (ensureMetadataResult.IsFailure)
return ensureMetadataResult;
return await EnsureArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<Result<Success>> ReconcileProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken)
{
(IReadOnlyList<Guid> metadataProviderPluginIds, IReadOnlyList<Guid> artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType);
Result<Success> reconcileMetadataResult = await ReconcileMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false);
if (reconcileMetadataResult.IsFailure)
return reconcileMetadataResult;
return await ReconcileArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<Result<Deleted>> RemoveProviderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken)
{
Result<Deleted> removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (removeMetadataResult.IsFailure)
return removeMetadataResult;
return await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<Result<Deleted>> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken)
{
Result<Deleted> removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
if (removeMetadataResult.IsFailure)
return removeMetadataResult;
return await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="libraryType">The type of the media library the providers must support.</param>
/// <returns>The Ids of the plugins providing metadata, and the Ids of the plugins providing artwork.</returns>
private (IReadOnlyList<Guid> metadataProviderPluginIds, IReadOnlyList<Guid> artworkProviderPluginIds) GetSupportedProviderPluginIds(LibraryType libraryType)
{
List<Guid> metadataProviderPluginIds = [];
List<Guid> artworkProviderPluginIds = [];
foreach (IPlugin plugin in _pluginManager.GetPlugins().OrderBy(plugin => plugin.Name))
{
if (_serviceProvider.GetKeyedServices<IMetadataProvider>(plugin.Id).Any(provider => provider.SupportedLibraryTypes.Contains(libraryType)))
metadataProviderPluginIds.Add(plugin.Id);
if (_serviceProvider.GetKeyedServices<IArtworkProvider>(plugin.Id).Any(provider => provider.SupportedLibraryTypes.Contains(libraryType)))
artworkProviderPluginIds.Add(plugin.Id);
}
return (metadataProviderPluginIds, artworkProviderPluginIds);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are reconciled.</param>
/// <param name="metadataProviderPluginIds">The Ids of the plugins providing metadata for the library type, in rank order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> ReconcileMetadataConfigurationsAsync(Guid libraryId, IReadOnlyList<Guid> metadataProviderPluginIds, CancellationToken cancellationToken)
{
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return Result<Success>.Failure(getConfigurationsResult.Errors);
HashSet<Guid> supportedPluginIds = metadataProviderPluginIds.ToHashSet();
List<Guid> stalePluginIds = getConfigurationsResult.Value
.Select(configuration => configuration.PluginId)
.Where(pluginId => !supportedPluginIds.Contains(pluginId))
.ToList();
if (stalePluginIds.Count > 0)
{
Result<Deleted> removeResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false);
if (removeResult.IsFailure)
return Result<Success>.Failure(removeResult.Errors);
}
HashSet<Guid> 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<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return Result<Success>.Failure(upsertResult.Errors);
nextRank++;
}
return Result.Success;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork provider configurations are reconciled.</param>
/// <param name="artworkProviderPluginIds">The Ids of the plugins providing artwork for the library type, in rank order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> ReconcileArtworkConfigurationsAsync(Guid libraryId, IReadOnlyList<Guid> artworkProviderPluginIds, CancellationToken cancellationToken)
{
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return Result<Success>.Failure(getConfigurationsResult.Errors);
HashSet<Guid> supportedPluginIds = artworkProviderPluginIds.ToHashSet();
List<Guid> stalePluginIds = getConfigurationsResult.Value
.Select(configuration => configuration.PluginId)
.Where(pluginId => !supportedPluginIds.Contains(pluginId))
.ToList();
if (stalePluginIds.Count > 0)
{
Result<Deleted> removeResult = await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false);
if (removeResult.IsFailure)
return Result<Success>.Failure(removeResult.Errors);
}
HashSet<Guid> 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<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return Result<Success>.Failure(upsertResult.Errors);
nextRank++;
}
return Result.Success;
}
/// <summary>
/// Adds a disabled metadata provider configuration for every provided plugin that has no configuration yet for the media library.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are ensured.</param>
/// <param name="metadataProviderPluginIds">The Ids of the plugins providing metadata for the library type, in rank order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> EnsureMetadataConfigurationsAsync(Guid libraryId, IReadOnlyList<Guid> metadataProviderPluginIds, CancellationToken cancellationToken)
{
if (metadataProviderPluginIds.Count == 0)
return Result.Success;
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return Result<Success>.Failure(getConfigurationsResult.Errors);
HashSet<Guid> 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<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return Result<Success>.Failure(upsertResult.Errors);
nextRank++;
}
return Result.Success;
}
/// <summary>
/// Adds a disabled artwork provider configuration for every provided plugin that has no configuration yet for the media library.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork provider configurations are ensured.</param>
/// <param name="artworkProviderPluginIds">The Ids of the plugins providing artwork for the library type, in rank order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> EnsureArtworkConfigurationsAsync(Guid libraryId, IReadOnlyList<Guid> artworkProviderPluginIds, CancellationToken cancellationToken)
{
if (artworkProviderPluginIds.Count == 0)
return Result.Success;
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return Result<Success>.Failure(getConfigurationsResult.Errors);
HashSet<Guid> 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<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return Result<Success>.Failure(upsertResult.Errors);
nextRank++;
}
return Result.Success;
}
}
@@ -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<IMediaLibraryProviderConfigurationStore>();
Result<IEnumerable<PluginEntity>> 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<Deleted> 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<Deleted> 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<IEnumerable<LibraryEntity>> 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<Success> 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);
}
}
@@ -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<AddLibraryCommand> _mockValidator;
private readonly AddLibraryCommandHandler _sut;
private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new();
@@ -57,19 +60,22 @@ public class AddLibraryCommandHandlerTests
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockProviderConfigurationStore = Substitute.For<IMediaLibraryProviderConfigurationStore>();
_mockValidator = Substitute.For<IValidator<AddLibraryCommand>>();
_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<CancellationToken>()).Returns(true);
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
_mockLibraryRepository.InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any<AddLibraryCommand>()).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<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(
Arg.Any<Guid>(), Arg.Is<LibraryType>(libraryType => libraryType == Enum.Parse<LibraryType>(command.LibraryType)), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibrarySavedDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenProviderConfigurationSeedingFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create();
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to seed provider configurations"));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCoverImageIsNull_ShouldSkipImageTypeCheck()
{
@@ -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<DeleteLibraryCommand> _mockValidator;
private readonly DeleteLibraryCommandHandler _sut;
private readonly DeleteLibraryCommandFixture _deleteLibraryCommandFixture = new();
@@ -53,18 +55,21 @@ public class DeleteLibraryCommandHandlerTests
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockProviderConfigurationStore = Substitute.For<IMediaLibraryProviderConfigurationStore>();
_mockValidator = Substitute.For<IValidator<DeleteLibraryCommand>>();
_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<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockProviderConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockLibraryRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockValidator.Validate(Arg.Any<DeleteLibraryCommand>()).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<CancellationToken>());
await _mockLibraryRepository.Received(1).DeleteByIdAsync(command.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibraryDeletedDomainEvent>());
}
[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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockProviderConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to remove provider configurations"));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError()
{
@@ -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<UpdateLibraryCommand> _mockValidator;
private readonly UpdateLibraryCommandHandler _sut;
private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new();
@@ -59,10 +62,11 @@ public class UpdateLibraryCommandHandlerTests
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockProviderConfigurationStore = Substitute.For<IMediaLibraryProviderConfigurationStore>();
_mockValidator = Substitute.For<IValidator<UpdateLibraryCommand>>();
_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<AuthorizationPermission>(), Arg.Any<CancellationToken>())
.Returns(true);
@@ -70,9 +74,11 @@ public class UpdateLibraryCommandHandlerTests
.Returns(Result.From(ImageType.PNG));
_mockLibraryRepository.UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any<UpdateLibraryCommand>()).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<LibraryType>(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<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(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<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).ReconcileProviderConfigurationsAsync(
command.Id, Arg.Is<LibraryType>(libraryType => libraryType == commandLibraryType), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibrarySavedDomainEvent>());
}
[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<LibraryType>(command.LibraryType);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockProviderConfigurationStore.DidNotReceive().ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenProviderConfigurationReconciliationFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryType commandLibraryType = Enum.Parse<LibraryType>(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<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to reconcile provider configurations"));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.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<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.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<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> 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<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockEnvironmentContext.FileTypeService.DidNotReceive()
.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.Received(2).GetByIdAsync(command.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError()
{
@@ -156,6 +156,30 @@ public class LibrarySavedDomainEventHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(string.Concat(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1)) + '/'));
string internalImagePath = $"{AppContext.BaseDirectory.TrimEnd('/')}/Media/Libraries/guid/cover.png";
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
.Returns(callInfo => Result.From(callInfo.Arg<FileSystemPathId>().Path == internalImagePath));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
Assert.Equal("/Media/Libraries/guid/cover.png", library.CoverImage);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), Arg.Any<bool>());
await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCoverSourceFileDoesNotExist_ShouldThrowEventualConsistencyException()
{
@@ -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<GetLibraryMetadataProvidersQuery> _mockValidator;
private readonly GetLibraryMetadataProvidersQueryHandler _sut;
private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new();
@@ -47,12 +48,11 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
public GetLibraryMetadataProvidersQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryMetadataProviderConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockLibraryMetadataProviderConfigurationRepository);
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockProviderConfigurationStore = Substitute.For<IMediaLibraryProviderConfigurationStore>();
_mockValidator = Substitute.For<IValidator<GetLibraryMetadataProvidersQuery>>();
_userId = Guid.NewGuid();
@@ -62,7 +62,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
.Returns(true);
_mockValidator.Validate(Arg.Any<GetLibraryMetadataProvidersQuery>()).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<Guid>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.DidNotReceive().GetConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
_mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>(configurations));
List<PluginEntity> plugins =
[
@@ -125,7 +125,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
[
_configurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1)
];
_mockLibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
_mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>(configurations));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<PluginEntity>>([_pluginEntityFixture.Create()]));
@@ -145,7 +145,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
{
// Arrange
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
_mockLibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
_mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<PluginEntity>>([]));
@@ -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<CancellationToken>())
_mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
@@ -180,7 +180,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
{
// Arrange
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
_mockLibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
_mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.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<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.LibraryId), Arg.Any<CancellationToken>());
await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.DidNotReceive().GetConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
@@ -226,6 +226,6 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.DidNotReceive().GetConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
}
@@ -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<Deleted> 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<Deleted> 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<Deleted> 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);
}
}
@@ -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<Deleted> 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<Deleted> 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<Deleted> 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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryProviderConfigurationStore"/> class.
/// </summary>
[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();
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryProviderConfigurationStoreTests"/> class.
/// </summary>
public MediaLibraryProviderConfigurationStoreTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository);
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
_mockPluginManager = Substitute.For<IPluginManager>();
_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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([configuration]));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> 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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockMetadataConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockArtworkConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == alphaPluginId && configuration.Rank == 1 && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 2 && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 1 && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([existingConfiguration]));
// Act
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
}
[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<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Error.Failure(description: "Failed to read configurations"));
// Act
Result<Success> 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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([existingConfiguration]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockMetadataConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync(
libraryId, Arg.Is<IEnumerable<Guid>>(pluginIds => pluginIds.SequenceEqual(new[] { alphaPluginId })), Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 2 && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == alphaPluginId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task RemoveProviderConfigurationsForLibraryAsync_WhenCalled_ShouldDeleteTheConfigurationsOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockMetadataConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtworkConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveProviderConfigurationsForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task RemoveProviderConfigurationsAsync_WhenCalled_ShouldDeleteTheConfigurationsOfThePlugin()
{
// Arrange
Guid pluginId = Guid.NewGuid();
_mockMetadataConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtworkConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveProviderConfigurationsAsync(pluginId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates the store under test wired to the mocked dependencies, optionally registering the providers of the loaded plugins.
/// </summary>
/// <param name="pluginProviders">The providers registered by the loaded plugins, keyed by their plugin, when any.</param>
/// <returns>The created store.</returns>
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<IMetadataProvider>(pluginId, (_, _) => metadataProvider);
if (artworkProvider is not null)
services.AddKeyedSingleton<IArtworkProvider>(pluginId, (_, _) => artworkProvider);
}
return new MediaLibraryProviderConfigurationStore(_mockUnitOfWork, _mockPluginManager, services.BuildServiceProvider());
}
/// <summary>
/// Creates a mocked plugin with the provided identity.
/// </summary>
/// <param name="id">The Id of the plugin.</param>
/// <param name="name">The name of the plugin.</param>
/// <returns>The created plugin mock.</returns>
private static IPlugin CreatePlugin(Guid id, string name)
{
IPlugin plugin = Substitute.For<IPlugin>();
plugin.Id.Returns(id);
plugin.Name.Returns(name);
return plugin;
}
/// <summary>
/// Creates a mocked metadata provider supporting the provided library type.
/// </summary>
/// <param name="supportedLibraryType">The library type supported by the provider.</param>
/// <returns>The created metadata provider mock.</returns>
private static IMetadataProvider CreateMetadataProvider(LibraryType supportedLibraryType)
{
IMetadataProvider provider = Substitute.For<IMetadataProvider>();
provider.SupportedLibraryTypes.Returns([supportedLibraryType]);
return provider;
}
/// <summary>
/// Creates a mocked artwork provider supporting the provided library type.
/// </summary>
/// <param name="supportedLibraryType">The library type supported by the provider.</param>
/// <returns>The created artwork provider mock.</returns>
private static IArtworkProvider CreateArtworkProvider(LibraryType supportedLibraryType)
{
IArtworkProvider provider = Substitute.For<IArtworkProvider>();
provider.SupportedLibraryTypes.Returns([supportedLibraryType]);
return provider;
}
}
@@ -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<PluginDetectionSyncJob> _mockLogger;
private readonly PluginLoadErrorDtoFixture _pluginLoadErrorDtoFixture;
private readonly PluginEntityFixture _pluginEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="PluginDetectionSyncJobTests"/> class.
@@ -57,7 +64,15 @@ public class PluginDetectionSyncJobTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockProviderConfigurationStore = Substitute.For<IMediaLibraryProviderConfigurationStore>();
_mockProviderConfigurationStore.RemoveProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockServiceProvider.GetService(typeof(IMediaLibraryProviderConfigurationStore)).Returns(_mockProviderConfigurationStore);
_mockPluginManager = Substitute.For<IPluginManager>();
_mockLogger = Substitute.For<ILogger<PluginDetectionSyncJob>>();
@@ -182,6 +197,31 @@ public class PluginDetectionSyncJobTests
// Assert
await _mockPluginRepository.Received(1).DeleteByIdAsync(stalePluginRow.Id, Arg.Any<CancellationToken>());
await _mockPluginRepository.DidNotReceive().DeleteByIdAsync(loadedPluginRow.Id, Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).RemoveProviderConfigurationsAsync(stalePluginRow.Id, Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.DidNotReceive().RemoveProviderConfigurationsAsync(loadedPluginRow.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<PluginEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
LibraryEntity bookLibrary = _libraryEntityFixture.Create(libraryType: LibraryType.Book);
_mockLibraryRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From((IEnumerable<LibraryEntity>)[bookLibrary]));
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
PluginDetectionSyncJob sut = CreateSut();
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}