diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryMetadataProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryMetadataProvidersRequestMapping.cs new file mode 100644 index 00000000..e14f4dab --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryMetadataProvidersRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryMetadataProvidersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryMetadataProvidersQuery ToQuery(this GetLibraryMetadataProvidersRequest request) + { + return new GetLibraryMetadataProvidersQuery(request.LibraryId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetPluginSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetPluginSettingsRequestMapping.cs new file mode 100644 index 00000000..8f196830 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetPluginSettingsRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class GetPluginSettingsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetPluginSettingsQuery ToQuery(this GetPluginSettingsRequest request) + { + return new GetPluginSettingsQuery(request.PluginId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/LibraryMetadataProviderConfigurationEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/LibraryMetadataProviderConfigurationEntityMapping.cs new file mode 100644 index 00000000..a1c7805b --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/LibraryMetadataProviderConfigurationEntityMapping.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Responses.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class LibraryMetadataProviderConfigurationEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The display name of the metadata provider. + /// The converted response. + public static LibraryMetadataProviderResponse ToResponse(this LibraryMetadataProviderConfigurationEntity configuration, string providerName) + { + return new LibraryMetadataProviderResponse( + configuration.PluginId, + providerName, + configuration.IsEnabled, + configuration.Rank + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/PluginEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/PluginEntityMapping.cs new file mode 100644 index 00000000..4864cae7 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/PluginEntityMapping.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System.Collections.Generic; +using System.Text.Json; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class PluginEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response. + public static PluginResponse ToResponse(this PluginEntity pluginEntity) + { + return new PluginResponse( + pluginEntity.Id, + pluginEntity.Name, + pluginEntity.Author, + pluginEntity.Version, + pluginEntity.Description, + pluginEntity.LoadStatus, + pluginEntity.LoadError, + pluginEntity.ToSettings() + ); + } + + /// + /// Deserializes the settings of . + /// + /// The repository entity whose settings are deserialized. + /// The deserialized settings, or when no settings are stored. + public static IReadOnlyDictionary? ToSettings(this PluginEntity pluginEntity) + { + if (pluginEntity.SettingsJson is null) + return null; + return JsonSerializer.Deserialize>(pluginEntity.SettingsJson); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/PluginSettingDescriptorMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/PluginSettingDescriptorMapping.cs new file mode 100644 index 00000000..c700ac71 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/PluginSettingDescriptorMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using ContractsPluginSettingType = Lumina.Contracts.Responses.Plugins.PluginSettingType; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class PluginSettingDescriptorMapping +{ + /// + /// Converts to . + /// + /// The plugin contract setting descriptor to be converted. + /// The converted response. + public static PluginSettingDescriptorResponse ToResponse(this PluginSettingDescriptorDto descriptor) + { + return new PluginSettingDescriptorResponse( + descriptor.Key, + descriptor.Label, + (ContractsPluginSettingType)(int)descriptor.Type, + descriptor.DefaultValue, + descriptor.AllowedValues + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMapping.cs new file mode 100644 index 00000000..6857df1e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class ReorderLibraryMetadataProvidersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static ReorderLibraryMetadataProvidersCommand ToCommand(this ReorderLibraryMetadataProvidersRequest request) + { + return new ReorderLibraryMetadataProvidersCommand(request.LibraryId, request.PluginIds); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMapping.cs new file mode 100644 index 00000000..a0b46032 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class SetLibraryMetadataProviderEnabledRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static SetLibraryMetadataProviderEnabledCommand ToCommand(this SetLibraryMetadataProviderEnabledRequest request) + { + return new SetLibraryMetadataProviderEnabledCommand(request.LibraryId, request.PluginId, request.IsEnabled); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/UpdatePluginSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/UpdatePluginSettingsRequestMapping.cs new file mode 100644 index 00000000..6e8f1930 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/UpdatePluginSettingsRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class UpdatePluginSettingsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static UpdatePluginSettingsCommand ToCommand(this UpdatePluginSettingsRequest request) + { + return new UpdatePluginSettingsCommand(request.PluginId, request.Settings); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs new file mode 100644 index 00000000..1a695d7e --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Mediator; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; + +/// +/// Command for reordering the metadata providers of a media library. +/// +/// The Id of the media library whose metadata providers are reordered. +/// The plugin Ids in the new order, from highest to lowest rank. +public record ReorderLibraryMetadataProvidersCommand( + Guid LibraryId, + IReadOnlyList PluginIds +) : IRequest>; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs new file mode 100644 index 00000000..1c1a2034 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Mediator; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; + +/// +/// Handler for the command to reorder the metadata providers of a media library. +/// +public class ReorderLibraryMetadataProvidersCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public ReorderLibraryMetadataProvidersCommandHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Handles the command to reorder the metadata providers of a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async ValueTask> Handle(ReorderLibraryMetadataProvidersCommand request, CancellationToken cancellationToken) + { + ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); + ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsError) + return getConfigurationsResult.Errors; + + Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); + for (int rank = 0; rank < request.PluginIds.Count; rank++) + { + Guid pluginId = request.PluginIds[rank]; + if (configurationsByPluginId.TryGetValue(pluginId, out LibraryMetadataProviderConfigurationEntity? configuration)) + { + configuration.Rank = rank + 1; + ErrorOr upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsError) + return upsertResult.Errors; + } + } + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs new file mode 100644 index 00000000..aff5200e --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Domain.SharedKernel.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; + +/// +/// Validates the needed validation rules for . +/// +public class ReorderLibraryMetadataProvidersCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryMetadataProvidersCommandValidator() + { + RuleFor(x => x.LibraryId) + .NotEmpty().WithMessage(Errors.Plugins.LibraryIdCannotBeEmpty.Description); + RuleFor(x => x.PluginIds) + .NotNull().WithMessage(Errors.Plugins.PluginIdsListCannotBeNull.Description) + .NotEmpty().WithMessage(Errors.Plugins.PluginIdsListCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs new file mode 100644 index 00000000..b0e98e20 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Mediator; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; + +/// +/// Command for enabling or disabling a metadata provider for a media library. +/// +/// The Id of the media library whose metadata provider is enabled or disabled. +/// The unique identifier of the plugin providing the metadata. +/// Whether the metadata provider should be enabled for the media library. +public record SetLibraryMetadataProviderEnabledCommand( + Guid LibraryId, + Guid PluginId, + bool IsEnabled +) : IRequest>; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs new file mode 100644 index 00000000..3d4be916 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Mediator; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; + +/// +/// Handler for the command to enable or disable a metadata provider for a media library. +/// +public class SetLibraryMetadataProviderEnabledCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public SetLibraryMetadataProviderEnabledCommandHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Handles the command to enable or disable a metadata provider for a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async ValueTask> Handle(SetLibraryMetadataProviderEnabledCommand request, CancellationToken cancellationToken) + { + ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); + ErrorOr getConfigurationResult = await configurationRepository.GetByLibraryAndPluginIdAsync(request.LibraryId, request.PluginId, cancellationToken).ConfigureAwait(false); + if (getConfigurationResult.IsError) + return getConfigurationResult.Errors; + + LibraryMetadataProviderConfigurationEntity configuration; + if (getConfigurationResult.Value is not null) + { + configuration = getConfigurationResult.Value; + configuration.IsEnabled = request.IsEnabled; + } + else + { + // compute the rank to assign to the new configuration, appending it after the existing ones + ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsError) + return getConfigurationsResult.Errors; + int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; + configuration = new LibraryMetadataProviderConfigurationEntity + { + Id = Guid.NewGuid(), + LibraryId = request.LibraryId, + PluginId = request.PluginId, + IsEnabled = request.IsEnabled, + Rank = nextRank, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + } + + ErrorOr upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsError) + return upsertResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs new file mode 100644 index 00000000..fc27be68 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Domain.SharedKernel.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; + +/// +/// Validates the needed validation rules for . +/// +public class SetLibraryMetadataProviderEnabledCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public SetLibraryMetadataProviderEnabledCommandValidator() + { + RuleFor(x => x.LibraryId) + .NotEmpty().WithMessage(Errors.Plugins.LibraryIdCannotBeEmpty.Description); + RuleFor(x => x.PluginId) + .NotEmpty().WithMessage(Errors.Plugins.PluginIdCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommand.cs new file mode 100644 index 00000000..e160d675 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommand.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Mediator; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; + +/// +/// Command for updating the settings of a plugin. +/// +/// The unique identifier of the plugin. +/// The settings of the plugin. +public record UpdatePluginSettingsCommand( + Guid PluginId, + IReadOnlyDictionary? Settings +) : IRequest>; diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs new file mode 100644 index 00000000..e97a118b --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Mediator; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; + +/// +/// Handler for the command to update the settings of a plugin. +/// +public class UpdatePluginSettingsCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public UpdatePluginSettingsCommandHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Handles the command to update the settings of a plugin. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async ValueTask> Handle(UpdatePluginSettingsCommand request, CancellationToken cancellationToken) + { + IPluginRepository pluginRepository = _unitOfWork.GetRepository(); + string? settingsJson = request.Settings is not null ? JsonSerializer.Serialize(request.Settings) : null; + ErrorOr updateResult = await pluginRepository.UpdateSettingsAsync(request.PluginId, settingsJson, cancellationToken).ConfigureAwait(false); + if (updateResult.IsError) + return updateResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs new file mode 100644 index 00000000..454fcfec --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Domain.SharedKernel.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; + +/// +/// Validates the needed validation rules for . +/// +public class UpdatePluginSettingsCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePluginSettingsCommandValidator() + { + RuleFor(x => x.PluginId) + .NotEmpty().WithMessage(Errors.Plugins.PluginIdCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQuery.cs new file mode 100644 index 00000000..e73ecb00 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQuery.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Plugins; +using Mediator; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; + +/// +/// Query for getting the metadata providers configured for a media library. +/// +/// The Id of the media library whose metadata providers are retrieved. +public record GetLibraryMetadataProvidersQuery( + Guid LibraryId +) : IRequest>>; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs new file mode 100644 index 00000000..46e89a7a --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Mediator; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; + +/// +/// Handler for the query to get the metadata providers configured for a media library. +/// +public class GetLibraryMetadataProvidersQueryHandler : IRequestHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public GetLibraryMetadataProvidersQueryHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Handles the query to get the metadata providers configured for a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async ValueTask>> Handle(GetLibraryMetadataProvidersQuery request, CancellationToken cancellationToken) + { + ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); + ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsError) + return getConfigurationsResult.Errors; + + // build a plugin name lookup from the detected plugins + IPluginRepository pluginRepository = _unitOfWork.GetRepository(); + ErrorOr> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsError) + return getPluginsResult.Errors; + Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + + return getConfigurationsResult.Value + .OrderBy(configuration => configuration.Rank) + .Select(configuration => configuration.ToResponse(pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty)) + .ToList(); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQuery.cs new file mode 100644 index 00000000..a7daf05b --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQuery.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Plugins; +using Mediator; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetPluginSettings; + +/// +/// Query for getting the settings of a plugin and their schema. +/// +/// The unique identifier of the plugin. +public record GetPluginSettingsQuery( + Guid PluginId +) : IRequest>; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs new file mode 100644 index 00000000..ce66191a --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.SharedKernel.Common.Errors; +using Lumina.Plugins.Contracts.Core.Plugins; +using Mediator; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetPluginSettings; + +/// +/// Handler for the query to get the settings of a plugin and their schema. +/// +public class GetPluginSettingsQueryHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IPluginManager _pluginManager; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected manager of the plugins loaded by the host application. + public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager) + { + _unitOfWork = unitOfWork; + _pluginManager = pluginManager; + } + + /// + /// Handles the query to get the settings of a plugin and their schema. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a , or an error. + /// + public async ValueTask> Handle(GetPluginSettingsQuery request, CancellationToken cancellationToken) + { + IPluginRepository pluginRepository = _unitOfWork.GetRepository(); + ErrorOr getPluginResult = await pluginRepository.GetByIdAsync(request.PluginId, cancellationToken).ConfigureAwait(false); + if (getPluginResult.IsError) + return getPluginResult.Errors; + PluginEntity? pluginEntity = getPluginResult.Value; + if (pluginEntity is null) + return Errors.Plugins.PluginNotFound; + + // the schema comes from the loaded plugin, the current values from the storage medium + IPlugin? loadedPlugin = _pluginManager.GetPlugin(request.PluginId); + IReadOnlyList schema = loadedPlugin is not null + ? loadedPlugin.GetSettingsSchema().Select(setting => setting.ToResponse()).ToList() + : []; + return new PluginSettingsResponse(request.PluginId, schema, pluginEntity.ToSettings()); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQuery.cs new file mode 100644 index 00000000..2a840280 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQuery.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.Plugins; +using Mediator; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetPlugins; + +/// +/// Query for getting all the detected plugins. +/// +public record GetPluginsQuery() : IRequest>>; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs new file mode 100644 index 00000000..fe8a7292 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Mediator; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetPlugins; + +/// +/// Handler for the query to get all the detected plugins. +/// +public class GetPluginsQueryHandler : IRequestHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public GetPluginsQueryHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Handles the query to get all the detected plugins. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async ValueTask>> Handle(GetPluginsQuery request, CancellationToken cancellationToken) + { + IPluginRepository pluginRepository = _unitOfWork.GetRepository(); + ErrorOr> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + return getPluginsResult.Match( + plugins => ErrorOrFactory.From>(plugins.Select(plugin => plugin.ToResponse()).ToList()), + errors => errors); + } +} diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryMetadataProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryMetadataProvidersRequest.cs new file mode 100644 index 00000000..5e2e14c9 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryMetadataProvidersRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the metadata providers configured for a media library. +/// +/// The Id of the media library whose metadata providers are retrieved. Required. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public sealed record GetLibraryMetadataProvidersRequest( + Guid LibraryId +); diff --git a/src/Lumina.Contracts/Requests/Plugins/GetPluginSettingsRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetPluginSettingsRequest.cs new file mode 100644 index 00000000..2d0d5d09 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetPluginSettingsRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the settings of a plugin. +/// +/// The unique identifier of the plugin. Required. +[DebuggerDisplay("PluginId: {PluginId}")] +public sealed record GetPluginSettingsRequest( + Guid PluginId +); diff --git a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs new file mode 100644 index 00000000..24b6021e --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to reorder the metadata providers of a media library. +/// +/// The Id of the media library whose metadata providers are reordered. Required. +/// The plugin Ids in the new order, from highest to lowest rank. Required. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public sealed record ReorderLibraryMetadataProvidersRequest( + Guid LibraryId, + IReadOnlyList PluginIds +); diff --git a/src/Lumina.Contracts/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs new file mode 100644 index 00000000..385c4bc1 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to enable or disable a metadata provider for a media library. +/// +/// The Id of the media library whose metadata provider is enabled or disabled. Required. +/// The unique identifier of the plugin providing the metadata. Required. +/// Whether the metadata provider should be enabled for the media library. +[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] +public sealed record SetLibraryMetadataProviderEnabledRequest( + Guid LibraryId, + Guid PluginId, + bool IsEnabled +); diff --git a/src/Lumina.Contracts/Requests/Plugins/UpdatePluginSettingsRequest.cs b/src/Lumina.Contracts/Requests/Plugins/UpdatePluginSettingsRequest.cs new file mode 100644 index 00000000..8646f137 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/UpdatePluginSettingsRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to update the settings of a plugin. +/// +/// The unique identifier of the plugin. Required. +/// The settings of the plugin. +[DebuggerDisplay("PluginId: {PluginId}")] +public sealed record UpdatePluginSettingsRequest( + Guid PluginId, + IReadOnlyDictionary? Settings +); diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs new file mode 100644 index 00000000..b47a3b1a --- /dev/null +++ b/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.Responses.Plugins; + +/// +/// Represents a metadata provider configured for a media library. +/// +/// The unique identifier of the plugin providing the metadata. +/// The display name of the metadata provider. +/// Whether the metadata provider is enabled for the media library. +/// The rank of the metadata provider, determining the order in which providers are tried. +public sealed record LibraryMetadataProviderResponse( + Guid PluginId, + string Name, + bool IsEnabled, + int Rank +); diff --git a/src/Lumina.Contracts/Responses/Plugins/PluginResponse.cs b/src/Lumina.Contracts/Responses/Plugins/PluginResponse.cs new file mode 100644 index 00000000..f5a290f5 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Plugins/PluginResponse.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Plugins; + +/// +/// Represents a detected plugin. +/// +/// The unique identifier of the plugin. +/// The display name of the plugin. +/// The author of the plugin. +/// The version of the plugin. +/// The description of the plugin. +/// The load status of the plugin. +/// The error message when the plugin failed to load, if applicable. +/// The settings of the plugin. +[DebuggerDisplay("Name: {Name}")] +public sealed record PluginResponse( + Guid Id, + string Name, + string Author, + string Version, + string Description, + PluginLoadStatus LoadStatus, + string? LoadError, + IReadOnlyDictionary? Settings +); diff --git a/src/Lumina.Contracts/Responses/Plugins/PluginSettingDescriptorResponse.cs b/src/Lumina.Contracts/Responses/Plugins/PluginSettingDescriptorResponse.cs new file mode 100644 index 00000000..1511f604 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Plugins/PluginSettingDescriptorResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +#endregion + +namespace Lumina.Contracts.Responses.Plugins; + +/// +/// Describes a single setting of a plugin. +/// +/// The unique key of the setting. +/// The display label of the setting. +/// The type of the setting. +/// The optional default value of the setting. +/// The list of allowed values, when the setting is a selection. +public sealed record PluginSettingDescriptorResponse( + string Key, + string Label, + PluginSettingType Type, + string? DefaultValue, + IReadOnlyList? AllowedValues +); diff --git a/src/Lumina.Contracts/Responses/Plugins/PluginSettingType.cs b/src/Lumina.Contracts/Responses/Plugins/PluginSettingType.cs new file mode 100644 index 00000000..3b111cfd --- /dev/null +++ b/src/Lumina.Contracts/Responses/Plugins/PluginSettingType.cs @@ -0,0 +1,27 @@ +namespace Lumina.Contracts.Responses.Plugins; + +/// +/// Enumeration for the types of a plugin setting. +/// +public enum PluginSettingType +{ + /// + /// A free-form single line text value. + /// + Text, + + /// + /// A numeric value. + /// + Number, + + /// + /// A boolean (true/false) value. + /// + Boolean, + + /// + /// A value selected from a list of allowed values. + /// + Select +} diff --git a/src/Lumina.Contracts/Responses/Plugins/PluginSettingsResponse.cs b/src/Lumina.Contracts/Responses/Plugins/PluginSettingsResponse.cs new file mode 100644 index 00000000..b9ce52ed --- /dev/null +++ b/src/Lumina.Contracts/Responses/Plugins/PluginSettingsResponse.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Contracts.Responses.Plugins; + +/// +/// Represents the settings of a plugin and their schema. +/// +/// The unique identifier of the plugin. +/// The schema of the plugin settings. +/// The current values of the plugin settings. +public sealed record PluginSettingsResponse( + Guid PluginId, + IReadOnlyList Schema, + IReadOnlyDictionary? Settings +); diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs index 413c36ab..d10992bb 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs @@ -22,5 +22,8 @@ public static partial class ApiRoutes public const string GET_RUNNING_LIBRARIES_SCAN = "/libraries/scans/running"; public const string CANCEL_LIBRARIES_SCAN = "/libraries/scans/cancel"; public const string CANCEL_LIBRARY_SCAN = "/libraries/{libraryId}/scans/{scanId}/cancel"; + public const string GET_LIBRARY_METADATA_PROVIDERS = "/libraries/{libraryId}/metadata-providers"; + public const string SET_LIBRARY_METADATA_PROVIDER_ENABLED = "/libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; + public const string REORDER_LIBRARY_METADATA_PROVIDERS = "/libraries/{libraryId}/metadata-providers/reorder"; } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/Plugins/ApiRoutes.Plugins.cs b/src/Lumina.Presentation.Api/Common/Routes/Plugins/ApiRoutes.Plugins.cs new file mode 100644 index 00000000..4081864a --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Plugins/ApiRoutes.Plugins.cs @@ -0,0 +1,17 @@ +namespace Lumina.Presentation.Api.Common.Routes.Plugins; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Plugins route. + /// + public static class Plugins + { + public const string GET_PLUGINS = "/plugins"; + public const string GET_PLUGIN_SETTINGS = "/plugins/{pluginId}/settings"; + public const string UPDATE_PLUGIN_SETTINGS = "/plugins/{pluginId}/settings"; + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs new file mode 100644 index 00000000..88a9f564 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryMetadataProviders; + +/// +/// API endpoint for the /libraries/{libraryId}/metadata-providers route. +/// +public class GetLibraryMetadataProvidersEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetLibraryMetadataProvidersEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_METADATA_PROVIDERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the metadata providers configured for the media library identified by . + /// + /// The request containing the Id of the media library whose metadata providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryMetadataProvidersRequest request, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointSummary.cs new file mode 100644 index 00000000..258c5b5b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointSummary.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryMetadataProviders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryMetadataProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryMetadataProvidersEndpointSummary() + { + Summary = "Retrieves the metadata providers configured for a media library."; + Description = "Retrieves the metadata providers configured for a media library, with their enabled state and rank."; + + ExampleRequest = new GetLibraryMetadataProvidersRequest( + LibraryId: Guid.NewGuid() + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose metadata providers are retrieved. Required."); + + ResponseParam(r => r.PluginId, "The unique identifier of the plugin providing the metadata."); + ResponseParam(r => r.Name, "The display name of the metadata provider."); + ResponseParam(r => r.IsEnabled, "Whether the metadata provider is enabled for the media library."); + ResponseParam(r => r.Rank, "The rank of the metadata provider, determining the order in which providers are tried."); + + Response(200, "The metadata providers configured for the media library are returned.", + example: new LibraryMetadataProviderResponse[] { + new( + PluginId: Guid.NewGuid(), + Name: "Goodreads", + IsEnabled: true, + Rank: 1 + ), + new( + PluginId: Guid.NewGuid(), + Name: "OpenLibrary", + IsEnabled: false, + Rank: 2 + ) + } + ); + + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/metadata-providers" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/libraries/{libraryId}/metadata-providers" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/metadata-providers" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/metadata-providers", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/metadata-providers", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/metadata-providers", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs new file mode 100644 index 00000000..5171e4e8 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Presentation.Api.Common.Routes.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPluginSettings; + +/// +/// API endpoint for the /plugins/{pluginId}/settings route. +/// +public class GetPluginSettingsEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetPluginSettingsEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Plugins.GET_PLUGIN_SETTINGS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the settings of the plugin identified by and their schema. + /// + /// The request containing the Id of the plugin whose settings are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPluginSettingsRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointSummary.cs new file mode 100644 index 00000000..52505bd9 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointSummary.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPluginSettings; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPluginSettingsEndpointSummary() + { + Summary = "Retrieves the settings of a plugin and their schema."; + Description = "Retrieves the settings of a plugin and their schema, used to render the plugin settings page."; + + ExampleRequest = new GetPluginSettingsRequest( + PluginId: Guid.NewGuid() + ); + + RequestParam(r => r.PluginId, "The unique identifier of the plugin. Required."); + + ResponseParam(r => r.PluginId, "The unique identifier of the plugin."); + ResponseParam(r => r.Schema, "The schema of the plugin settings, used to render the settings form."); + ResponseParam(r => r.Settings, "The current values of the plugin settings."); + + Response(200, "The settings of the plugin and their schema are returned.", example: new PluginSettingsResponse( + PluginId: Guid.NewGuid(), + Schema: + [ + new PluginSettingDescriptorResponse( + Key: "preferredLanguage", + Label: "Preferred Language", + Type: PluginSettingType.Text, + DefaultValue: "en", + AllowedValues: null + ), + new PluginSettingDescriptorResponse( + Key: "selectionStrategy", + Label: "Selection Strategy", + Type: PluginSettingType.Select, + DefaultValue: "first", + AllowedValues: ["first", "best"] + ) + ], + Settings: new Dictionary + { + { "preferredLanguage", "fr" }, + { "selectionStrategy", "first" } + } + )); + + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/plugins/{pluginId}/settings" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/plugins/{pluginId}/settings" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/plugins/{pluginId}/settings" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/plugins/{pluginId}/settings", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested plugin does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PluginNotFound", + instance = "/api/v1/plugins/{pluginId}/settings", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/plugins/{pluginId}/settings", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PluginIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs new file mode 100644 index 00000000..adb03b12 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Core.Plugins.Queries.GetPlugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Presentation.Api.Common.Routes.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPlugins; + +/// +/// API endpoint for the /plugins route. +/// +public class GetPluginsEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetPluginsEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Plugins.GET_PLUGINS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the list of all the detected plugins. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(new GetPluginsQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointSummary.cs new file mode 100644 index 00000000..1f01491e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointSummary.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPlugins; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPluginsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPluginsEndpointSummary() + { + Summary = "Retrieves the list of detected plugins."; + Description = "Retrieves the list of all the plugins detected by the host application, including their load status and settings."; + + ResponseParam(r => r.Id, "The unique identifier of the plugin."); + ResponseParam(r => r.Name, "The display name of the plugin."); + ResponseParam(r => r.Author, "The author of the plugin."); + ResponseParam(r => r.Version, "The version of the plugin."); + ResponseParam(r => r.Description, "The description of the plugin."); + ResponseParam(r => r.LoadStatus, "The load status of the plugin."); + ResponseParam(r => r.LoadError, "The error message when the plugin failed to load, if applicable."); + ResponseParam(r => r.Settings, "The settings of the plugin."); + + Response(200, "The list of detected plugins is returned.", + example: new PluginResponse[] { + new( + Id: Guid.NewGuid(), + Name: "Goodreads", + Author: "Lumina", + Version: "1.0.0", + Description: "Provides book metadata from Goodreads.", + LoadStatus: PluginLoadStatus.Loaded, + LoadError: null, + Settings: new Dictionary + { + { "preferredLanguage", "en" }, + { "selectionStrategy", "first" } + } + ) + } + ); + + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/plugins" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/plugins" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/plugins" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/plugins", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs new file mode 100644 index 00000000..ce196936 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; + +/// +/// API endpoint for the /libraries/{libraryId}/metadata-providers/reorder route. +/// +public class ReorderLibraryMetadataProvidersEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public ReorderLibraryMetadataProvidersEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.PUT); + Routes(ApiRoutes.Libraries.REORDER_LIBRARY_METADATA_PROVIDERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Reorders the metadata providers of the media library identified by . + /// + /// The request containing the Id of the media library and the plugin Ids in the new order. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ReorderLibraryMetadataProvidersRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointSummary.cs new file mode 100644 index 00000000..ac0a841d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointSummary.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryMetadataProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryMetadataProvidersEndpointSummary() + { + Summary = "Reorders the metadata providers of a media library."; + Description = "Reorders the metadata providers of a media library, determining the order in which the providers are tried during the metadata enrichment of the library scans."; + + ExampleRequest = new ReorderLibraryMetadataProvidersRequest( + LibraryId: Guid.NewGuid(), + PluginIds: + [ + Guid.NewGuid(), + Guid.NewGuid() + ] + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose metadata providers are reordered. Required."); + RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); + + Response(200, "The metadata providers of the media library were successfully reordered."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "PluginIdsListCannotBeNull", + "PluginIdsListCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs new file mode 100644 index 00000000..2f4247ad --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; + +/// +/// API endpoint for the /libraries/{libraryId}/metadata-providers/{pluginId}/enabled route. +/// +public class SetLibraryMetadataProviderEnabledEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public SetLibraryMetadataProviderEnabledEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.PUT); + Routes(ApiRoutes.Libraries.SET_LIBRARY_METADATA_PROVIDER_ENABLED); + Version(1); + DontCatchExceptions(); + } + + /// + /// Enables or disables the metadata provider identified by for the media library. + /// + /// The request containing the Ids of the media library and of the metadata provider. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SetLibraryMetadataProviderEnabledRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointSummary.cs new file mode 100644 index 00000000..369b4869 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointSummary.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryMetadataProviderEnabledEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SetLibraryMetadataProviderEnabledEndpointSummary() + { + Summary = "Enables or disables a metadata provider for a media library."; + Description = "Enables or disables the metadata provider for the media library, so that it is included or excluded from the metadata enrichment of the library scans."; + + ExampleRequest = new SetLibraryMetadataProviderEnabledRequest( + LibraryId: Guid.NewGuid(), + PluginId: Guid.NewGuid(), + IsEnabled: true + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose metadata provider is enabled or disabled. Required."); + RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the metadata. Required."); + RequestParam(r => r.IsEnabled, "Whether the metadata provider should be enabled for the media library. Required."); + + Response(200, "The metadata provider was successfully enabled or disabled for the media library."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "PluginIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs new file mode 100644 index 00000000..76cecc8e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Presentation.Api.Common.Routes.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Mediator; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.UpdatePluginSettings; + +/// +/// API endpoint for the /plugins/{pluginId}/settings route. +/// +public class UpdatePluginSettingsEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public UpdatePluginSettingsEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.PUT); + Routes(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the settings of the plugin identified by . + /// + /// The request containing the Id of the plugin and its settings. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdatePluginSettingsRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointSummary.cs new file mode 100644 index 00000000..114bc76a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointSummary.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.UpdatePluginSettings; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePluginSettingsEndpointSummary() + { + Summary = "Updates the settings of a plugin."; + Description = "Updates the settings of a plugin, used by the plugin settings page."; + + ExampleRequest = new UpdatePluginSettingsRequest( + PluginId: Guid.NewGuid(), + Settings: new Dictionary + { + { "preferredLanguage", "fr" }, + { "selectionStrategy", "first" } + } + ); + + RequestParam(r => r.PluginId, "The unique identifier of the plugin. Required."); + RequestParam(r => r.Settings, "The settings of the plugin. Required."); + + Response(200, "The settings of the plugin were successfully updated."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/plugins/{pluginId}/settings" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/plugins/{pluginId}/settings" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/plugins/{pluginId}/settings" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/plugins/{pluginId}/settings", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested plugin does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PluginNotFound", + instance = "/api/v1/plugins/{pluginId}/settings", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/plugins/{pluginId}/settings", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PluginIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs new file mode 100644 index 00000000..96565902 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +public class ReorderLibraryMetadataProvidersCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; + private readonly ReorderLibraryMetadataProvidersCommandHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryMetadataProvidersCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockConfigurationRepository = Substitute.For(); + _mockUnitOfWork.GetRepository().Returns(_mockConfigurationRepository); + _sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockUnitOfWork); + } + + [Fact] + public async Task Handle_WhenCalled_ShouldAssignRanksInTheProvidedOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryMetadataProviderConfigurationEntity firstProvider = CreateConfiguration(libraryId, Guid.NewGuid(), 2); + LibraryMetadataProviderConfigurationEntity secondProvider = CreateConfiguration(libraryId, Guid.NewGuid(), 1); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List { firstProvider, secondProvider }); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + ErrorOr result = await _sut.Handle(new ReorderLibraryMetadataProvidersCommand(libraryId, [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); + + // Assert + Assert.False(result.IsError); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1), + Arg.Any()); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2), + Arg.Any()); + } + + private static LibraryMetadataProviderConfigurationEntity CreateConfiguration(Guid libraryId, Guid pluginId, int rank) + { + return new LibraryMetadataProviderConfigurationEntity + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = true, + Rank = rank, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = default, + UpdatedBy = default + }; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs new file mode 100644 index 00000000..5d5d333c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; + +/// +/// Contains unit tests for the class. +/// +public class SetLibraryMetadataProviderEnabledCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; + private readonly SetLibraryMetadataProviderEnabledCommandHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public SetLibraryMetadataProviderEnabledCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockConfigurationRepository = Substitute.For(); + _mockUnitOfWork.GetRepository().Returns(_mockConfigurationRepository); + _sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockUnitOfWork); + } + + [Fact] + public async Task Handle_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) + .Returns((LibraryMetadataProviderConfigurationEntity?)null); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List()); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + ErrorOr result = await _sut.Handle(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None); + + // Assert + Assert.False(result.IsError); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 1), + Arg.Any()); + } + + [Fact] + public async Task Handle_WhenConfigurationExists_ShouldUpdateItsEnabledState() + { + // Arrange + LibraryMetadataProviderConfigurationEntity existingConfiguration = new() + { + Id = Guid.NewGuid(), + LibraryId = Guid.NewGuid(), + PluginId = Guid.NewGuid(), + IsEnabled = false, + Rank = 2, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = default, + UpdatedBy = default + }; + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any()) + .Returns(existingConfiguration); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + ErrorOr result = await _sut.Handle(new SetLibraryMetadataProviderEnabledCommand(existingConfiguration.LibraryId, existingConfiguration.PluginId, true), CancellationToken.None); + + // Assert + Assert.False(result.IsError); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 2), + Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs new file mode 100644 index 00000000..9cea88b4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.UpdatePluginSettings; + +/// +/// Contains unit tests for the class. +/// +public class UpdatePluginSettingsCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly UpdatePluginSettingsCommandHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public UpdatePluginSettingsCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.GetRepository().Returns(_mockPluginRepository); + _sut = new UpdatePluginSettingsCommandHandler(_mockUnitOfWork); + } + + [Fact] + public async Task Handle_WhenCalled_ShouldPersistTheSettings() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + Dictionary settings = new() { ["preferredLanguage"] = "fr" }; + _mockPluginRepository.UpdateSettingsAsync(pluginId, Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + ErrorOr result = await _sut.Handle(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None); + + // Assert + Assert.False(result.IsError); + await _mockPluginRepository.Received(1).UpdateSettingsAsync(pluginId, Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs new file mode 100644 index 00000000..a619fe08 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Plugins.Queries.GetPlugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetPlugins; + +/// +/// Contains unit tests for the class. +/// +public class GetPluginsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly GetPluginsQueryHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public GetPluginsQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.GetRepository().Returns(_mockPluginRepository); + _sut = new GetPluginsQueryHandler(_mockUnitOfWork); + } + + [Fact] + public async Task Handle_WhenCalled_ShouldReturnAllDetectedPlugins() + { + // Arrange + List plugins = [CreatePluginEntity(), CreatePluginEntity()]; + _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); + + // Act + ErrorOr> result = await _sut.Handle(new GetPluginsQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsError); + Assert.Equal(2, result.Value.Count); + Assert.Equal(plugins[0].Name, result.Value[0].Name); + Assert.Equal(plugins[0].Id, result.Value[0].Id); + } + + [Fact] + public async Task Handle_WhenRepositoryReturnsError_ShouldReturnError() + { + // Arrange + _mockPluginRepository.GetAllAsync(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get plugins")); + + // Act + ErrorOr> result = await _sut.Handle(new GetPluginsQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsError); + } + + private static PluginEntity CreatePluginEntity() + { + return new PluginEntity + { + Id = Guid.NewGuid(), + Name = "Test Plugin", + Author = "Lumina", + Version = "1.0.0", + Description = "A test plugin.", + LoadStatus = PluginLoadStatus.Loaded, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = default, + UpdatedOnUtc = DateTime.UtcNow, + UpdatedBy = default + }; + } +}