diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDto.cs new file mode 100644 index 00000000..cefd576f --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.Management; + +/// +/// Data transfer object for the choice made for one metadata provider, artwork provider or book reader of a media library, carried by the commands that create or update a media library. +/// +/// The Id of the plugin providing the metadata provider, artwork provider or book reader. +/// Whether the provider or reader is enabled for the media library. When absent, the stored state is kept, and a provider or reader without a stored state starts disabled. +[DebuggerDisplay("PluginId: {PluginId}; IsEnabled: {IsEnabled}")] +public record LibraryProviderSelectionDto( + Guid PluginId, + bool? IsEnabled +); diff --git a/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs b/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs index 3f911baa..444cc400 100644 --- a/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs +++ b/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; @@ -11,7 +12,7 @@ using System.Threading.Tasks; namespace Lumina.Application.Common.Infrastructure.Plugins; /// -/// Store of the metadata and artwork provider configurations of the media libraries. +/// Store of the metadata provider, artwork provider and book reader configurations of the media libraries. /// public interface IMediaLibraryProviderConfigurationStore { @@ -24,25 +25,18 @@ public interface IMediaLibraryProviderConfigurationStore Task>> GetConfigurationsAsync(Guid libraryId, CancellationToken cancellationToken); /// - /// Adds a disabled provider configuration for every loaded plugin that supports the provided library type and has no + /// Adds a disabled metadata provider, artwork provider and book reader configuration for every loaded plugin that supports the provided library type and has no /// configuration yet for the media library identified by . /// + /// + /// The added configurations are only staged until the unit of work is saved, and are not visible to a later ensure, so it must be called at most once per media library before the changes are saved. + /// /// The Id of the media library whose provider configurations are ensured. /// The type of the media library, used to determine the plugins whose providers apply. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> EnsureProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); - /// - /// Replaces the provider configurations of the media library identified by so that they - /// match the plugins supporting the provided library type. - /// - /// The Id of the media library whose provider configurations are reconciled. - /// The type of the media library, used to determine the plugins whose providers apply. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> ReconcileProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); - /// /// Deletes all the provider configurations of the media library identified by . /// @@ -60,36 +54,52 @@ public interface IMediaLibraryProviderConfigurationStore Task> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken); /// - /// Adds a disabled book reader configuration for every loaded plugin that supports the provided library type and has no configuration yet, for the media library identified by . + /// Makes the provider and book reader configurations of the media library identified by match the plugins supporting the provided library type, and applies the choices made for them. /// - /// The Id of the media library whose book reader configurations are ensured. - /// The type of the media library, used to determine the plugins whose book readers apply. + /// + /// A list that is provided reconciles that kind of configuration with the library type and applies the choices: the configurations of the plugins that do not support the library type + /// are removed, even when the list does not name them, every supported plugin gets a configuration, and the list sets the enabled state of every provider or reader it names and, for the + /// metadata and artwork providers, their order. A choice without an enabled state keeps the stored state, the supported plugins the list does not name keep their stored state and are + /// ordered after the named ones, and a plugin without a stored configuration starts disabled. A list that is leaves that kind of configuration untouched, unless + /// is , in which case it is reconciled the same way, without choices. Whenever the book reader configurations are + /// reconciled or chosen, the cached reader enablements of the library are dropped. + /// + /// The Id of the media library whose provider and book reader configurations are configured. + /// The type of the media library, used to determine the plugins whose providers and book readers apply. + /// The choices made for the metadata providers, in the order in which they are tried. + /// The choices made for the artwork providers, in the order in which they are tried. + /// The choices made for the book readers. + /// Whether the kinds of configuration whose list of choices is are reconciled with the library type, which is needed when the + /// library is new or its type changed. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> EnsureBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error when a choice names a plugin that does not support the library type. + Task> ConfigureProvidersAsync( + Guid libraryId, + LibraryType libraryType, + IReadOnlyList? metadataProviders, + IReadOnlyList? artworkProviders, + IReadOnlyList? bookReaders, + bool shouldReconcileOmittedKinds, + CancellationToken cancellationToken); /// - /// Replaces the book reader configurations of the media library identified by so that they match the plugins supporting the provided library type. + /// Gets the Ids of the loaded plugins that provide metadata for the provided library type, ordered alphabetically by plugin name. /// - /// The Id of the media library whose book reader configurations are reconciled. - /// The type of the media library, used to determine the plugins whose book readers apply. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> ReconcileBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); + /// The type of the media library the metadata providers must support. + /// The Ids of the plugins providing metadata for the library type. + IReadOnlyList GetSupportedMetadataProviderPluginIds(LibraryType libraryType); /// - /// Deletes all the book reader configurations of the media library identified by . + /// Gets the Ids of the loaded plugins that provide artwork for the provided library type, ordered alphabetically by plugin name. /// - /// The Id of the media library whose book reader configurations are deleted. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> RemoveBookReaderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); + /// The type of the media library the artwork providers must support. + /// The Ids of the plugins providing artwork for the library type. + IReadOnlyList GetSupportedArtworkProviderPluginIds(LibraryType libraryType); /// - /// Deletes all the book reader configurations referencing the plugin identified by . + /// Gets the Ids of the loaded plugins that provide a book reader for the provided library type, ordered alphabetically by plugin name. /// - /// The Id of the plugin whose book reader configurations are deleted. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> RemoveBookReaderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken); + /// The type of the media library the book readers must support. + /// The Ids of the plugins providing a book reader for the library type. + IReadOnlyList GetSupportedBookReaderPluginIds(LibraryType libraryType); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs index 0c62bc02..b9044904 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; using System.Linq; #endregion @@ -15,6 +16,10 @@ public static class AddMediaLibraryRequestMapping /// /// Converts to . /// + /// + /// A path template part that is is converted to a part without a kind, and a provider or book reader choice that is is + /// converted to a choice without a plugin Id, so that the validation of the command reports them, instead of the conversion failing before the command is validated. + /// /// The request to be converted. /// The converted command. public static AddLibraryCommand ToCommand(this AddLibraryRequest request) @@ -32,7 +37,10 @@ public static class AddMediaLibraryRequestMapping request.IsContentOnSsd, request.ShouldTrackConsumptionProgress, request.CompletionThresholdPercentage, - request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part.Kind, part.Representation, part.IsOptional)).ToArray() + request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part?.Kind, part?.Representation, part?.IsOptional ?? false)).ToArray(), + request.MetadataProviders?.Select(provider => new LibraryProviderSelectionDto(provider?.PluginId ?? Guid.Empty, provider?.IsEnabled)).ToArray(), + request.ArtworkProviders?.Select(provider => new LibraryProviderSelectionDto(provider?.PluginId ?? Guid.Empty, provider?.IsEnabled)).ToArray(), + request.BookReaders?.Select(reader => new LibraryProviderSelectionDto(reader?.PluginId ?? Guid.Empty, reader?.IsEnabled)).ToArray() ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs index 6ab4c212..75add9b6 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; using System.Linq; #endregion @@ -15,13 +16,16 @@ public static class UpdateLibraryRequestMapping /// /// Converts to . /// + /// + /// A path template part that is is converted to a part without a kind, and a provider or book reader choice that is is + /// converted to a choice without a plugin Id, so that the validation of the command reports them, instead of the conversion failing before the command is validated. + /// /// The request to be converted. /// The converted command. public static UpdateLibraryCommand ToCommand(this UpdateLibraryRequest request) { return new UpdateLibraryCommand( request.Id, - request.UserId, request.Title, request.LibraryType, request.ContentLocations, @@ -34,7 +38,10 @@ public static class UpdateLibraryRequestMapping request.IsContentOnSsd, request.ShouldTrackConsumptionProgress, request.CompletionThresholdPercentage, - request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part.Kind, part.Representation, part.IsOptional)).ToArray() + request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part?.Kind, part?.Representation, part?.IsOptional ?? false)).ToArray(), + request.MetadataProviders?.Select(provider => new LibraryProviderSelectionDto(provider?.PluginId ?? Guid.Empty, provider?.IsEnabled)).ToArray(), + request.ArtworkProviders?.Select(provider => new LibraryProviderSelectionDto(provider?.PluginId ?? Guid.Empty, provider?.IsEnabled)).ToArray(), + request.BookReaders?.Select(reader => new LibraryProviderSelectionDto(reader?.PluginId ?? Guid.Empty, reader?.IsEnabled)).ToArray() ); } } diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMapping.cs new file mode 100644 index 00000000..73e2945c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryTypeArtworkProvidersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryTypeArtworkProvidersQuery ToQuery(this GetLibraryTypeArtworkProvidersRequest request) + { + return new GetLibraryTypeArtworkProvidersQuery( + request.LibraryType + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMapping.cs new file mode 100644 index 00000000..f299d721 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryTypeBookReadersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryTypeBookReadersQuery ToQuery(this GetLibraryTypeBookReadersRequest request) + { + return new GetLibraryTypeBookReadersQuery( + request.LibraryType + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMapping.cs new file mode 100644 index 00000000..31826085 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryTypeMetadataProvidersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryTypeMetadataProvidersQuery ToQuery(this GetLibraryTypeMetadataProvidersRequest request) + { + return new GetLibraryTypeMetadataProvidersQuery( + request.LibraryType + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs deleted file mode 100644 index 7b0ab2fc..00000000 --- a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs +++ /dev/null @@ -1,25 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Contracts.Requests.Plugins; -#endregion - -namespace Lumina.Application.Common.Mapping.Plugins; - -/// -/// Extension methods for converting . -/// -public static class ReorderLibraryArtworkProvidersRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted command. - public static ReorderLibraryArtworkProvidersCommand ToCommand(this ReorderLibraryArtworkProvidersRequest request) - { - return new ReorderLibraryArtworkProvidersCommand( - LibraryId: request.LibraryId, - PluginIds: request.PluginIds - ); - } -} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMapping.cs deleted file mode 100644 index 6857df1e..00000000 --- a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMapping.cs +++ /dev/null @@ -1,22 +0,0 @@ -#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/SetLibraryArtworkProviderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs deleted file mode 100644 index 4494aeb8..00000000 --- a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs +++ /dev/null @@ -1,26 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Contracts.Requests.Plugins; -#endregion - -namespace Lumina.Application.Common.Mapping.Plugins; - -/// -/// Extension methods for converting . -/// -public static class SetLibraryArtworkProviderEnabledRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted command. - public static SetLibraryArtworkProviderEnabledCommand ToCommand(this SetLibraryArtworkProviderEnabledRequest request) - { - return new SetLibraryArtworkProviderEnabledCommand( - LibraryId: request.LibraryId, - PluginId: request.PluginId, - IsEnabled: request.IsEnabled - ); - } -} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMapping.cs deleted file mode 100644 index 727601ca..00000000 --- a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMapping.cs +++ /dev/null @@ -1,26 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Contracts.Requests.Plugins; -#endregion - -namespace Lumina.Application.Common.Mapping.Plugins; - -/// -/// Extension methods for converting . -/// -public static class SetLibraryBookReaderEnabledRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted command. - public static SetLibraryBookReaderEnabledCommand ToCommand(this SetLibraryBookReaderEnabledRequest request) - { - return new SetLibraryBookReaderEnabledCommand( - request.LibraryId, - request.PluginId, - request.IsEnabled - ); - } -} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMapping.cs deleted file mode 100644 index a0b46032..00000000 --- a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMapping.cs +++ /dev/null @@ -1,22 +0,0 @@ -#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/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs b/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs index b6a46775..dd9a9998 100644 --- a/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs +++ b/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs @@ -4,7 +4,6 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.Favorites; using System; -using System.Linq; #endregion namespace Lumina.Application.Core.Favorites.Commands.RemoveFavorite; @@ -26,9 +25,12 @@ public class RemoveFavoriteCommandValidator : AbstractValidator command.MediaKind) - .Must(mediaKind => Enum.GetNames() - .Where(mediaKindName => !string.Equals(mediaKindName, nameof(FavoriteMediaKind.None), StringComparison.Ordinal)) - .Contains(mediaKind, StringComparer.OrdinalIgnoreCase)) + .IsInEnum() + .When(command => command.MediaKind is not null && command.MediaKind.Length > 0) + .WithError(Errors.Favorites.FavoriteMediaKindIsInvalid); + + RuleFor(command => command.MediaKind) + .Must(mediaKind => !string.Equals(mediaKind, nameof(FavoriteMediaKind.None), StringComparison.OrdinalIgnoreCase)) .When(command => command.MediaKind is not null && command.MediaKind.Length > 0) .WithError(Errors.Favorites.FavoriteMediaKindIsInvalid); diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs index f12a2dab..d39cfe27 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs @@ -4,7 +4,6 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; -using System.Linq; #endregion namespace Lumina.Application.Core.MediaConsumption.Commands.StartConsumption; @@ -35,7 +34,7 @@ public class StartConsumptionCommandValidator : AbstractValidator command.MediaKind) - .Must(mediaKind => Enum.GetNames().Contains(mediaKind, StringComparer.OrdinalIgnoreCase)) + .IsInEnum() .When(command => command.MediaKind is not null && command.MediaKind.Length > 0) .WithError(Errors.MediaConsumption.UnsupportedMediaKind); diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs index 389ae690..64fbe268 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs @@ -4,7 +4,6 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; -using System.Linq; #endregion namespace Lumina.Application.Core.MediaConsumption.Queries.GetResumePoint; @@ -25,7 +24,7 @@ public class GetResumePointQueryValidator : AbstractValidator query.MediaKind) - .Must(mediaKind => Enum.GetNames().Contains(mediaKind, StringComparer.OrdinalIgnoreCase)) + .IsInEnum() .When(query => query.MediaKind is not null && query.MediaKind.Length > 0) .WithError(Errors.MediaConsumption.UnsupportedMediaKind); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs index 6b013e07..92600e28 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs @@ -22,6 +22,9 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; /// Whether the consumption progress of the media library items should be tracked, or not. When absent, the default of the library type is used. /// The percentage of a media library item that must be consumed for its session to be considered completed. When absent, the default of the library type is used on creation. /// The ordered parts of the template describing the structure of the media library on disk. +/// The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, every provider supported by the library type is added disabled. +/// The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, every provider supported by the library type is added disabled. +/// The book readers of the media library, and whether each one is enabled. When absent, every reader supported by the library type is added disabled. [DebuggerDisplay("Title: {Title}")] public record AddLibraryCommand( string? Title, @@ -36,5 +39,8 @@ public record AddLibraryCommand( bool IsContentOnSsd, bool? ShouldTrackConsumptionProgress, int? CompletionThresholdPercentage, - LibraryPathTemplatePartDto[]? PathTemplateParts + LibraryPathTemplatePartDto[]? PathTemplateParts, + LibraryProviderSelectionDto[]? MetadataProviders, + LibraryProviderSelectionDto[]? ArtworkProviders, + LibraryProviderSelectionDto[]? BookReaders ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 1a4cf50b..2f6232dd 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -114,7 +114,7 @@ public class AddLibraryCommandHandler : ICommandHandler(command.LibraryType!); + LibraryType libraryType = Enum.Parse(command.LibraryType!, ignoreCase: true); // A library created without explicit consumption settings uses the defaults of its type. When progress tracking is on and no threshold is // supplied, the default threshold of the type is used; a type without one keeps no threshold, which means completion is recorded explicitly. @@ -158,15 +158,15 @@ public class AddLibraryCommandHandler : ICommandHandler insertLibraryResult = await _unitOfWork.LibraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (insertLibraryResult.IsFailure) return insertLibraryResult.Errors; - Result ensureProviderConfigurationsResult = await _providerConfigurationStore.EnsureProviderConfigurationsAsync( - createLibraryResult.Value.Id.Value, libraryType, cancellationToken).ConfigureAwait(false); - if (ensureProviderConfigurationsResult.IsFailure) - return ensureProviderConfigurationsResult.Errors; + Result configureProvidersResult = await _providerConfigurationStore.ConfigureProvidersAsync( + createLibraryResult.Value.Id.Value, libraryType, command.MetadataProviders, command.ArtworkProviders, command.BookReaders, shouldReconcileOmittedKinds: true, cancellationToken).ConfigureAwait(false); + if (configureProvidersResult.IsFailure) + return configureProvidersResult.Errors; Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveChangesResult.IsFailure) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs index d5974c69..beb7f1c6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Errors; using System; +using System.Linq; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; @@ -21,7 +22,7 @@ public class AddLibraryCommandValidator : AbstractValidator RuleFor(command => command.LibraryType) .NotNull() .WithError(Errors.Library.LibraryTypeCannotBeNull) - .Must(libraryType => Enum.TryParse(libraryType, out _)) + .IsInEnum() .WithError(Errors.Library.UnknownLibraryType); RuleFor(command => command.ContentLocations) @@ -61,5 +62,32 @@ public class AddLibraryCommandValidator : AbstractValidator .When(pathPart => !string.Equals(pathPart.Kind, nameof(LibraryPathPartKind.Separator), StringComparison.OrdinalIgnoreCase)) .WithError(Errors.Library.PathTemplateLiteralCannotBeEmpty); }); + + RuleForEach(command => command.MetadataProviders) + .ChildRules(provider => provider.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.MetadataProviders) + .Must(providers => providers is null || providers.Select(selection => selection.PluginId).Distinct().Count() == providers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); + + RuleForEach(command => command.ArtworkProviders) + .ChildRules(provider => provider.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.ArtworkProviders) + .Must(providers => providers is null || providers.Select(selection => selection.PluginId).Distinct().Count() == providers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); + + RuleForEach(command => command.BookReaders) + .ChildRules(reader => reader.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.BookReaders) + .Must(readers => readers is null || readers.Select(selection => selection.PluginId).Distinct().Count() == readers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs index ae7b4e06..81572f86 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs @@ -13,6 +13,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using System; using System.Collections.Generic; using System.Threading; @@ -85,10 +86,12 @@ public class DeleteLibraryCommandHandler : ICommandHandler( - userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) + // Admins can delete any library. Everyone else can only delete the libraries they own, and only while they hold the permission to manage media + // libraries, which can be withheld to keep a user from deleting even the libraries they own. + if (!await _authorizationService.EvaluatePolicyAsync(userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false) && + !await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false)) return ApplicationErrors.Authorization.NotAuthorized; // Create a domain library object. diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs index 66819bd4..5ad99baf 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs @@ -11,7 +11,6 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary /// Command for updating a media library. /// /// The unique identifier of the media library. -/// The unique identifier of the user owning the media library. /// The title of the media library. /// The type of the media library. /// The file system paths of the directories where the media library elements are located. @@ -25,10 +24,12 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary /// Whether the consumption progress of the media library items should be tracked, or not. When absent, the stored value is kept. /// The percentage of a media library item that must be consumed for its session to be considered completed. When absent, the stored value is kept. /// The ordered parts of the template describing the structure of the media library on disk. +/// The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, the stored configurations are kept, or reconciled with the library type when it changes. +/// The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, the stored configurations are kept, or reconciled with the library type when it changes. +/// The book readers of the media library, and whether each one is enabled. When absent, the stored configurations are kept, or reconciled with the library type when it changes. [DebuggerDisplay("Title: {Title}")] public record UpdateLibraryCommand( Guid Id, - Guid OwnerId, string? Title, string? LibraryType, string[]? ContentLocations, @@ -41,5 +42,8 @@ public record UpdateLibraryCommand( bool IsContentOnSsd, bool? ShouldTrackConsumptionProgress, int? CompletionThresholdPercentage, - LibraryPathTemplatePartDto[]? PathTemplateParts + LibraryPathTemplatePartDto[]? PathTemplateParts, + LibraryProviderSelectionDto[]? MetadataProviders, + LibraryProviderSelectionDto[]? ArtworkProviders, + LibraryProviderSelectionDto[]? BookReaders ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index b77a417c..84209f82 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -105,6 +105,16 @@ public class UpdateLibraryCommandHandler : ICommandHandler(userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false) && + !await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + bool hasProviderChoices = command.MetadataProviders is not null || command.ArtworkProviders is not null || command.BookReaders is not null; + // Make sure the file is an actual supported image, but only when a new cover image was chosen; the stored cover image is // relative to the application base directory and is already validated, so it must not block saving unrelated changes. if (command.CoverImage is not null && command.CoverImage != getLibraryResult.Value.CoverImage) @@ -120,15 +130,8 @@ public class UpdateLibraryCommandHandler : ICommandHandler( - userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false); - if (!hasManagePermission && !canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - // Create a domain library object. - LibraryType newLibraryType = Enum.Parse(command.LibraryType!); + LibraryType newLibraryType = Enum.Parse(command.LibraryType!, ignoreCase: true); // Keep the stored consumption settings unless the request explicitly changes them. When progress tracking is enabled and // no threshold is supplied, the stored threshold is kept; the value object never retains a threshold while tracking is disabled. @@ -157,9 +160,10 @@ public class UpdateLibraryCommandHandler : ICommandHandler createLibraryResult = Library.Create( LibraryId.Create(command.Id), - UserId.Create(command.OwnerId), + UserId.Create(getLibraryResult.Value.UserId), command.Title!, newLibraryType, command.ContentLocations!, @@ -179,16 +183,19 @@ public class UpdateLibraryCommandHandler : ICommandHandler updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (updateLibraryResult.IsFailure) return updateLibraryResult.Errors; - if (getLibraryResult.Value.LibraryType != newLibraryType) + bool isLibraryTypeChanged = getLibraryResult.Value.LibraryType != newLibraryType; + if (isLibraryTypeChanged || hasProviderChoices) { - Result reconcileResult = await _providerConfigurationStore.ReconcileProviderConfigurationsAsync(command.Id, newLibraryType, cancellationToken).ConfigureAwait(false); - if (reconcileResult.IsFailure) - return reconcileResult.Errors; + Result configureProvidersResult = await _providerConfigurationStore.ConfigureProvidersAsync( + command.Id, newLibraryType, command.MetadataProviders, command.ArtworkProviders, command.BookReaders, isLibraryTypeChanged, cancellationToken).ConfigureAwait(false); + if (configureProvidersResult.IsFailure) + return configureProvidersResult.Errors; } Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveChangesResult.IsFailure) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs index d0a2c721..70d8deff 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Errors; using System; +using System.Linq; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; @@ -24,16 +25,10 @@ public class UpdateLibraryCommandValidator : AbstractValidator id != Guid.Empty) .WithError(Errors.Library.LibraryIdCannotBeEmpty); - RuleFor(command => command.OwnerId) - .NotEmpty() - .WithError(Errors.Users.UserIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Users.UserIdCannotBeEmpty); - RuleFor(command => command.LibraryType) .NotNull() .WithError(Errors.Library.LibraryTypeCannotBeNull) - .Must(libraryType => Enum.TryParse(libraryType, out _)) + .IsInEnum() .WithError(Errors.Library.UnknownLibraryType); RuleFor(command => command.ContentLocations) @@ -73,5 +68,32 @@ public class UpdateLibraryCommandValidator : AbstractValidator !string.Equals(pathPart.Kind, nameof(LibraryPathPartKind.Separator), StringComparison.OrdinalIgnoreCase)) .WithError(Errors.Library.PathTemplateLiteralCannotBeEmpty); }); + + RuleForEach(command => command.MetadataProviders) + .ChildRules(provider => provider.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.MetadataProviders) + .Must(providers => providers is null || providers.Select(selection => selection.PluginId).Distinct().Count() == providers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); + + RuleForEach(command => command.ArtworkProviders) + .ChildRules(provider => provider.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.ArtworkProviders) + .Must(providers => providers is null || providers.Select(selection => selection.PluginId).Distinct().Count() == providers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); + + RuleForEach(command => command.BookReaders) + .ChildRules(reader => reader.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.BookReaders) + .Must(readers => readers is null || readers.Select(selection => selection.PluginId).Distinct().Count() == readers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs index ac64fcec..b39ec76d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs @@ -41,19 +41,19 @@ public class GetLibraryPathTemplatePartsQueryHandler : IQueryHandler public Task> HandleAsync(GetLibraryPathTemplatePartsQuery query, CancellationToken cancellationToken) { - // the library type travels as a string taken from the route, and is matched against the enum the same way the create and update + // The library type travels as a string taken from the route, and is matched against the enum the same way the create and update // library commands do, so that a malformed type is reported as an unknown library type instead of silently returning an empty catalog. - if (!Enum.TryParse(query.LibraryType, ignoreCase: true, out LibraryType libraryType)) + if (!Enum.TryParse(query.LibraryType, ignoreCase: true, out LibraryType libraryType) || !Enum.IsDefined(libraryType)) return Task.FromResult>(DomainErrors.Library.UnknownLibraryType); - // only the catalog registered for the requested library type applies, so the parts and the default structure offered to the user are + // Only the catalog registered for the requested library type applies, so the parts and the default structure offered to the user are // type aware (music libraries get artist and release parts, book libraries get author and title parts, and so on). ILibraryPathPartCatalog? catalog = _catalogs.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); if (catalog is null) - // a library type without a catalog has no structure to describe, so an empty catalog is returned, which the client uses to hide the editor. + // A library type without a catalog has no structure to describe, so an empty catalog is returned, which the client uses to hide the editor. return Task.FromResult(Result.Success(new LibraryPathTemplateCatalogResponse([], []))); - // the selectable parts describe what the user can drop into the template, together with the value type and the default on-disk representation of each part. + // The selectable parts describe what the user can drop into the template, together with the value type and the default on-disk representation of each part. List parts = [ .. catalog.GetPartDefinitions().Select(definition => new LibraryPathPartDefinitionResponse( @@ -62,7 +62,7 @@ public class GetLibraryPathTemplatePartsQueryHandler : IQueryHandler defaultTemplateParts = [ .. catalog.GetDefaultTemplate().Parts.Select(part => new LibraryPathTemplatePartResponse(part.Kind.ToString(), part.Representation, part.IsOptional)) diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs deleted file mode 100644 index a202a355..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using System; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; - -/// -/// Command for reordering the artwork providers of a media library. -/// -/// The Id of the media library whose artwork providers are reordered. -/// The plugin Ids in the new order, from highest to lowest rank. -public record ReorderLibraryArtworkProvidersCommand( - Guid LibraryId, - IReadOnlyList PluginIds -) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs deleted file mode 100644 index 8c713a6b..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs +++ /dev/null @@ -1,98 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Validation; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; - -/// -/// Handler for the command to reorder the artwork providers of a media library. -/// -public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IAuthorizationService _authorizationService; - private readonly ICurrentUserService _currentUserService; - private readonly IValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for authorization related functionality. - /// Injected service to retrieve the current user information. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected validator for application validation rules. - public ReorderLibraryArtworkProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) - { - _authorizationService = authorizationService; - _currentUserService = currentUserService; - _unitOfWork = unitOfWork; - _validator = validator; - } - - /// - /// Handles the command to reorder the artwork providers of a media library. - /// - /// The request to be handled. - /// Cancellation token that can be used to stop the execution. - /// - /// An representing either a successful operation, or an error. - /// - public async Task> HandleAsync(ReorderLibraryArtworkProvidersCommand command, CancellationToken cancellationToken) - { - List validationResult = _validator.Validate(command); - if (validationResult.Count > 0) - return validationResult; - - // An authenticated request must always carry a user identity. - Guid? currentUserId = _currentUserService.UserId; - if (currentUserId is null) - return ApplicationErrors.Authorization.NotAuthorized; - Guid userId = currentUserId.Value; - - // Admins can reorder the artwork providers of any library; for everyone else, only their own libraries. - bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - - // Load the artwork provider configurations that are currently registered for the library, so that only providers it actually has are reordered. - Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsFailure) - return getConfigurationsResult.Errors; - - // Index the configurations by plugin id, so that each requested plugin can be matched without repeatedly searching the list. - Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); - // Walk the requested order and assign each provider the 1-based rank that matches its position in the command, so the persisted order follows the user's choice. - for (int rank = 0; rank < command.PluginIds.Count; rank++) - { - Guid pluginId = command.PluginIds[rank]; - if (configurationsByPluginId.TryGetValue(pluginId, out LibraryArtworkProviderConfigurationEntity? configuration)) - { - configuration.Rank = rank + 1; - Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - return upsertResult.Errors; - } - } - - // Persist all the rank changes in a single save, so that the reorder is applied atomically. - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - return Result.Success; - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs deleted file mode 100644 index 770f3f31..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Common.Utilities; -using Lumina.Domain.Common.Errors; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; - -/// -/// Validates the needed validation rules for . -/// -public class ReorderLibraryArtworkProvidersCommandValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryArtworkProvidersCommandValidator() - { - RuleFor(command => command.LibraryId) - .NotEmpty() - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); - - RuleFor(command => command.PluginIds) - .NotNull() - .WithError(Errors.Plugins.PluginIdsListCannotBeNull) - .NotEmpty() - .WithError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs deleted file mode 100644 index a1ab58c2..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -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 -) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs deleted file mode 100644 index 3b3133c8..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs +++ /dev/null @@ -1,97 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; - -/// -/// Handler for the command to reorder the metadata providers of a media library. -/// -public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IAuthorizationService _authorizationService; - private readonly ICurrentUserService _currentUserService; - private readonly IValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for authorization related functionality. - /// Injected service to retrieve the current user information. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected validator for application validation rules. - public ReorderLibraryMetadataProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) - { - _authorizationService = authorizationService; - _currentUserService = currentUserService; - _unitOfWork = unitOfWork; - _validator = validator; - } - - /// - /// 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 Task> HandleAsync(ReorderLibraryMetadataProvidersCommand command, CancellationToken cancellationToken) - { - List validationResult = _validator.Validate(command); - if (validationResult.Count > 0) - return validationResult; - - // An authenticated request must always carry a user identity. - Guid? currentUserId = _currentUserService.UserId; - if (currentUserId is null) - return ApplicationErrors.Authorization.NotAuthorized; - Guid userId = currentUserId.Value; - - // Admins can reorder the metadata providers of any library; for everyone else, only their own libraries. - bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - - // Load the metadata provider configurations that are currently registered for the library, so that only providers it actually has are reordered. - Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsFailure) - return getConfigurationsResult.Errors; - - // Index the configurations by plugin id, so that each requested plugin can be matched without repeatedly searching the list. - Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); - // Walk the requested order and assign each provider the 1-based rank that matches its position in the command, so the persisted order follows the user's choice. - for (int rank = 0; rank < command.PluginIds.Count; rank++) - { - Guid pluginId = command.PluginIds[rank]; - if (configurationsByPluginId.TryGetValue(pluginId, out LibraryMetadataProviderConfigurationEntity? configuration)) - { - configuration.Rank = rank + 1; - Result upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - return upsertResult.Errors; - } - } - - // Persist all the rank changes in a single save, so that the reorder is applied atomically. - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - 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 deleted file mode 100644 index 95c01884..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Common.Utilities; -using Lumina.Domain.Common.Errors; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; - -/// -/// Validates the needed validation rules for . -/// -public class ReorderLibraryMetadataProvidersCommandValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryMetadataProvidersCommandValidator() - { - RuleFor(command => command.LibraryId) - .NotEmpty() - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); - - RuleFor(command => command.PluginIds) - .NotNull() - .WithError(Errors.Plugins.PluginIdsListCannotBeNull) - .NotEmpty() - .WithError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs deleted file mode 100644 index e4acf111..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Command for enabling or disabling an artwork provider for a media library. -/// -/// The Id of the media library whose artwork provider is enabled or disabled. -/// The unique identifier of the plugin providing the artwork. -/// Whether the artwork provider should be enabled for the media library. -public record SetLibraryArtworkProviderEnabledCommand( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs deleted file mode 100644 index 09b304db..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs +++ /dev/null @@ -1,113 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Handler for the command to enable or disable an artwork provider for a media library. -/// -public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IAuthorizationService _authorizationService; - private readonly ICurrentUserService _currentUserService; - private readonly IValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for authorization related functionality. - /// Injected service to retrieve the current user information. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected validator for application validation rules. - public SetLibraryArtworkProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) - { - _authorizationService = authorizationService; - _currentUserService = currentUserService; - _unitOfWork = unitOfWork; - _validator = validator; - } - - /// - /// Handles the command to enable or disable an artwork provider for a media library. - /// - /// The request to be handled. - /// Cancellation token that can be used to stop the execution. - /// - /// An representing either a successful operation, or an error. - /// - public async Task> HandleAsync(SetLibraryArtworkProviderEnabledCommand command, CancellationToken cancellationToken) - { - List validationResult = _validator.Validate(command); - if (validationResult.Count > 0) - return validationResult; - - // An authenticated request must always carry a user identity. - Guid? currentUserId = _currentUserService.UserId; - if (currentUserId is null) - return ApplicationErrors.Authorization.NotAuthorized; - Guid userId = currentUserId.Value; - - // Admins can configure the artwork providers of any library; for everyone else, only their own libraries. - bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - - // Look up the configuration of this provider for the library, so that an existing one is toggled instead of duplicated. - Result getConfigurationResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); - if (getConfigurationResult.IsFailure) - return getConfigurationResult.Errors; - - LibraryArtworkProviderConfigurationEntity configuration; - if (getConfigurationResult.Value is not null) - { - // The provider is already configured for the library, so only its enabled state changes, keeping its existing rank in the display order. - configuration = getConfigurationResult.Value; - configuration.IsEnabled = command.IsEnabled; - } - else - { - // Compute the rank to assign to the new configuration, appending it after the existing ones. - Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsFailure) - return getConfigurationsResult.Errors; - int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; - configuration = new LibraryArtworkProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = command.LibraryId, - PluginId = command.PluginId, - IsEnabled = command.IsEnabled, - Rank = nextRank, - CreatedOnUtc = default, - CreatedBy = default, - UpdatedBy = default - }; - } - - // Insert the new configuration, or update the existing one, and persist the change. - Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - return upsertResult.Errors; - - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - return Result.Success; - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs deleted file mode 100644 index 040a486f..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Common.Utilities; -using Lumina.Domain.Common.Errors; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Validates the needed validation rules for . -/// -public class SetLibraryArtworkProviderEnabledCommandValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryArtworkProviderEnabledCommandValidator() - { - RuleFor(command => command.LibraryId) - .NotEmpty() - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); - - RuleFor(command => command.PluginId) - .NotEmpty() - .WithError(Errors.Plugins.PluginIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.PluginIdCannotBeEmpty); - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommand.cs deleted file mode 100644 index a40b4e93..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommand.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Command for enabling or disabling a book reader for a media library. -/// -/// The Id of the media library whose book reader is enabled or disabled. -/// The unique identifier of the plugin providing the book reader. -/// Whether the book reader should be enabled for the media library. -public record SetLibraryBookReaderEnabledCommand( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs deleted file mode 100644 index 6ff5d6c9..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs +++ /dev/null @@ -1,108 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Reading; -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Handler for the command to enable or disable a book reader for a media library. -/// -public class SetLibraryBookReaderEnabledCommandHandler : ICommandHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IAuthorizationService _authorizationService; - private readonly ICurrentUserService _currentUserService; - private readonly IBookReaderEnablementCache _enablementCache; - private readonly IValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for authorization related functionality. - /// Injected service to retrieve the current user information. - /// Injected cache of whether the book reader of a plugin is enabled for a media library. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected validator for application validation rules. - public SetLibraryBookReaderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReaderEnablementCache enablementCache, IUnitOfWork unitOfWork, IValidator validator) - { - _authorizationService = authorizationService; - _currentUserService = currentUserService; - _enablementCache = enablementCache; - _unitOfWork = unitOfWork; - _validator = validator; - } - - /// - /// Handles the command to enable or disable a book reader for a media library. - /// - /// The request to be handled. - /// Cancellation token that can be used to stop the execution. - /// - /// An representing either a successful operation, or an error. - /// - public async Task> HandleAsync(SetLibraryBookReaderEnabledCommand command, CancellationToken cancellationToken) - { - List validationResult = _validator.Validate(command); - if (validationResult.Count > 0) - return validationResult; - - // An authenticated request must always carry a user identity. - Guid? currentUserId = _currentUserService.UserId; - if (currentUserId is null) - return ApplicationErrors.Authorization.NotAuthorized; - Guid userId = currentUserId.Value; - - // Admins can configure the book readers of any library; for everyone else, only their own libraries. - bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - - Result getConfigurationResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); - if (getConfigurationResult.IsFailure) - return getConfigurationResult.Errors; - - LibraryBookReaderConfigurationEntity configuration; - if (getConfigurationResult.Value is not null) - { - configuration = getConfigurationResult.Value; - configuration.IsEnabled = command.IsEnabled; - } - else - { - configuration = new LibraryBookReaderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = command.LibraryId, - PluginId = command.PluginId, - IsEnabled = command.IsEnabled, - CreatedOnUtc = default, - CreatedBy = default, - UpdatedBy = default - }; - } - - Result upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - return upsertResult.Errors; - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - // The reading service caches the enablement of a reader, because it consults it on every request; the cache is invalidated here, - // so that disabling a reader cuts access to its books immediately, without waiting for the cache to expire. - _enablementCache.Invalidate(command.LibraryId, command.PluginId); - return Result.Success; - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidator.cs deleted file mode 100644 index 1178b5f9..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidator.cs +++ /dev/null @@ -1,28 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Common.Utilities; -using Lumina.Domain.Common.Errors; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Validates the needed validation rules for . -/// -public class SetLibraryBookReaderEnabledCommandValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryBookReaderEnabledCommandValidator() - { - RuleFor(command => command.LibraryId) - .NotEmpty() - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); - - RuleFor(command => command.PluginId) - .NotEmpty() - .WithError(Errors.Plugins.PluginIdCannotBeEmpty); - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs deleted file mode 100644 index c81174c5..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -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 -) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs deleted file mode 100644 index 526852b2..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs +++ /dev/null @@ -1,113 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; - -/// -/// Handler for the command to enable or disable a metadata provider for a media library. -/// -public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IAuthorizationService _authorizationService; - private readonly ICurrentUserService _currentUserService; - private readonly IValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for authorization related functionality. - /// Injected service to retrieve the current user information. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected validator for application validation rules. - public SetLibraryMetadataProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) - { - _authorizationService = authorizationService; - _currentUserService = currentUserService; - _unitOfWork = unitOfWork; - _validator = validator; - } - - /// - /// 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 Task> HandleAsync(SetLibraryMetadataProviderEnabledCommand command, CancellationToken cancellationToken) - { - List validationResult = _validator.Validate(command); - if (validationResult.Count > 0) - return validationResult; - - // An authenticated request must always carry a user identity. - Guid? currentUserId = _currentUserService.UserId; - if (currentUserId is null) - return ApplicationErrors.Authorization.NotAuthorized; - Guid userId = currentUserId.Value; - - // Admins can configure the metadata providers of any library; for everyone else, only their own libraries. - bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - - // Look up the configuration of this provider for the library, so that an existing one is toggled instead of duplicated. - Result getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); - if (getConfigurationResult.IsFailure) - return getConfigurationResult.Errors; - - LibraryMetadataProviderConfigurationEntity configuration; - if (getConfigurationResult.Value is not null) - { - // The provider is already configured for the library, so only its enabled state changes, keeping its existing rank in the display order. - configuration = getConfigurationResult.Value; - configuration.IsEnabled = command.IsEnabled; - } - else - { - // Compute the rank to assign to the new configuration, appending it after the existing ones. - Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsFailure) - return getConfigurationsResult.Errors; - int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; - configuration = new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = command.LibraryId, - PluginId = command.PluginId, - IsEnabled = command.IsEnabled, - Rank = nextRank, - CreatedOnUtc = default, - CreatedBy = default, - UpdatedBy = default - }; - } - - // Insert the new configuration, or update the existing one, and persist the change. - Result upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - return upsertResult.Errors; - - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - 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 deleted file mode 100644 index b910702f..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Common.Utilities; -using Lumina.Domain.Common.Errors; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; - -/// -/// Validates the needed validation rules for . -/// -public class SetLibraryMetadataProviderEnabledCommandValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryMetadataProviderEnabledCommandValidator() - { - RuleFor(command => command.LibraryId) - .NotEmpty() - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); - - RuleFor(command => command.PluginId) - .NotEmpty() - .WithError(Errors.Plugins.PluginIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.PluginIdCannotBeEmpty); - } -} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQuery.cs new file mode 100644 index 00000000..ed2691f7 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Query for getting the artwork providers available for a media library type. +/// +/// The media library type whose available artwork providers are retrieved. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeArtworkProvidersQuery( + string? LibraryType +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandler.cs new file mode 100644 index 00000000..92cfe456 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandler.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Handler for the query to get the artwork providers available for a media library type. +/// +public class GetLibraryTypeArtworkProvidersQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected store of the provider configurations of the media libraries. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public GetLibraryTypeArtworkProvidersQueryHandler(ICurrentUserService currentUserService, IMediaLibraryProviderConfigurationStore providerConfigurationStore, IUnitOfWork unitOfWork, IValidator validator) + { + _currentUserService = currentUserService; + _providerConfigurationStore = providerConfigurationStore; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the query to get the artwork providers available for a media library type. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async Task>> HandleAsync(GetLibraryTypeArtworkProvidersQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + if (_currentUserService.UserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + + LibraryType libraryType = Enum.Parse(query.LibraryType!, ignoreCase: true); + + // Build a plugin name lookup from the detected plugins, so that each provider is returned with its display name. + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsFailure) + return getPluginsResult.Errors; + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + + // The providers are returned the way a new media library of this type is configured with them: disabled, and ranked in alphabetical order. + IReadOnlyList pluginIds = _providerConfigurationStore.GetSupportedArtworkProviderPluginIds(libraryType); + return pluginIds + .Select((pluginId, index) => new LibraryArtworkProviderResponse(pluginId, pluginNames.GetValueOrDefault(pluginId) ?? string.Empty, IsEnabled: false, Rank: index + 1)) + .ToList(); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidator.cs new file mode 100644 index 00000000..53f53134 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryTypeArtworkProvidersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersQueryValidator() + { + RuleFor(query => query.LibraryType) + .NotNull() + .WithError(Errors.Library.LibraryTypeCannotBeNull) + .IsInEnum() + .WithError(Errors.Library.UnknownLibraryType); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQuery.cs new file mode 100644 index 00000000..aa64b3e8 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Query for getting the book readers available for a media library type. +/// +/// The media library type whose available book readers are retrieved. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeBookReadersQuery( + string? LibraryType +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandler.cs new file mode 100644 index 00000000..1b6fd722 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandler.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Reading; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Handler for the query to get the book readers available for a media library type. +/// +public class GetLibraryTypeBookReadersQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore; + private readonly IBookReaderRegistry _bookReaderRegistry; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected store of the provider configurations of the media libraries. + /// Injected registry of the book readers provided by the loaded plugins. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public GetLibraryTypeBookReadersQueryHandler(ICurrentUserService currentUserService, IMediaLibraryProviderConfigurationStore providerConfigurationStore, IBookReaderRegistry bookReaderRegistry, IUnitOfWork unitOfWork, IValidator validator) + { + _currentUserService = currentUserService; + _providerConfigurationStore = providerConfigurationStore; + _bookReaderRegistry = bookReaderRegistry; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the query to get the book readers available for a media library type. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async Task>> HandleAsync(GetLibraryTypeBookReadersQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + if (_currentUserService.UserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + + LibraryType libraryType = Enum.Parse(query.LibraryType!, ignoreCase: true); + + // Build a plugin name lookup from the detected plugins, so that each reader is returned with its display name. + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsFailure) + return getPluginsResult.Errors; + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + + IReadOnlyDictionary> supportedExtensionsByPluginId = _bookReaderRegistry.GetSupportedExtensionsByPluginId(); + + // The readers are returned the way a new media library of this type is configured with them: disabled, in alphabetical order. + IReadOnlyList pluginIds = _providerConfigurationStore.GetSupportedBookReaderPluginIds(libraryType); + return pluginIds + .Select(pluginId => new LibraryBookReaderResponse( + pluginId, + pluginNames.GetValueOrDefault(pluginId) ?? string.Empty, + supportedExtensionsByPluginId.GetValueOrDefault(pluginId) ?? [], + IsEnabled: false)) + .ToList(); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidator.cs new file mode 100644 index 00000000..eed752b0 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryTypeBookReadersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersQueryValidator() + { + RuleFor(query => query.LibraryType) + .NotNull() + .WithError(Errors.Library.LibraryTypeCannotBeNull) + .IsInEnum() + .WithError(Errors.Library.UnknownLibraryType); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQuery.cs new file mode 100644 index 00000000..a7e250c2 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Query for getting the metadata providers available for a media library type. +/// +/// The media library type whose available metadata providers are retrieved. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeMetadataProvidersQuery( + string? LibraryType +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandler.cs new file mode 100644 index 00000000..3b867d57 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandler.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Handler for the query to get the metadata providers available for a media library type. +/// +public class GetLibraryTypeMetadataProvidersQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected store of the provider configurations of the media libraries. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public GetLibraryTypeMetadataProvidersQueryHandler(ICurrentUserService currentUserService, IMediaLibraryProviderConfigurationStore providerConfigurationStore, IUnitOfWork unitOfWork, IValidator validator) + { + _currentUserService = currentUserService; + _providerConfigurationStore = providerConfigurationStore; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the query to get the metadata providers available for a media library type. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async Task>> HandleAsync(GetLibraryTypeMetadataProvidersQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + if (_currentUserService.UserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + + LibraryType libraryType = Enum.Parse(query.LibraryType!, ignoreCase: true); + + // Build a plugin name lookup from the detected plugins, so that each provider is returned with its display name. + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsFailure) + return getPluginsResult.Errors; + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + + // The providers are returned the way a new media library of this type is configured with them: disabled, and ranked in alphabetical order. + IReadOnlyList pluginIds = _providerConfigurationStore.GetSupportedMetadataProviderPluginIds(libraryType); + return pluginIds + .Select((pluginId, index) => new LibraryMetadataProviderResponse(pluginId, pluginNames.GetValueOrDefault(pluginId) ?? string.Empty, IsEnabled: false, Rank: index + 1)) + .ToList(); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidator.cs new file mode 100644 index 00000000..c727f952 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryTypeMetadataProvidersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersQueryValidator() + { + RuleFor(query => query.LibraryType) + .NotNull() + .WithError(Errors.Library.LibraryTypeCannotBeNull) + .IsInEnum() + .WithError(Errors.Library.UnknownLibraryType); + } +} diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs index 6daf08ed..0a755dd6 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs @@ -11,15 +11,18 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// The type of the media library. Required. /// The file system paths of the directories where the media library elements are located. Required. /// The path of the image file used as the cover for the library. Optional. -/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional. -/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional. -/// Whether this media library should update the metadata of its elements from the web, or not. Optional. -/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional. -/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. -/// Whether the content of this media library is stored on a solid state drive, in which case the file discovery and content hashing stages read the files in parallel. Optional. +/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Required. +/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Required. +/// Whether this media library should update the metadata of its elements from the web, or not. Required. +/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Required. +/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Required. +/// Whether the content of this media library is stored on a solid state drive, in which case the file discovery and content hashing stages read the files in parallel. Required. /// Whether the consumption progress of the media library items should be tracked, or not. Optional, the default of the library type is used when absent. /// The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the default of the library type is used when absent. /// The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent. +/// The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, every provider supported by the library type is added disabled. +/// The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, every provider supported by the library type is added disabled. +/// The book readers of the media library, and whether each one is enabled. Optional, every reader supported by the library type is added disabled. [DebuggerDisplay("Title: {Title}")] public record AddLibraryRequest( string? Title, @@ -34,5 +37,8 @@ public record AddLibraryRequest( bool IsContentOnSsd, bool? ShouldTrackConsumptionProgress, int? CompletionThresholdPercentage, - LibraryPathTemplatePartRequest[]? PathTemplateParts + LibraryPathTemplatePartRequest?[]? PathTemplateParts, + LibraryProviderSelectionRequest?[]? MetadataProviders, + LibraryProviderSelectionRequest?[]? ArtworkProviders, + LibraryProviderSelectionRequest?[]? BookReaders ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/LibraryProviderSelectionRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/LibraryProviderSelectionRequest.cs new file mode 100644 index 00000000..26552e4e --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/LibraryProviderSelectionRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.Management; + +/// +/// Represents the choice made for one metadata provider, artwork provider or book reader of a media library. +/// +/// The Id of the plugin providing the metadata provider, artwork provider or book reader. Required. +/// Whether the provider or reader is enabled for the media library. Optional, the stored state is kept when absent, and a provider or reader without a stored state starts disabled. +[DebuggerDisplay("PluginId: {PluginId}; IsEnabled: {IsEnabled}")] +public record LibraryProviderSelectionRequest( + Guid PluginId, + bool? IsEnabled +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs index 9d4377f2..b1183e6f 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs @@ -9,24 +9,25 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// Represents a request to update a media library. /// /// The unique identifier of the media library. Required. -/// The unique identifier of the user owning the media library. Required. /// The title of the media library. Required. /// The type of the media library. Required. /// The file system paths of the directories where the media library elements are located. Required. /// The path of the image file used as the cover for the library. Optional. -/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional. -/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional. -/// Whether this media library should update the metadata of its elements from the web, or not. Optional. -/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. -/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. -/// Whether the content of this media library is stored on a solid state drive, in which case the file discovery and content hashing stages read the files in parallel. Optional. +/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Required. +/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Required. +/// Whether this media library should update the metadata of its elements from the web, or not. Required. +/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Required. +/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Required. +/// Whether the content of this media library is stored on a solid state drive, in which case the file discovery and content hashing stages read the files in parallel. Required. /// Whether the consumption progress of the media library items should be tracked, or not. Optional, the stored value is kept when absent. /// The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the stored value is kept when absent. /// The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent. +/// The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes. +/// The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes. +/// The book readers of the media library, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes. [DebuggerDisplay("Title: {Title}")] public record class UpdateLibraryRequest( Guid Id, - Guid UserId, string? Title, string? LibraryType, string[]? ContentLocations, @@ -39,5 +40,8 @@ public record class UpdateLibraryRequest( bool IsContentOnSsd, bool? ShouldTrackConsumptionProgress, int? CompletionThresholdPercentage, - LibraryPathTemplatePartRequest[]? PathTemplateParts + LibraryPathTemplatePartRequest?[]? PathTemplateParts, + LibraryProviderSelectionRequest?[]? MetadataProviders, + LibraryProviderSelectionRequest?[]? ArtworkProviders, + LibraryProviderSelectionRequest?[]? BookReaders ); diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeArtworkProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeArtworkProvidersRequest.cs new file mode 100644 index 00000000..21c66ce0 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeArtworkProvidersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the artwork providers available for a media library type. +/// +/// The media library type whose available artwork providers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public sealed record GetLibraryTypeArtworkProvidersRequest( + string? LibraryType +); diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeBookReadersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeBookReadersRequest.cs new file mode 100644 index 00000000..496af117 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeBookReadersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the book readers available for a media library type. +/// +/// The media library type whose available book readers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public sealed record GetLibraryTypeBookReadersRequest( + string? LibraryType +); diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeMetadataProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeMetadataProvidersRequest.cs new file mode 100644 index 00000000..8eff614b --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeMetadataProvidersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the metadata providers available for a media library type. +/// +/// The media library type whose available metadata providers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public sealed record GetLibraryTypeMetadataProvidersRequest( + string? LibraryType +); diff --git a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs deleted file mode 100644 index 0e0f815c..00000000 --- a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.Plugins; - -/// -/// Represents a request to reorder the artwork providers of a media library. -/// -/// The unique identifier of the media library whose artwork providers are reordered. Required. -/// The plugin Ids in the new order, from highest to lowest rank. Required. -[DebuggerDisplay("LibraryId: {LibraryId}")] -public sealed record ReorderLibraryArtworkProvidersRequest( - Guid LibraryId, - IReadOnlyList PluginIds -); diff --git a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs deleted file mode 100644 index 24b6021e..00000000 --- a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs +++ /dev/null @@ -1,18 +0,0 @@ -#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/SetLibraryArtworkProviderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs deleted file mode 100644 index bbfb2b95..00000000 --- a/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.Plugins; - -/// -/// Represents a request to enable or disable an artwork provider for a media library. -/// -/// The unique identifier of the media library whose artwork provider is enabled or disabled. Required. -/// The unique identifier of the plugin providing the artwork. Required. -/// Whether the artwork provider should be enabled for the media library. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public sealed record SetLibraryArtworkProviderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Contracts/Requests/Plugins/SetLibraryBookReaderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryBookReaderEnabledRequest.cs deleted file mode 100644 index 3392ae17..00000000 --- a/src/Lumina.Contracts/Requests/Plugins/SetLibraryBookReaderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.Plugins; - -/// -/// Represents a request to enable or disable a book reader for a media library. -/// -/// The Id of the media library whose book reader is enabled or disabled. Required. -/// The unique identifier of the plugin providing the book reader. Required. -/// Whether the book reader should be enabled for the media library. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public sealed record SetLibraryBookReaderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Contracts/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs deleted file mode 100644 index 342ec7b7..00000000 --- a/src/Lumina.Contracts/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#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. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public sealed record SetLibraryMetadataProviderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs index c9b01c01..a000754a 100644 --- a/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs +++ b/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs @@ -5,12 +5,12 @@ using System; namespace Lumina.Contracts.Responses.Plugins; /// -/// Represents an artwork provider configured for a media library. +/// Represents an artwork provider, either as configured for a media library, or as available for a library type, the way a new library of that type starts. /// /// The unique identifier of the plugin providing the artwork. /// The display name of the artwork provider. -/// Whether the artwork provider is enabled for the media library. -/// The rank of the artwork provider, determining the order in which providers are tried. +/// Whether the artwork provider is enabled for the media library. Always for a provider available for a library type, since a new provider starts disabled. +/// The rank of the artwork provider, determining the order in which providers are tried. For a provider available for a library type, it is the rank a new library starts with, in alphabetical order of the plugin names. public sealed record LibraryArtworkProviderResponse( Guid PluginId, string Name, diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs index bb095299..8c2141d7 100644 --- a/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs +++ b/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs @@ -7,12 +7,12 @@ using System.Diagnostics; namespace Lumina.Contracts.Responses.Plugins; /// -/// Represents a book reader configured for a media library. +/// Represents a book reader, either as configured for a media library, or as available for a library type, the way a new library of that type starts. /// /// The unique identifier of the plugin providing the book reader. /// The display name of the book reader. /// The file extensions supported by the book reader. -/// Whether the book reader is enabled for the media library. +/// Whether the book reader is enabled for the media library. Always for a reader available for a library type, since a new reader starts disabled. [DebuggerDisplay("Name: {Name}")] public sealed record LibraryBookReaderResponse( Guid PluginId, diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs index b47a3b1a..923a5d54 100644 --- a/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs +++ b/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs @@ -5,12 +5,12 @@ using System; namespace Lumina.Contracts.Responses.Plugins; /// -/// Represents a metadata provider configured for a media library. +/// Represents a metadata provider, either as configured for a media library, or as available for a library type, the way a new library of that type starts. /// /// 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. +/// Whether the metadata provider is enabled for the media library. Always for a provider available for a library type, since a new provider starts disabled. +/// The rank of the metadata provider, determining the order in which providers are tried. For a provider available for a library type, it is the rank a new library starts with, in alphabetical order of the plugin names. public sealed record LibraryMetadataProviderResponse( Guid PluginId, string Name, diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs index 89618882..ada861a6 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs @@ -20,7 +20,7 @@ public class LibraryArtworkProviderConfigurationConfiguration : IEntityTypeConfi builder.ToTable("LibraryArtworkProviderConfigurations"); builder.HasKey(configuration => configuration.Id); builder.Property(configuration => configuration.Id) - .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it. .HasColumnOrder(0); builder.Property(configuration => configuration.LibraryId) .IsRequired() @@ -35,7 +35,7 @@ public class LibraryArtworkProviderConfigurationConfiguration : IEntityTypeConfi .IsRequired() .HasColumnOrder(4); - // audit + // Audit. builder.Property(configuration => configuration.CreatedOnUtc) .IsRequired() .HasColumnOrder(5); @@ -52,6 +52,9 @@ public class LibraryArtworkProviderConfigurationConfiguration : IEntityTypeConfi .HasDefaultValue(null) .HasColumnOrder(8); - builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId }); + // A media library has at most one artwork provider configuration per plugin, so the pair is unique; the repository upserts on it, and + // the constraint guarantees that two concurrent upserts cannot insert duplicate rows. + builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId }) + .IsUnique(); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryMetadataProviderConfigurationConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryMetadataProviderConfigurationConfiguration.cs index 2130ed43..8b167ebb 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryMetadataProviderConfigurationConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryMetadataProviderConfigurationConfiguration.cs @@ -20,7 +20,7 @@ public class LibraryMetadataProviderConfigurationConfiguration : IEntityTypeConf builder.ToTable("LibraryMetadataProviderConfigurations"); builder.HasKey(configuration => configuration.Id); builder.Property(configuration => configuration.Id) - .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it. .HasColumnOrder(0); builder.Property(configuration => configuration.LibraryId) .IsRequired() @@ -35,7 +35,7 @@ public class LibraryMetadataProviderConfigurationConfiguration : IEntityTypeConf .IsRequired() .HasColumnOrder(4); - // audit + // Audit. builder.Property(configuration => configuration.CreatedOnUtc) .IsRequired() .HasColumnOrder(5); @@ -52,6 +52,9 @@ public class LibraryMetadataProviderConfigurationConfiguration : IEntityTypeConf .HasDefaultValue(null) .HasColumnOrder(8); - builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId }); + // A media library has at most one metadata provider configuration per plugin, so the pair is unique; the repository upserts on it, and + // the constraint guarantees that two concurrent upserts cannot insert duplicate rows. + builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId }) + .IsUnique(); } } diff --git a/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.Designer.cs new file mode 100644 index 00000000..4dce5d66 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.Designer.cs @@ -0,0 +1,3904 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin")] + partial class MakesProviderConfigurationsUniquePerLibraryAndPlugin + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "CreatedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId") + .IsUnique(); + + b.ToTable("Favorites", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaConsumptionRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ConsecutivePagesRead") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(14); + + b.Property("ConsumedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LastActivityOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionKind") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(13); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "StartedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId", "LastActivityOnUtc"); + + b.ToTable("MediaConsumptionRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaResumePointEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LastConsumedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(8); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId") + .IsUnique(); + + b.ToTable("MediaResumePoints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CompletionThresholdPercentage") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsContentOnSsd") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(18); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("ShouldTrackConsumptionProgress") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(16); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(28); + + b.Property("VuMeterHighThreshold") + .HasColumnType("REAL") + .HasColumnOrder(23); + + b.Property("VuMeterMediumThreshold") + .HasColumnType("REAL") + .HasColumnOrder(22); + + b.Property("VuMeterOrientation") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("VuMeterPeakHoldDurationInMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("VuMeterPeakReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(27); + + b.Property("VuMeterReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(26); + + b.Property("VuMeterSegmentCount") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("VuMeterSegmentGap") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("VuMeterShowPeak") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaConsumptionRecordEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaResumePointEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.cs b/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.cs new file mode 100644 index 00000000..778c777a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.cs @@ -0,0 +1,72 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class MakesProviderConfigurationsUniquePerLibraryAndPlugin : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // The upserts read before they add, so two concurrent ones could store the same plugin twice for a library; the duplicates are removed before the + // indexes become unique, keeping the configuration that is tried first, so the unique indexes can be created on an existing database. + migrationBuilder.Sql(""" + DELETE FROM LibraryMetadataProviderConfigurations WHERE rowid NOT IN ( + SELECT rowid FROM ( + SELECT rowid, ROW_NUMBER() OVER (PARTITION BY LibraryId, PluginId ORDER BY Rank, rowid) AS RowNumber + FROM LibraryMetadataProviderConfigurations) + WHERE RowNumber = 1); + + DELETE FROM LibraryArtworkProviderConfigurations WHERE rowid NOT IN ( + SELECT rowid FROM ( + SELECT rowid, ROW_NUMBER() OVER (PARTITION BY LibraryId, PluginId ORDER BY Rank, rowid) AS RowNumber + FROM LibraryArtworkProviderConfigurations) + WHERE RowNumber = 1); + """); + + migrationBuilder.DropIndex( + name: "IX_LibraryMetadataProviderConfigurations_LibraryId_PluginId", + table: "LibraryMetadataProviderConfigurations"); + + migrationBuilder.DropIndex( + name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId", + table: "LibraryArtworkProviderConfigurations"); + + migrationBuilder.CreateIndex( + name: "IX_LibraryMetadataProviderConfigurations_LibraryId_PluginId", + table: "LibraryMetadataProviderConfigurations", + columns: new[] { "LibraryId", "PluginId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId", + table: "LibraryArtworkProviderConfigurations", + columns: new[] { "LibraryId", "PluginId" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_LibraryMetadataProviderConfigurations_LibraryId_PluginId", + table: "LibraryMetadataProviderConfigurations"); + + migrationBuilder.DropIndex( + name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId", + table: "LibraryArtworkProviderConfigurations"); + + migrationBuilder.CreateIndex( + name: "IX_LibraryMetadataProviderConfigurations_LibraryId_PluginId", + table: "LibraryMetadataProviderConfigurations", + columns: new[] { "LibraryId", "PluginId" }); + + migrationBuilder.CreateIndex( + name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId", + table: "LibraryArtworkProviderConfigurations", + columns: new[] { "LibraryId", "PluginId" }); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 7bc06864..d1761391 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -2223,7 +2223,8 @@ namespace Lumina.DataAccess.Common.Migrations b.HasKey("Id"); - b.HasIndex("LibraryId", "PluginId"); + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); b.ToTable("LibraryArtworkProviderConfigurations", (string)null); }); @@ -2310,7 +2311,8 @@ namespace Lumina.DataAccess.Common.Migrations b.HasKey("Id"); - b.HasIndex("LibraryId", "PluginId"); + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); b.ToTable("LibraryMetadataProviderConfigurations", (string)null); }); diff --git a/src/Lumina.Domain/Common/Errors/Errors.Plugins.cs b/src/Lumina.Domain/Common/Errors/Errors.Plugins.cs index f79e7cb1..bad24145 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Plugins.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Plugins.cs @@ -15,8 +15,8 @@ public static partial class Errors public static Error PluginIdCannotBeEmpty => Error.Validation(description: nameof(PluginIdCannotBeEmpty)); public static Error PluginSettingsCannotBeNull => Error.Validation(description: nameof(PluginSettingsCannotBeNull)); public static Error LibraryIdCannotBeEmpty => Error.Validation(description: nameof(LibraryIdCannotBeEmpty)); - public static Error PluginIdsListCannotBeNull => Error.Validation(description: nameof(PluginIdsListCannotBeNull)); - public static Error PluginIdsListCannotBeEmpty => Error.Validation(description: nameof(PluginIdsListCannotBeEmpty)); + public static Error PluginIdsMustBeUnique => Error.Validation(description: nameof(PluginIdsMustBeUnique)); + public static Error PluginNotSupportedForLibraryType => Error.Validation(description: nameof(PluginNotSupportedForLibraryType)); public static Error LibraryMetadataProviderConfigurationNotFound => Error.NotFound(description: nameof(LibraryMetadataProviderConfigurationNotFound)); public static Error PluginArchiveCannotBeNull => Error.Validation(description: nameof(PluginArchiveCannotBeNull)); public static Error PluginFileNameCannotBeEmpty => Error.Validation(description: nameof(PluginFileNameCannotBeEmpty)); diff --git a/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs b/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs index f1347aae..debdadd7 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Reading; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Plugins.Contracts.Core.Metadata; @@ -25,9 +27,10 @@ namespace Lumina.Infrastructure.Core.Plugins; /// The configurations decide, per media library, which loaded plugins may serve metadata or artwork, which book reader opens the /// books of the library, and whether each of them is currently enabled. They are persisted as rows instead of being derived from /// the loaded plugins on the fly, because the user can enable or disable a provider per library, and because the set of loaded -/// plugins can change between restarts. This class is the single place that maintains them, and the only one that knows the -/// difference between "ensure" (only add what is missing) and "reconcile" (make the persisted configurations match the loaded -/// plugins exactly). +/// plugins can change between restarts. This class is the only one that writes them, while the queries, the scan enrichers and the +/// reading service read them through their repositories. It maintains them in three ways: "ensure" only adds what is missing, +/// "reconcile" makes the persisted configurations match the plugins supporting the library type, and "apply" reconciles them +/// and sets the enabled state and the order chosen when the library is added or updated. /// internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProviderConfigurationStore { @@ -63,8 +66,12 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv } /// - /// Adds a disabled provider configuration for every loaded plugin that supports the provided library type and has no configuration yet for the media library identified by . + /// Adds a disabled metadata provider, artwork provider and book reader configuration for every loaded plugin that supports the provided library type and has no configuration yet + /// for the media library identified by . /// + /// + /// The added configurations are only staged until the unit of work is saved, and are not visible to a later ensure, so it must be called at most once per media library before the changes are saved. + /// /// The Id of the media library whose provider configurations are ensured. /// The type of the media library, used to determine the plugins whose providers apply. /// Cancellation token that can be used to stop the execution. @@ -83,28 +90,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv return await EnsureBookReaderConfigurationsAsync(libraryId, libraryType, cancellationToken).ConfigureAwait(false); } - /// - /// Replaces the provider configurations of the media library identified by so that they match the plugins supporting the provided library type. - /// - /// The Id of the media library whose provider configurations are reconciled. - /// The type of the media library, used to determine the plugins whose providers apply. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> ReconcileProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) - { - // "Reconcile" makes the persisted configurations match the loaded plugins exactly: configurations of plugins that no longer support - // the library type are removed, configurations for newly supported plugins are added, and the rest are kept. It is called when a - // plugin is uninstalled or when the type of a library changes. - (IReadOnlyList metadataProviderPluginIds, IReadOnlyList artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType); - Result reconcileMetadataResult = await ReconcileMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false); - if (reconcileMetadataResult.IsFailure) - return reconcileMetadataResult; - Result reconcileArtworkResult = await ReconcileArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false); - if (reconcileArtworkResult.IsFailure) - return reconcileArtworkResult; - return await ReconcileBookReaderConfigurationsAsync(libraryId, libraryType, cancellationToken).ConfigureAwait(false); - } - /// /// Deletes all the provider configurations of the media library identified by . /// @@ -152,35 +137,63 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv } /// - /// Deletes all the book reader configurations of the media library identified by . + /// Makes the provider and book reader configurations of the media library identified by match the plugins supporting the provided library type, + /// and applies the choices made for them. /// - /// The Id of the media library whose book reader configurations are deleted. + /// + /// A list that is provided reconciles that kind of configuration with the library type and applies the choices: the configurations of the plugins that do not support the library type + /// are removed, even when the list does not name them, every supported plugin gets a configuration, and the list sets the enabled state of every provider or reader it names and, for the + /// metadata and artwork providers, their order. A choice without an enabled state keeps the stored state, the supported plugins the list does not name keep their stored state and are + /// ordered after the named ones, and a plugin without a stored configuration starts disabled. A list that is leaves that kind of configuration untouched, unless + /// is , in which case it is reconciled the same way, without choices. Whenever the book reader configurations are + /// reconciled or chosen, the cached reader enablements of the library are dropped. + /// + /// The Id of the media library whose provider and book reader configurations are configured. + /// The type of the media library, used to determine the plugins whose providers and book readers apply. + /// The choices made for the metadata providers, in the order in which they are tried. + /// The choices made for the artwork providers, in the order in which they are tried. + /// The choices made for the book readers. + /// Whether the kinds of configuration whose list of choices is are reconciled with the library type, which is needed when the + /// library is new or its type changed. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> RemoveBookReaderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error when a choice names a plugin that does not support the library type. + public async Task> ConfigureProvidersAsync( + Guid libraryId, + LibraryType libraryType, + IReadOnlyList? metadataProviders, + IReadOnlyList? artworkProviders, + IReadOnlyList? bookReaders, + bool shouldReconcileOmittedKinds, + CancellationToken cancellationToken) { - Result removeResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); - if (removeResult.IsFailure) - return removeResult; - // The reader enablements of the deleted library are no longer valid, so the reading service must not serve its books from the cache. + // The configurations are computed in a single pass from the stored state, instead of reconciling first and applying the choices afterwards, + // because the configurations added by a reconcile are only staged until the unit of work is saved, and a second upsert of the same plugin would not find them and would add a duplicate. + (IReadOnlyList metadataProviderPluginIds, IReadOnlyList artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType); + if (metadataProviders is not null || shouldReconcileOmittedKinds) + { + Result configureMetadataResult = metadataProviders is null + ? await ReconcileMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false) + : await ApplyMetadataProviderSelectionsAsync(libraryId, metadataProviderPluginIds, metadataProviders, cancellationToken).ConfigureAwait(false); + if (configureMetadataResult.IsFailure) + return configureMetadataResult; + } + if (artworkProviders is not null || shouldReconcileOmittedKinds) + { + Result configureArtworkResult = artworkProviders is null + ? await ReconcileArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false) + : await ApplyArtworkProviderSelectionsAsync(libraryId, artworkProviderPluginIds, artworkProviders, cancellationToken).ConfigureAwait(false); + if (configureArtworkResult.IsFailure) + return configureArtworkResult; + } + // Reconciling the book readers drops the cached enablements of the library by itself. + if (bookReaders is null) + return shouldReconcileOmittedKinds ? await ReconcileBookReaderConfigurationsAsync(libraryId, libraryType, cancellationToken).ConfigureAwait(false) : Result.Success; + Result configureBookReadersResult = await ApplyBookReaderSelectionsAsync(libraryId, GetSupportedBookReaderPluginIds(libraryType), bookReaders, cancellationToken).ConfigureAwait(false); + if (configureBookReadersResult.IsFailure) + return configureBookReadersResult; + // The reading service caches the enablement of the readers, so the cached state of the library is dropped, and a reader that was disabled stops serving its books immediately. _enablementCache.InvalidateLibrary(libraryId); - return removeResult; - } - - /// - /// Deletes all the book reader configurations referencing the plugin identified by . - /// - /// The Id of the plugin whose book reader configurations are deleted. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> RemoveBookReaderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken) - { - Result removeResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false); - if (removeResult.IsFailure) - return removeResult; - // The reader enablements of the removed plugin are no longer valid, so the reading service must not serve its books from the cache. - _enablementCache.InvalidatePlugin(pluginId); - return removeResult; + return Result.Success; } /// @@ -205,12 +218,32 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv return (metadataProviderPluginIds, artworkProviderPluginIds); } + /// + /// Gets the Ids of the loaded plugins that provide metadata for the provided library type, ordered alphabetically by plugin name. + /// + /// The type of the media library the metadata providers must support. + /// The Ids of the plugins providing metadata for the library type. + public IReadOnlyList GetSupportedMetadataProviderPluginIds(LibraryType libraryType) + { + return GetSupportedProviderPluginIds(libraryType).metadataProviderPluginIds; + } + + /// + /// Gets the Ids of the loaded plugins that provide artwork for the provided library type, ordered alphabetically by plugin name. + /// + /// The type of the media library the artwork providers must support. + /// The Ids of the plugins providing artwork for the library type. + public IReadOnlyList GetSupportedArtworkProviderPluginIds(LibraryType libraryType) + { + return GetSupportedProviderPluginIds(libraryType).artworkProviderPluginIds; + } + /// /// Gets the Ids of the loaded plugins that provide a book reader for the provided library type, ordered alphabetically by plugin name so that the assigned order is stable. /// /// The type of the media library the book readers must support. /// The Ids of the plugins providing a book reader for the library type. - private IReadOnlyList GetSupportedBookReaderPluginIds(LibraryType libraryType) + public IReadOnlyList GetSupportedBookReaderPluginIds(LibraryType libraryType) { // Book readers have no rank: a book is opened by exactly one reader matched by its file extension, not by priority, so the alphabetical order is only used to keep the display order stable. List bookReaderPluginIds = []; @@ -224,11 +257,14 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv /// /// Replaces the book reader configurations of the media library identified by so that they match the plugins supporting the provided library type. /// + /// + /// The cached reader enablements of the library are dropped, so a reader whose configuration was removed stops serving its books immediately. + /// /// The Id of the media library whose book reader configurations are reconciled. /// The type of the media library, used to determine the plugins whose book readers apply. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async Task> ReconcileBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) + private async Task> ReconcileBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) { // First, the configurations of readers that no longer apply are deleted, then a disabled configuration is added for every reader // that applies, but is not configured yet; the configurations of readers that still apply are kept untouched. @@ -267,6 +303,8 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv if (upsertResult.IsFailure) return Result.Failure(upsertResult.Errors); } + // The reading service caches the enablement of the readers, so the cached state of the library is dropped, and a reader whose configuration was removed stops serving its books immediately. + _enablementCache.InvalidateLibrary(libraryId); return Result.Success; } @@ -277,7 +315,7 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv /// The type of the media library, used to determine the plugins whose book readers apply. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async Task> EnsureBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) + private async Task> EnsureBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) { // Unlike reconcile, ensure never deletes: it only adds a disabled configuration for the readers that are not configured yet. IReadOnlyList bookReaderPluginIds = GetSupportedBookReaderPluginIds(libraryType); @@ -499,4 +537,193 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv } return Result.Success; } + + /// + /// Makes the metadata provider configurations of the media library match the plugins supporting its type, and applies the provided choices. + /// + /// The Id of the media library whose metadata provider configurations are configured. + /// The Ids of the plugins providing metadata for the library type, in alphabetical order. + /// The choices made for the metadata providers, in the order in which they are tried. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> ApplyMetadataProviderSelectionsAsync(Guid libraryId, IReadOnlyList metadataProviderPluginIds, IReadOnlyList selections, CancellationToken cancellationToken) + { + // The command validation rejects duplicated choices already, and they are reported here too, so that a direct caller gets an error instead of an exception. + if (selections.Select(selection => selection.PluginId).Distinct().Count() != selections.Count) + return Errors.Plugins.PluginIdsMustBeUnique; + if (selections.Any(selection => !metadataProviderPluginIds.Contains(selection.PluginId))) + return Errors.Plugins.PluginNotSupportedForLibraryType; + Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + List stalePluginIds = [.. getConfigurationsResult.Value + .Select(configuration => configuration.PluginId) + .Where(pluginId => !metadataProviderPluginIds.Contains(pluginId))]; + if (stalePluginIds.Count > 0) + { + Result removeResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); + if (removeResult.IsFailure) + return Result.Failure(removeResult.Errors); + } + Dictionary configurationsByPluginId = getConfigurationsResult.Value + .Where(configuration => metadataProviderPluginIds.Contains(configuration.PluginId)) + .ToDictionary(configuration => configuration.PluginId); + IReadOnlyList orderedPluginIds = GetProviderOrder(selections, configurationsByPluginId.Values.OrderBy(configuration => configuration.Rank).Select(configuration => configuration.PluginId), metadataProviderPluginIds); + Dictionary enabledStatesByPluginId = selections.ToDictionary(selection => selection.PluginId, selection => selection.IsEnabled); + for (int index = 0; index < orderedPluginIds.Count; index++) + { + Guid pluginId = orderedPluginIds[index]; + configurationsByPluginId.TryGetValue(pluginId, out LibraryMetadataProviderConfigurationEntity? storedConfiguration); + // A provider that is not named, or is named without an enabled state, keeps its stored state, and a provider that has no configuration yet starts disabled, so it never silently starts enriching the library. + bool isEnabled = enabledStatesByPluginId.GetValueOrDefault(pluginId) ?? storedConfiguration?.IsEnabled ?? false; + LibraryMetadataProviderConfigurationEntity configuration = storedConfiguration ?? new LibraryMetadataProviderConfigurationEntity + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = isEnabled, + Rank = index + 1, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + configuration.IsEnabled = isEnabled; + configuration.Rank = index + 1; + Result upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + } + return Result.Success; + } + + /// + /// Makes the artwork provider configurations of the media library match the plugins supporting its type, and applies the provided choices. + /// + /// The Id of the media library whose artwork provider configurations are configured. + /// The Ids of the plugins providing artwork for the library type, in alphabetical order. + /// The choices made for the artwork providers, in the order in which they are tried. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> ApplyArtworkProviderSelectionsAsync(Guid libraryId, IReadOnlyList artworkProviderPluginIds, IReadOnlyList selections, CancellationToken cancellationToken) + { + // The command validation rejects duplicated choices already, and they are reported here too, so that a direct caller gets an error instead of an exception. + if (selections.Select(selection => selection.PluginId).Distinct().Count() != selections.Count) + return Errors.Plugins.PluginIdsMustBeUnique; + if (selections.Any(selection => !artworkProviderPluginIds.Contains(selection.PluginId))) + return Errors.Plugins.PluginNotSupportedForLibraryType; + Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + List stalePluginIds = [.. getConfigurationsResult.Value + .Select(configuration => configuration.PluginId) + .Where(pluginId => !artworkProviderPluginIds.Contains(pluginId))]; + if (stalePluginIds.Count > 0) + { + Result removeResult = await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); + if (removeResult.IsFailure) + return Result.Failure(removeResult.Errors); + } + Dictionary configurationsByPluginId = getConfigurationsResult.Value + .Where(configuration => artworkProviderPluginIds.Contains(configuration.PluginId)) + .ToDictionary(configuration => configuration.PluginId); + IReadOnlyList orderedPluginIds = GetProviderOrder(selections, configurationsByPluginId.Values.OrderBy(configuration => configuration.Rank).Select(configuration => configuration.PluginId), artworkProviderPluginIds); + Dictionary enabledStatesByPluginId = selections.ToDictionary(selection => selection.PluginId, selection => selection.IsEnabled); + for (int index = 0; index < orderedPluginIds.Count; index++) + { + Guid pluginId = orderedPluginIds[index]; + configurationsByPluginId.TryGetValue(pluginId, out LibraryArtworkProviderConfigurationEntity? storedConfiguration); + // A provider that is not named, or is named without an enabled state, keeps its stored state, and a provider that has no configuration yet starts disabled, so it never silently starts enriching the library. + bool isEnabled = enabledStatesByPluginId.GetValueOrDefault(pluginId) ?? storedConfiguration?.IsEnabled ?? false; + LibraryArtworkProviderConfigurationEntity configuration = storedConfiguration ?? new LibraryArtworkProviderConfigurationEntity + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = isEnabled, + Rank = index + 1, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + configuration.IsEnabled = isEnabled; + configuration.Rank = index + 1; + Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + } + return Result.Success; + } + + /// + /// Makes the book reader configurations of the media library match the plugins supporting its type, and applies the provided choices. + /// + /// The Id of the media library whose book reader configurations are configured. + /// The Ids of the plugins providing a book reader for the library type. + /// The choices made for the book readers. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> ApplyBookReaderSelectionsAsync(Guid libraryId, IReadOnlyList bookReaderPluginIds, IReadOnlyList selections, CancellationToken cancellationToken) + { + // The command validation rejects duplicated choices already, and they are reported here too, so that a direct caller gets an error instead of an exception. + if (selections.Select(selection => selection.PluginId).Distinct().Count() != selections.Count) + return Errors.Plugins.PluginIdsMustBeUnique; + if (selections.Any(selection => !bookReaderPluginIds.Contains(selection.PluginId))) + return Errors.Plugins.PluginNotSupportedForLibraryType; + Result> getConfigurationsResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + List stalePluginIds = [.. getConfigurationsResult.Value + .Select(configuration => configuration.PluginId) + .Where(pluginId => !bookReaderPluginIds.Contains(pluginId))]; + if (stalePluginIds.Count > 0) + { + Result removeResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); + if (removeResult.IsFailure) + return Result.Failure(removeResult.Errors); + } + Dictionary configurationsByPluginId = getConfigurationsResult.Value + .Where(configuration => bookReaderPluginIds.Contains(configuration.PluginId)) + .ToDictionary(configuration => configuration.PluginId); + Dictionary enabledStatesByPluginId = selections.ToDictionary(selection => selection.PluginId, selection => selection.IsEnabled); + // Book readers have no rank, since a book is opened by the reader matched by its file extension, so only their enabled state is applied. + foreach (Guid pluginId in bookReaderPluginIds) + { + configurationsByPluginId.TryGetValue(pluginId, out LibraryBookReaderConfigurationEntity? storedConfiguration); + // A reader that is not named, or is named without an enabled state, keeps its stored state, and a reader that has no configuration yet starts disabled, so it never silently takes over reading the books of the library. + bool isEnabled = enabledStatesByPluginId.GetValueOrDefault(pluginId) ?? storedConfiguration?.IsEnabled ?? false; + LibraryBookReaderConfigurationEntity configuration = storedConfiguration ?? new LibraryBookReaderConfigurationEntity + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = isEnabled, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + configuration.IsEnabled = isEnabled; + Result upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + } + return Result.Success; + } + + /// + /// Gets the order in which the supported providers of a media library are tried: the named providers in the order of the choices, then the providers that are already configured, + /// in their stored order, then the providers that are not configured yet, in alphabetical order. + /// + /// The choices made for the providers, in the order in which they are tried. + /// The Ids of the plugins whose providers are already configured and still supported, in their stored order. + /// The Ids of the plugins providing for the library type, in alphabetical order. + /// The Ids of the plugins, in the order in which their providers are tried. + private static IReadOnlyList GetProviderOrder(IReadOnlyList selections, IEnumerable configuredPluginIds, IReadOnlyList supportedPluginIds) + { + List orderedPluginIds = [.. selections.Select(selection => selection.PluginId)]; + HashSet orderedPluginIdSet = [.. orderedPluginIds]; + foreach (Guid pluginId in configuredPluginIds.Concat(supportedPluginIds)) + if (orderedPluginIdSet.Add(pluginId)) + orderedPluginIds.Add(pluginId); + return orderedPluginIds; + } } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index c31213fa..e7f94809 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -129,7 +129,9 @@ internal sealed class PluginDetectionSyncJob : BackgroundService } } - // Seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata or artwork for its type. + // Seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata, artwork or a book reader for its type. + // A single ensure covers all three kinds, because the configurations it adds are only staged until the unit of work is saved, and a second ensure in the + // same scope would not find them and would add duplicates that break the unique index on save. Result> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync(cancellationToken: stoppingToken).ConfigureAwait(false); if (getLibrariesResult.IsFailure) _logger.LogError("Failed to get the media libraries while seeding the provider configurations."); @@ -140,9 +142,6 @@ internal sealed class PluginDetectionSyncJob : BackgroundService Result ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false); if (ensureResult.IsFailure) _logger.LogError("Failed to seed the provider configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureResult.FirstError.Description); - Result ensureBookReadersResult = await providerConfigurationStore.EnsureBookReaderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false); - if (ensureBookReadersResult.IsFailure) - _logger.LogError("Failed to seed the book reader configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureBookReadersResult.FirstError.Description); } } 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 2f6fd0de..5a0d88dc 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 @@ -23,13 +23,11 @@ public static partial class ApiRoutes 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"; public const string GET_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers"; - public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "/libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; - public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers/reorder"; public const string GET_LIBRARY_PATH_TEMPLATE_PARTS = "/libraries/path-template-parts/{libraryType}"; public const string GET_LIBRARY_BOOK_READERS = "/libraries/{libraryId}/book-readers"; - public const string SET_LIBRARY_BOOK_READER_ENABLED = "/libraries/{libraryId}/book-readers/{pluginId}/enabled"; + public const string GET_LIBRARY_TYPE_METADATA_PROVIDERS = "/libraries/metadata-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_ARTWORK_PROVIDERS = "/libraries/artwork-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_BOOK_READERS = "/libraries/book-readers/{libraryType}"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs index a2e8a6f0..2dfa66f7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs @@ -40,7 +40,10 @@ public class AddLibraryEndpointSummary : Summary r.Title, "The title of the media library. Required."); @@ -56,6 +59,9 @@ public class AddLibraryEndpointSummary : Summary r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items should be tracked, or not. Optional, the default of the library type is used when absent."); RequestParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the default of the library type is used when absent."); RequestParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent."); + RequestParam(r => r.MetadataProviders, "The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, every provider supported by the library type is added disabled when absent."); + RequestParam(r => r.ArtworkProviders, "The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, every provider supported by the library type is added disabled when absent."); + RequestParam(r => r.BookReaders, "The book readers of the media library, and whether each one is enabled. Optional, every reader supported by the library type is added disabled when absent."); ResponseParam(r => r.Id, "The unique identifier of the entity."); ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); @@ -172,7 +178,10 @@ public class AddLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library. Required."); - RequestParam(r => r.UserId, "The unique identifier of the user owning the media library. Required."); RequestParam(r => r.Title, "The title of the media library. Required."); RequestParam(r => r.LibraryType, "The type of the media library. Required."); RequestParam(r => r.ContentLocations, ">The file system paths of the directories where the media library elements are located. Required."); @@ -60,6 +61,9 @@ public class UpdateLibraryEndpointSummary : Summary r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items should be tracked, or not. Optional, the stored value is kept when absent."); RequestParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the stored value is kept when absent."); RequestParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent."); + RequestParam(r => r.MetadataProviders, "The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes when absent."); + RequestParam(r => r.ArtworkProviders, "The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes when absent."); + RequestParam(r => r.BookReaders, "The book readers of the media library, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes when absent."); ResponseParam(r => r.Id, "The unique identifier of the entity."); ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); @@ -130,7 +134,7 @@ public class UpdateLibraryEndpointSummary : Summary +/// API endpoint for the /libraries/artwork-providers/{libraryType} route. +/// +public class GetLibraryTypeArtworkProvidersEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getLibraryTypeArtworkProvidersQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get library type artwork providers queries. + public GetLibraryTypeArtworkProvidersEndpoint(IQueryHandler>> getLibraryTypeArtworkProvidersQueryHandler) + { + _getLibraryTypeArtworkProvidersQueryHandler = getLibraryTypeArtworkProvidersQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the artwork providers available for the media library type provided in . + /// + /// The request containing the media library type whose available artwork providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeArtworkProvidersRequest request, CancellationToken cancellationToken) + { + Result> result = await _getLibraryTypeArtworkProvidersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs new file mode 100644 index 00000000..583e08c6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs @@ -0,0 +1,118 @@ +#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.GetLibraryTypeArtworkProviders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersEndpointSummary() + { + Summary = "Retrieves the artwork providers available for a media library type."; + Description = "Retrieves the artwork providers of the loaded plugins that support a media library type, in the state a new media library of that type starts with: disabled, and ranked in alphabetical order."; + + ExampleRequest = new GetLibraryTypeArtworkProvidersRequest( + LibraryType: "Book" + ); + + RequestParam(r => r.LibraryType, "The media library type whose available artwork providers are retrieved. Required."); + + ResponseParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork."); + ResponseParam(r => r.Name, "The display name of the artwork provider."); + ResponseParam(r => r.IsEnabled, "Whether the artwork provider is enabled. Always false, since no media library is involved."); + ResponseParam(r => r.Rank, "The rank of the artwork provider, determining the order in which providers are tried."); + + Response(200, "The artwork providers available for the media library type are returned.", + example: new LibraryArtworkProviderResponse[] { + new( + PluginId: Guid.NewGuid(), + Name: "Goodreads", + IsEnabled: false, + 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 = "Authentication failed", + instance = "/api/v1/libraries/artwork-providers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/libraries/artwork-providers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/artwork-providers/{libraryType}" + } + } + ); + + Response(403, "The request failed because the request carries no user identity.", "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/artwork-providers/{libraryType}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/artwork-providers/{libraryType}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryTypeCannotBeNull", + "UnknownLibraryType" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs new file mode 100644 index 00000000..d4b290f3 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; + +/// +/// API endpoint for the /libraries/book-readers/{libraryType} route. +/// +public class GetLibraryTypeBookReadersEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getLibraryTypeBookReadersQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get library type book readers queries. + public GetLibraryTypeBookReadersEndpoint(IQueryHandler>> getLibraryTypeBookReadersQueryHandler) + { + _getLibraryTypeBookReadersQueryHandler = getLibraryTypeBookReadersQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the book readers available for the media library type provided in . + /// + /// The request containing the media library type whose available book readers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeBookReadersRequest request, CancellationToken cancellationToken) + { + Result> result = await _getLibraryTypeBookReadersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs new file mode 100644 index 00000000..05f2fb0a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs @@ -0,0 +1,118 @@ +#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.GetLibraryTypeBookReaders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersEndpointSummary() + { + Summary = "Retrieves the book readers available for a media library type."; + Description = "Retrieves the book readers of the loaded plugins that support a media library type, with their supported file extensions, in the state a new media library of that type starts with: disabled, in alphabetical order."; + + ExampleRequest = new GetLibraryTypeBookReadersRequest( + LibraryType: "Book" + ); + + RequestParam(r => r.LibraryType, "The media library type whose available book readers are retrieved. Required."); + + ResponseParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader."); + ResponseParam(r => r.Name, "The display name of the book reader."); + ResponseParam(r => r.SupportedExtensions, "The file extensions supported by the book reader."); + ResponseParam(r => r.IsEnabled, "Whether the book reader is enabled. Always false, since no media library is involved."); + + Response(200, "The book readers available for the media library type are returned.", + example: new LibraryBookReaderResponse[] { + new( + PluginId: Guid.NewGuid(), + Name: "EPUB Reader", + SupportedExtensions: [".epub"], + IsEnabled: false + ), + new( + PluginId: Guid.NewGuid(), + Name: "PDF Reader", + SupportedExtensions: [".pdf"], + IsEnabled: false + ) + } + ); + + 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 = "Authentication failed", + instance = "/api/v1/libraries/book-readers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/libraries/book-readers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/book-readers/{libraryType}" + } + } + ); + + Response(403, "The request failed because the request carries no user identity.", "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/book-readers/{libraryType}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/book-readers/{libraryType}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryTypeCannotBeNull", + "UnknownLibraryType" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs new file mode 100644 index 00000000..7cd472a5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; + +/// +/// API endpoint for the /libraries/metadata-providers/{libraryType} route. +/// +public class GetLibraryTypeMetadataProvidersEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getLibraryTypeMetadataProvidersQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get library type metadata providers queries. + public GetLibraryTypeMetadataProvidersEndpoint(IQueryHandler>> getLibraryTypeMetadataProvidersQueryHandler) + { + _getLibraryTypeMetadataProvidersQueryHandler = getLibraryTypeMetadataProvidersQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the metadata providers available for the media library type provided in . + /// + /// The request containing the media library type whose available metadata providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeMetadataProvidersRequest request, CancellationToken cancellationToken) + { + Result> result = await _getLibraryTypeMetadataProvidersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs new file mode 100644 index 00000000..a0d27f55 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs @@ -0,0 +1,118 @@ +#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.GetLibraryTypeMetadataProviders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersEndpointSummary() + { + Summary = "Retrieves the metadata providers available for a media library type."; + Description = "Retrieves the metadata providers of the loaded plugins that support a media library type, in the state a new media library of that type starts with: disabled, and ranked in alphabetical order."; + + ExampleRequest = new GetLibraryTypeMetadataProvidersRequest( + LibraryType: "Book" + ); + + RequestParam(r => r.LibraryType, "The media library type whose available 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. Always false, since no media library is involved."); + ResponseParam(r => r.Rank, "The rank of the metadata provider, determining the order in which providers are tried."); + + Response(200, "The metadata providers available for the media library type are returned.", + example: new LibraryMetadataProviderResponse[] { + new( + PluginId: Guid.NewGuid(), + Name: "Goodreads", + IsEnabled: false, + 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 = "Authentication failed", + instance = "/api/v1/libraries/metadata-providers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/libraries/metadata-providers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/metadata-providers/{libraryType}" + } + } + ); + + Response(403, "The request failed because the request carries no user identity.", "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/metadata-providers/{libraryType}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-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/metadata-providers/{libraryType}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryTypeCannotBeNull", + "UnknownLibraryType" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs deleted file mode 100644 index 57e492af..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Routes.Library.Management; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; - -/// -/// API endpoint for the /libraries/{libraryId}/artwork-providers/reorder route. -/// -public class ReorderLibraryArtworkProvidersEndpoint : BaseEndpoint -{ - private readonly ICommandHandler> _reorderLibraryArtworkProvidersCommandHandler; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling reorder library artwork providers commands. - public ReorderLibraryArtworkProvidersEndpoint(ICommandHandler> reorderLibraryArtworkProvidersCommandHandler) - { - _reorderLibraryArtworkProvidersCommandHandler = reorderLibraryArtworkProvidersCommandHandler; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(FastEndpoints.Http.PUT); - Routes(ApiRoutes.Libraries.REORDER_LIBRARY_ARTWORK_PROVIDERS); - Version(1); - DontCatchExceptions(); - } - - /// - /// Reorders the artwork providers of the media library identified by . - /// - /// The request containing the Id of the media library and the plugin Ids in the new order. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(ReorderLibraryArtworkProvidersRequest request, CancellationToken cancellationToken) - { - Result result = await _reorderLibraryArtworkProvidersCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs deleted file mode 100644 index 72d7e799..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs +++ /dev/null @@ -1,116 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; - -/// -/// Class used for providing a textual description for the API endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryArtworkProvidersEndpointSummary() - { - Summary = "Reorders the artwork providers of a media library."; - Description = "Reorders the artwork providers of a media library, determining the order in which the providers are tried during the artwork enrichment of the library scans."; - - ExampleRequest = new ReorderLibraryArtworkProvidersRequest( - LibraryId: Guid.NewGuid(), - PluginIds: - [ - Guid.NewGuid(), - Guid.NewGuid() - ] - ); - - RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are reordered. Required."); - RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); - - Response(200, "The artwork providers of the media library were successfully reordered."); - - Response(401, "Authentication required.", "application/problem+json", - example: new[] - { - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "Authentication failed", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token has expired", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token is invalid", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" - } - } - ); - - Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", - title = "General.Failure", - status = 403, - detail = "NotAuthorized", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", - traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" - } - ); - - Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", - title = "General.NotFound", - status = 404, - detail = "LibraryNotFound", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", - traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" - } - ); - - Response(422, "The request did not pass validation checks.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc4918#section-11.2", - title = "General.Validation", - status = 422, - detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", - errors = new Dictionary - { - { - "General.Validation", new[] - { - "LibraryIdCannotBeEmpty", - "PluginIdsListCannotBeNull", - "PluginIdsListCannotBeEmpty" - } - } - }, - traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" - } - ); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs deleted file mode 100644 index c07e7016..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Routes.Library.Management; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; - -/// -/// API endpoint for the /libraries/{libraryId}/metadata-providers/reorder route. -/// -public class ReorderLibraryMetadataProvidersEndpoint : BaseEndpoint -{ - private readonly ICommandHandler> _reorderLibraryMetadataProvidersCommandHandler; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling reorder library metadata providers commands. - public ReorderLibraryMetadataProvidersEndpoint(ICommandHandler> reorderLibraryMetadataProvidersCommandHandler) - { - _reorderLibraryMetadataProvidersCommandHandler = reorderLibraryMetadataProvidersCommandHandler; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(FastEndpoints.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) - { - Result result = await _reorderLibraryMetadataProvidersCommandHandler.HandleAsync(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 deleted file mode 100644 index de2e24a1..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointSummary.cs +++ /dev/null @@ -1,116 +0,0 @@ -#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 = "Authentication failed", - 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 has expired", - 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/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs deleted file mode 100644 index b525dac5..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Routes.Library.Management; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; - -/// -/// API endpoint for the /libraries/{libraryId}/artwork-providers/{pluginId}/enabled route. -/// -public class SetLibraryArtworkProviderEnabledEndpoint : BaseEndpoint -{ - private readonly ICommandHandler> _setLibraryArtworkProviderEnabledCommandHandler; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling set library artwork provider enabled commands. - public SetLibraryArtworkProviderEnabledEndpoint(ICommandHandler> setLibraryArtworkProviderEnabledCommandHandler) - { - _setLibraryArtworkProviderEnabledCommandHandler = setLibraryArtworkProviderEnabledCommandHandler; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(FastEndpoints.Http.PUT); - Routes(ApiRoutes.Libraries.SET_LIBRARY_ARTWORK_PROVIDER_ENABLED); - Version(1); - DontCatchExceptions(); - } - - /// - /// Enables or disables the artwork provider identified by for the media library. - /// - /// The request containing the Ids of the media library and of the artwork provider. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetLibraryArtworkProviderEnabledRequest request, CancellationToken cancellationToken) - { - Result result = await _setLibraryArtworkProviderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs deleted file mode 100644 index 25100d34..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs +++ /dev/null @@ -1,113 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; - -/// -/// Class used for providing a textual description for the API endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryArtworkProviderEnabledEndpointSummary() - { - Summary = "Enables or disables an artwork provider for a media library."; - Description = "Enables or disables the artwork provider for the media library, so that it is included or excluded from the artwork enrichment of the library scans."; - - ExampleRequest = new SetLibraryArtworkProviderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - RequestParam(r => r.LibraryId, "The Id of the media library whose artwork provider is enabled or disabled. Required."); - RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork. Required."); - RequestParam(r => r.IsEnabled, "Whether the artwork provider should be enabled for the media library. Required."); - - Response(200, "The artwork provider was successfully enabled or disabled for the media library."); - - Response(401, "Authentication required.", "application/problem+json", - example: new[] - { - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "Authentication failed", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token has expired", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token is invalid", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" - } - } - ); - - Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", - title = "General.Failure", - status = 403, - detail = "NotAuthorized", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", - traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" - } - ); - - Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", - title = "General.NotFound", - status = 404, - detail = "LibraryNotFound", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", - traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" - } - ); - - Response(422, "The request did not pass validation checks.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc4918#section-11.2", - title = "General.Validation", - status = 422, - detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", - errors = new Dictionary - { - { - "General.Validation", new[] - { - "LibraryIdCannotBeEmpty", - "PluginIdCannotBeEmpty" - } - } - }, - traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" - } - ); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpoint.cs deleted file mode 100644 index 3ec20be4..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Routes.Library.Management; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; - -/// -/// API endpoint for the /libraries/{libraryId}/book-readers/{pluginId}/enabled route. -/// -public class SetLibraryBookReaderEnabledEndpoint : BaseEndpoint -{ - private readonly ICommandHandler> _setLibraryBookReaderEnabledCommandHandler; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling set library book reader enabled commands. - public SetLibraryBookReaderEnabledEndpoint(ICommandHandler> setLibraryBookReaderEnabledCommandHandler) - { - _setLibraryBookReaderEnabledCommandHandler = setLibraryBookReaderEnabledCommandHandler; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(FastEndpoints.Http.PUT); - Routes(ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED); - Version(1); - DontCatchExceptions(); - } - - /// - /// Enables or disables the book reader identified by for the media library. - /// - /// The request containing the Ids of the media library and of the book reader. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetLibraryBookReaderEnabledRequest request, CancellationToken cancellationToken) - { - Result result = await _setLibraryBookReaderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointSummary.cs deleted file mode 100644 index dc5f8742..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointSummary.cs +++ /dev/null @@ -1,118 +0,0 @@ -#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.SetLibraryBookReaderEnabled; - -/// -/// Class used for providing a textual description for the API endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryBookReaderEnabledEndpointSummary() - { - Summary = "Enables or disables a book reader for a media library."; - Description = "Enables or disables the book reader of the media library identified by the request."; - - ExampleRequest = new SetLibraryBookReaderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - RequestParam(r => r.LibraryId, "The Id of the media library whose book reader is enabled or disabled. Required."); - RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader. Required."); - RequestParam(r => r.IsEnabled, "Whether the book reader should be enabled for the media library. Required."); - - Response(200, "The book reader of the media library is enabled or disabled.", - example: new - { - success = true - } - ); - - 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 = "Authentication failed", - instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token has expired", - instance = "/api/v1/libraries/{libraryId}/book-readers/{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}/book-readers/{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}/book-readers/{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}/book-readers/{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}/book-readers/{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/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs deleted file mode 100644 index d3d490e3..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Routes.Library.Management; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; - -/// -/// API endpoint for the /libraries/{libraryId}/metadata-providers/{pluginId}/enabled route. -/// -public class SetLibraryMetadataProviderEnabledEndpoint : BaseEndpoint -{ - private readonly ICommandHandler> _setLibraryMetadataProviderEnabledCommandHandler; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling set library metadata provider enabled commands. - public SetLibraryMetadataProviderEnabledEndpoint(ICommandHandler> setLibraryMetadataProviderEnabledCommandHandler) - { - _setLibraryMetadataProviderEnabledCommandHandler = setLibraryMetadataProviderEnabledCommandHandler; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(FastEndpoints.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) - { - Result result = await _setLibraryMetadataProviderEnabledCommandHandler.HandleAsync(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 deleted file mode 100644 index 8097bb2a..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointSummary.cs +++ /dev/null @@ -1,113 +0,0 @@ -#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 = "Authentication failed", - 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 has expired", - 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.Web/Common/Authorization/PermissionAuthorizationHandler.cs b/src/Lumina.Presentation.Web/Common/Authorization/PermissionAuthorizationHandler.cs index ce4b912b..70fef020 100644 --- a/src/Lumina.Presentation.Web/Common/Authorization/PermissionAuthorizationHandler.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/PermissionAuthorizationHandler.cs @@ -24,12 +24,18 @@ public class PermissionAuthorizationHandler : AuthorizationHandler - /// Succeeds the requirement when the currently logged in user holds any of the required permissions. + /// Succeeds the requirement when the currently logged in user is an administrator, or holds any of the required permissions. /// /// The authorization context. /// The permission requirement to evaluate. protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authorizationHandlerContext, PermissionRequirement permissionRequirement) { + // The API lets administrators do what the permission allows even when they do not hold it, so the Web does not deny them what the API grants. + if (await _authorizationService.IsInRoleAsync("Admin", CancellationToken.None).ConfigureAwait(false)) + { + authorizationHandlerContext.Succeed(permissionRequirement); + return; + } foreach (AuthorizationPermission permission in permissionRequirement.Permissions) { if (await _authorizationService.HasPermissionAsync(permission, CancellationToken.None).ConfigureAwait(false)) diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibrariesIndexPageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibrariesIndexPageDto.cs new file mode 100644 index 00000000..1caafe30 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibrariesIndexPageDto.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Libraries; + +/// +/// Data transfer object for the data of the media libraries management page. +/// +/// Whether the current user can change and delete their media libraries, which takes the permission to manage media libraries, or the administrator role. +[DebuggerDisplay("CanManageLibraries: {CanManageLibraries}")] +public sealed record LibrariesIndexPageDto( + bool CanManageLibraries +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs index fcb59abc..d33e13db 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs @@ -17,11 +17,6 @@ public class LibraryDto /// public Guid? Id { get; set; } - /// - /// Gets or sets the unique identifier of the user owning the media library. - /// - public Guid? UserId { get; set; } - /// /// Gets or sets the title of the library. /// @@ -88,4 +83,22 @@ public class LibraryDto /// Gets or sets the ordered parts of the template describing the structure of the media library on disk. /// public List PathTemplateParts { get; set; } = []; + + /// + /// Gets or sets the metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, the providers are configured + /// with their defaults on create, and on update the stored configurations are kept, or reconciled with the library type when it changes. + /// + public List? MetadataProviders { get; set; } + + /// + /// Gets or sets the artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, the providers are configured + /// with their defaults on create, and on update the stored configurations are kept, or reconciled with the library type when it changes. + /// + public List? ArtworkProviders { get; set; } + + /// + /// Gets or sets the book readers of the media library, and whether each one is enabled. When absent, the readers are configured with their defaults on create, and on update + /// the stored configurations are kept, or reconciled with the library type when it changes. + /// + public List? BookReaders { get; set; } } diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryProviderSelectionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryProviderSelectionDto.cs new file mode 100644 index 00000000..e8836574 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryProviderSelectionDto.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Libraries; + +/// +/// Data transfer object for the choice made for one metadata provider, artwork provider or book reader of a media library. +/// +[DebuggerDisplay("PluginId: {PluginId}; IsEnabled: {IsEnabled}")] +public class LibraryProviderSelectionDto +{ + /// + /// Gets or sets the unique identifier of the plugin providing the metadata provider, artwork provider or book reader. + /// + public Guid PluginId { get; set; } + + /// + /// Gets or sets whether the provider or reader is enabled for the media library. Optional, the stored state is kept when absent, and a provider or reader without a stored state starts disabled. + /// + public bool? IsEnabled { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequest.cs new file mode 100644 index 00000000..f905852b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents a request for retrieving the artwork providers available for a media library type. +/// +/// The media library type whose available artwork providers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeArtworkProvidersRequest( + string LibraryType +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequest.cs new file mode 100644 index 00000000..610d219f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents a request for retrieving the book readers available for a media library type. +/// +/// The media library type whose available book readers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeBookReadersRequest( + string LibraryType +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequest.cs new file mode 100644 index 00000000..ec5a3ddd --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents a request for retrieving the metadata providers available for a media library type. +/// +/// The media library type whose available metadata providers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeMetadataProvidersRequest( + string LibraryType +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs deleted file mode 100644 index 86d84308..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Requests.Plugins; - -/// -/// Represents a request to reorder the artwork providers of a media library. -/// -/// The Id of the media library whose artwork providers are reordered. Required. -/// The plugin Ids in the new order, from highest to lowest rank. Required. -[DebuggerDisplay("LibraryId: {LibraryId}")] -public record ReorderLibraryArtworkProvidersRequest( - Guid LibraryId, - List PluginIds -); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs deleted file mode 100644 index a4048843..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.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 record ReorderLibraryMetadataProvidersRequest( - Guid LibraryId, - List PluginIds -); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetBookReaderEnabledRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetBookReaderEnabledRequest.cs deleted file mode 100644 index 9c934831..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetBookReaderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Requests.Plugins; - -/// -/// Represents a request to enable or disable a book reader for a media library. -/// -/// The Id of the media library whose book reader is enabled or disabled. Required. -/// The unique identifier of the plugin providing the book reader. Required. -/// Whether the book reader should be enabled for the media library. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public record SetBookReaderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs deleted file mode 100644 index aa55773d..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Requests.Plugins; - -/// -/// Represents a request to enable or disable an artwork provider for a media library. -/// -/// The Id of the media library whose artwork provider is enabled or disabled. Required. -/// The unique identifier of the plugin providing the artwork. Required. -/// Whether the artwork provider should be enabled for the media library. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public record SetLibraryArtworkProviderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs deleted file mode 100644 index bf442946..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.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. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public record SetLibraryMetadataProviderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs index 64ebcdc6..837be446 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs @@ -23,12 +23,10 @@ public static partial class ApiRoutes public const string CANCEL_LIBRARY_SCAN = "libraries/{libraryId}/scans/{scanId}/cancel"; public const string GET_LIBRARY_PATH_TEMPLATE_PARTS = "libraries/path-template-parts/{libraryType}"; public const string GET_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers"; - public const string SET_LIBRARY_METADATA_PROVIDER_ENABLED = "libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; - public const string REORDER_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers/reorder"; public const string GET_LIBRARY_ARTWORK_PROVIDERS = "libraries/{libraryId}/artwork-providers"; - public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; - public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "libraries/{libraryId}/artwork-providers/reorder"; public const string GET_LIBRARY_BOOK_READERS = "libraries/{libraryId}/book-readers"; - public const string SET_LIBRARY_BOOK_READER_ENABLED = "libraries/{libraryId}/book-readers/{pluginId}/enabled"; + public const string GET_LIBRARY_TYPE_METADATA_PROVIDERS = "libraries/metadata-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_ARTWORK_PROVIDERS = "libraries/artwork-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_BOOK_READERS = "libraries/book-readers/{libraryType}"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs index d89cf6a3..2f1a8cdf 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs @@ -24,12 +24,10 @@ public static partial class WebRoutes public const string CANCEL_LIBRARY_SCAN = "{culture}/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"; public const string GET_LIBRARY_PATH_TEMPLATE_PARTS = "{culture}/libraries/manage/api-get-path-template-parts/{libraryType}"; public const string GET_METADATA_PROVIDERS = "{culture}/libraries/manage/api-get-metadata-providers/{libraryId}"; - public const string SET_METADATA_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-metadata-provider-enabled"; - public const string REORDER_METADATA_PROVIDERS = "{culture}/libraries/manage/api-reorder-metadata-providers"; public const string GET_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-get-artwork-providers/{libraryId}"; - public const string SET_ARTWORK_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-artwork-provider-enabled"; - public const string REORDER_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-reorder-artwork-providers"; public const string GET_BOOK_READERS = "{culture}/libraries/manage/api-get-book-readers/{libraryId}"; - public const string SET_BOOK_READER_ENABLED = "{culture}/libraries/manage/api-set-book-reader-enabled"; + public const string GET_LIBRARY_TYPE_METADATA_PROVIDERS = "{culture}/libraries/manage/api-get-library-type-metadata-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-get-library-type-artwork-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_BOOK_READERS = "{culture}/libraries/manage/api-get-library-type-book-readers/{libraryType}"; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs index 0396bf28..e8d6974d 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; @@ -26,6 +27,7 @@ public class AddLibraryViewEndpoint : BaseEndpoint Routes(WebRoutes.LibraryManagement.ADD_LIBRARY); DontAutoTag(); Options(options => options.WithTags("Libraries")); + Policies(AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs index b84ee688..33f77008 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Requests.Library.Management; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; @@ -39,6 +40,7 @@ public class DeleteLibraryEndpoint : BaseEndpoint DontAutoTag(); Options(options => options.WithTags("Libraries")); EnableAntiforgery(); + Policies(AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs index b0106ea2..c22c3faa 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Common.Requests.Library.Management; using Lumina.Presentation.Web.Common.Routes; @@ -39,6 +40,7 @@ public class EditLibraryViewEndpoint : BaseEndpoint Routes(WebRoutes.LibraryManagement.EDIT_LIBRARY); DontAutoTag(); Options(options => options.WithTags("Libraries")); + Policies(AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpoint.cs new file mode 100644 index 00000000..b9c536ec --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-library-type-artwork-providers/{libraryType} route. +/// +public class GetLibraryTypeArtworkProvidersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetLibraryTypeArtworkProvidersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the artwork providers available for a media library type. + /// + /// The request containing the media library type whose available artwork providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeArtworkProvidersRequest request, CancellationToken cancellationToken) + { + LibraryArtworkProviderDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString(request.LibraryType)), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs new file mode 100644 index 00000000..710e538b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersEndpointSummary() + { + Summary = "Retrieves the artwork providers available for a media library type."; + Description = "Retrieves the artwork providers that support the media library type identified by the route, disabled and ranked in alphabetical order, the way a new media library of that type starts."; + RequestParam(r => r.LibraryType, "The media library type whose available artwork providers are retrieved. Required."); + + ExampleRequest = new GetLibraryTypeArtworkProvidersRequest( + LibraryType: "Book" + ); + + Response(200, "The artwork providers available for the media library type are returned."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs new file mode 100644 index 00000000..5636f4b3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-library-type-book-readers/{libraryType} route. +/// +public class GetLibraryTypeBookReadersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetLibraryTypeBookReadersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_BOOK_READERS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the book readers available for a media library type. + /// + /// The request containing the media library type whose available book readers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeBookReadersRequest request, CancellationToken cancellationToken) + { + LibraryBookReaderDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS.Replace("{libraryType}", Uri.EscapeDataString(request.LibraryType)), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs new file mode 100644 index 00000000..d3c05dbc --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersEndpointSummary() + { + Summary = "Retrieves the book readers available for a media library type."; + Description = "Retrieves the book readers that support the media library type identified by the route, with their supported file extensions, disabled and in alphabetical order, the way a new media library of that type starts."; + RequestParam(r => r.LibraryType, "The media library type whose available book readers are retrieved. Required."); + + ExampleRequest = new GetLibraryTypeBookReadersRequest( + LibraryType: "Book" + ); + + Response(200, "The book readers available for the media library type are returned."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs new file mode 100644 index 00000000..56104bcf --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-library-type-metadata-providers/{libraryType} route. +/// +public class GetLibraryTypeMetadataProvidersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetLibraryTypeMetadataProvidersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_METADATA_PROVIDERS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the metadata providers available for a media library type. + /// + /// The request containing the media library type whose available metadata providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeMetadataProvidersRequest request, CancellationToken cancellationToken) + { + LibraryMetadataProviderDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString(request.LibraryType)), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs new file mode 100644 index 00000000..eab5de61 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersEndpointSummary() + { + Summary = "Retrieves the metadata providers available for a media library type."; + Description = "Retrieves the metadata providers that support the media library type identified by the route, disabled and ranked in alphabetical order, the way a new media library of that type starts."; + RequestParam(r => r.LibraryType, "The media library type whose available metadata providers are retrieved. Required."); + + ExampleRequest = new GetLibraryTypeMetadataProvidersRequest( + LibraryType: "Book" + ); + + Response(200, "The metadata providers available for the media library type are returned."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs index f553d0eb..2a561166 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -15,6 +17,17 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; /// public class LibrariesIndexViewEndpoint : BaseEndpoint { + private readonly IAuthorizationService _authorizationService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization checks against the remote API. + public LibrariesIndexViewEndpoint(IAuthorizationService authorizationService) + { + _authorizationService = authorizationService; + } + /// /// Configures the endpoint. /// @@ -32,8 +45,12 @@ public class LibrariesIndexViewEndpoint : BaseEndpoint /// /// The request object. /// Cancellation token that can be used to stop the execution. - public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { - return Task.FromResult(View("/Core/Views/Library/Management/Index.cshtml")); + // Changing and deleting a media library takes the permission to manage media libraries, or the administrator role, the same rule the API applies, + // so the actions are only offered to the users the API would let through. + bool canManageLibraries = await _authorizationService.IsInRoleAsync("Admin", cancellationToken).ConfigureAwait(false) || + await _authorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false); + return View("/Core/Views/Library/Management/Index.cshtml", new LibrariesIndexPageDto(canManageLibraries)); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpoint.cs deleted file mode 100644 index fc468634..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpoint.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders; - -/// -/// API endpoint for the /{culture}/libraries/manage/api-reorder-artwork-providers route. -/// -public class ReorderArtworkProvidersEndpoint : BaseEndpoint -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public ReorderArtworkProvidersEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.PUT); - Routes(WebRoutes.LibraryManagement.REORDER_ARTWORK_PROVIDERS); - DontAutoTag(); - Options(options => options.WithTags("Libraries")); - EnableAntiforgery(); - } - - /// - /// Reorders the artwork providers of a media library. - /// - /// The request containing the Id of the media library and the plugin Ids in the new order. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(ReorderLibraryArtworkProvidersRequest request, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync(ApiRoutes.Libraries.REORDER_LIBRARY_ARTWORK_PROVIDERS.Replace("{libraryId}", request.LibraryId.ToString()), request, cancellationToken).ConfigureAwait(false); - return JsonSuccess(); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointSummary.cs deleted file mode 100644 index fbb75201..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointSummary.cs +++ /dev/null @@ -1,34 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class ReorderArtworkProvidersEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderArtworkProvidersEndpointSummary() - { - Summary = "Reorders the artwork providers of a media library."; - Description = "Reorders the artwork providers of the media library identified by the route, in the provided order."; - RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are reordered. Required."); - RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); - - ExampleRequest = new ReorderLibraryArtworkProvidersRequest( - LibraryId: Guid.NewGuid(), - PluginIds: [Guid.NewGuid(), Guid.NewGuid()] - ); - - Response(200, "The artwork providers of the media library are reordered.", example: new SuccessResponse(true)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpoint.cs deleted file mode 100644 index 89ea7054..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpoint.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; - -/// -/// API endpoint for the /{culture}/libraries/manage/api-reorder-metadata-providers route. -/// -public class ReorderMetadataProvidersEndpoint : BaseEndpoint -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public ReorderMetadataProvidersEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.PUT); - Routes(WebRoutes.LibraryManagement.REORDER_METADATA_PROVIDERS); - DontAutoTag(); - Options(options => options.WithTags("Libraries")); - EnableAntiforgery(); - } - - /// - /// Reorders the metadata providers of a media library. - /// - /// 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) - { - await _apiHttpClient.PutAsync(ApiRoutes.Libraries.REORDER_LIBRARY_METADATA_PROVIDERS.Replace("{libraryId}", request.LibraryId.ToString()), request, cancellationToken).ConfigureAwait(false); - return JsonSuccess(); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs deleted file mode 100644 index 1ea20a6c..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs +++ /dev/null @@ -1,39 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class ReorderMetadataProvidersEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderMetadataProvidersEndpointSummary() - { - Summary = "Reorders the metadata providers of a media library."; - Description = "Reorders the metadata providers of the media library identified by the route."; - 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."); - - ExampleRequest = new ReorderLibraryMetadataProvidersRequest( - LibraryId: Guid.NewGuid(), - PluginIds: - [ - Guid.NewGuid(), - Guid.NewGuid(), - ] - ); - - Response(200, "The metadata providers of the media library are reordered.", example: new SuccessResponse(true)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs index 338d22c4..9f068782 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs @@ -21,7 +21,6 @@ public class SaveLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library. Optional, when creating a new media library."); - RequestParam(r => r.UserId, "The unique identifier of the user owning the media library. Optional."); RequestParam(r => r.Title, "The title of the media library. Required."); RequestParam(r => r.LibraryType, "The type of the media library. Required."); RequestParam(r => r.CoverImage, "The path of the image file used as the cover of the media library. Optional."); @@ -35,6 +34,9 @@ public class SaveLibraryEndpointSummary : Summary r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items should be tracked, or not. Optional, the default of the library type is used on create, and the stored value is kept on update."); RequestParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the default of the library type is used on create, and the stored value is kept on update."); RequestParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent."); + RequestParam(r => r.MetadataProviders, "The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the providers are configured with their defaults on create, and the stored configurations are kept on update, when absent."); + RequestParam(r => r.ArtworkProviders, "The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the providers are configured with their defaults on create, and the stored configurations are kept on update, when absent."); + RequestParam(r => r.BookReaders, "The book readers of the media library, and whether each one is enabled. Optional, the readers are configured with their defaults on create, and the stored configurations are kept on update, when absent."); ExampleRequest = new LibraryDto(); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpoint.cs deleted file mode 100644 index 4d454ce8..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpoint.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled; - -/// -/// API endpoint for the /{culture}/libraries/manage/api-set-artwork-provider-enabled route. -/// -public class SetArtworkProviderEnabledEndpoint : BaseEndpoint -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public SetArtworkProviderEnabledEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.PUT); - Routes(WebRoutes.LibraryManagement.SET_ARTWORK_PROVIDER_ENABLED); - DontAutoTag(); - Options(options => options.WithTags("Libraries")); - EnableAntiforgery(); - } - - /// - /// Enables or disables an artwork provider of a media library. - /// - /// The request containing the Ids of the media library and of the plugin, and whether the provider is enabled. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetLibraryArtworkProviderEnabledRequest request, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync(ApiRoutes.Libraries.SET_LIBRARY_ARTWORK_PROVIDER_ENABLED.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); - return JsonSuccess(); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointSummary.cs deleted file mode 100644 index 7a1922e3..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointSummary.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetArtworkProviderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetArtworkProviderEnabledEndpointSummary() - { - Summary = "Enables or disables an artwork provider of a media library."; - Description = "Enables or disables the artwork provider of the media library identified by the route."; - RequestParam(r => r.LibraryId, "The Id of the media library whose artwork provider is enabled or disabled. Required."); - RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork. Required."); - RequestParam(r => r.IsEnabled, "Whether the artwork provider should be enabled for the media library, or not. Required."); - - ExampleRequest = new SetLibraryArtworkProviderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - Response(200, "The artwork provider of the media library is enabled or disabled.", example: new SuccessResponse(true)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpoint.cs deleted file mode 100644 index 423d5292..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpoint.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; - -/// -/// API endpoint for the /{culture}/libraries/manage/api-set-book-reader-enabled route. -/// -public class SetBookReaderEnabledEndpoint : BaseEndpoint -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public SetBookReaderEnabledEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.PUT); - Routes(WebRoutes.LibraryManagement.SET_BOOK_READER_ENABLED); - DontAutoTag(); - Options(options => options.WithTags("Libraries")); - EnableAntiforgery(); - } - - /// - /// Enables or disables a book reader of a media library. - /// - /// The request containing the Ids of the media library and of the plugin, and whether the book reader is enabled. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetBookReaderEnabledRequest request, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync(ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); - return JsonSuccess(); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs deleted file mode 100644 index bc08a3e0..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetBookReaderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetBookReaderEnabledEndpointSummary() - { - Summary = "Enables or disables a book reader of a media library."; - Description = "Enables or disables the book reader of the media library identified by the route."; - RequestParam(r => r.LibraryId, "The Id of the media library whose book reader is enabled or disabled. Required."); - RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader. Required."); - RequestParam(r => r.IsEnabled, "Whether the book reader should be enabled for the media library, or not. Required."); - - ExampleRequest = new SetBookReaderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - Response(200, "The book reader of the media library is enabled or disabled.", example: new SuccessResponse(true)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpoint.cs deleted file mode 100644 index c27924c3..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpoint.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; - -/// -/// API endpoint for the /{culture}/libraries/manage/api-set-metadata-provider-enabled route. -/// -public class SetMetadataProviderEnabledEndpoint : BaseEndpoint -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public SetMetadataProviderEnabledEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.PUT); - Routes(WebRoutes.LibraryManagement.SET_METADATA_PROVIDER_ENABLED); - DontAutoTag(); - Options(options => options.WithTags("Libraries")); - EnableAntiforgery(); - } - - /// - /// Enables or disables a metadata provider of a media library. - /// - /// The request containing the Ids of the media library and of the plugin, and whether the provider is enabled. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetLibraryMetadataProviderEnabledRequest request, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync(ApiRoutes.Libraries.SET_LIBRARY_METADATA_PROVIDER_ENABLED.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); - return JsonSuccess(); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs deleted file mode 100644 index 163d7afe..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetMetadataProviderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetMetadataProviderEnabledEndpointSummary() - { - Summary = "Enables or disables a metadata provider of a media library."; - Description = "Enables or disables the metadata provider of the media library identified by the route."; - 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, or not. Required."); - - ExampleRequest = new SetLibraryMetadataProviderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - Response(200, "The metadata provider of the media library is enabled or disabled.", example: new SuccessResponse(true)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx index d3c3df28..990838bb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx @@ -540,11 +540,11 @@ لا يمكن أن يكون معرف الإضافة فارغًا! - - لا يمكن أن تكون قائمة معرفات الإضافات فارغة! + + لا يمكن اختيار الإضافة نفسها أكثر من مرة! - - لا يمكن أن تكون قائمة معرفات الإضافات فارغة! + + الإضافة لا تدعم نوع مكتبة الوسائط! لم يتم العثور على الإضافة! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index 7acf27db..d50bb406 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -540,11 +540,11 @@ Die Plugin-ID darf nicht leer sein! - - Die Plugin-ID-Liste darf nicht leer sein! + + Dasselbe Plugin darf nicht mehrfach ausgewählt werden! - - Die Plugin-ID-Liste darf nicht null sein! + + Das Plugin unterstützt den Medienbibliothekstyp nicht! Das Plugin wurde nicht gefunden! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index 81d5e56c..4fb7b5ce 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -540,11 +540,11 @@ The plugin Id cannot be empty! - - The plugin Ids list cannot be empty! + + The same plugin cannot be chosen more than once! - - The plugin Ids list cannot be null! + + The plugin does not support the media library type! The plugin was not found! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index b36fedaf..eda9e4c2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -540,11 +540,11 @@ ¡El Id del plugin no puede estar vacío! - - ¡La lista de Ids de plugins no puede estar vacía! + + ¡No se puede elegir el mismo plugin más de una vez! - - ¡La lista de Ids de plugins no puede ser nula! + + ¡El plugin no admite el tipo de biblioteca multimedia! ¡El plugin no fue encontrado! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index fc764a80..21b5f621 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -540,11 +540,11 @@ L'Id du plugin ne peut pas être vide ! - - La liste des Ids de plugins ne peut pas être vide ! + + Le même plugin ne peut pas être choisi plus d'une fois ! - - La liste des Ids de plugins ne peut pas être nulle ! + + Le plugin ne prend pas en charge le type de médiathèque ! Le plugin est introuvable ! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index 56c362f1..faab4cbb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -540,11 +540,11 @@ L'Id del plugin non può essere vuoto! - - L'elenco degli Id dei plugin non può essere vuoto! + + Lo stesso plugin non può essere scelto più di una volta! - - L'elenco degli Id dei plugin non può essere nullo! + + Il plugin non supporta il tipo di libreria multimediale! Il plugin non è stato trovato! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index 804b2b90..8a4caeeb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -540,11 +540,11 @@ プラグイン ID を空にすることはできません。 - - プラグイン ID のリストを空にすることはできません。 + + 同じプラグインを複数回選択することはできません。 - - プラグイン ID のリストを null にすることはできません。 + + このプラグインはメディアライブラリの種類に対応していません。 プラグインが見つかりませんでした。 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 8d705929..20709fe1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -540,11 +540,11 @@ The plugin Id cannot be empty! - - The plugin Ids list cannot be empty! + + The same plugin cannot be chosen more than once! - - The plugin Ids list cannot be null! + + The plugin does not support the media library type! The plugin was not found! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index ae2450db..cf8669fd 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -540,11 +540,11 @@ Id-ul pluginului nu poate fi gol! - - Lista Id-urilor de pluginuri nu poate fi goala! + + Același plugin nu poate fi ales de mai multe ori! - - Lista Id-urilor de pluginuri nu poate fi nula! + + Pluginul nu suportă tipul bibliotecii media! Pluginul nu a fost gasit! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx index 197e157e..b203e4e0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx @@ -540,11 +540,11 @@ Ідентифікатор плагіна не може бути порожнім! - - Список ідентифікаторів плагінів не може бути порожнім! + + Той самий плагін не можна вибрати більше одного разу! - - Список ідентифікаторів плагінів не може бути порожнім! + + Плагін не підтримує тип медіатеки! Плагін не знайдено! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index cdcf3979..b8ec1f6d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -540,11 +540,11 @@ 插件 Id 不能为空! - - 插件 Id 列表不能为空! + + 同一插件不能被多次选择! - - 插件 Id 列表不能为 null! + + 该插件不支持此媒体库类型! 未找到插件! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx index 472452b6..89ebb567 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx @@ -333,9 +333,6 @@ نقل لأسفل - - تم حفظ الترتيب - مزوّدو البيانات الوصفية المستخدمون لإثراء عناصر هذه المكتبة، بالترتيب الذي يتم تجريبهم به. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx index 3951cc56..9c2ca317 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx @@ -333,9 +333,6 @@ Nach unten - - Reihenfolge gespeichert - Die Metadatenanbieter, die verwendet werden, um die Elemente dieser Bibliothek anzureichern, in der Reihenfolge, in der sie versucht werden. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx index 69679d6a..8045254d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx @@ -333,9 +333,6 @@ Move down - - Order saved - The metadata providers used to enrich the items of this library, in the order they are tried. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx index 70d5c756..40eb7a05 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx @@ -333,9 +333,6 @@ Bajar - - Orden guardado - Los proveedores de metadatos utilizados para enriquecer los elementos de esta biblioteca, en el orden en que se prueban. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx index 05c47ce0..60a3c87a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx @@ -333,9 +333,6 @@ Descendre - - Ordre enregistré - Les fournisseurs de métadonnées utilisés pour enrichir les éléments de cette bibliothèque, dans l'ordre où ils sont essayés. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx index 6141fb44..e3db91a5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx @@ -333,9 +333,6 @@ Sposta giù - - Ordine salvato - I fornitori di metadati utilizzati per arricchire gli elementi di questa libreria, nell'ordine in cui vengono provati. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx index 4dcdd3f0..a842698c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx @@ -333,9 +333,6 @@ 下へ移動 - - 順序を保存しました - このライブラリのアイテムを補完するために使用されるメタデータプロバイダーを、試行する順序で指定します。 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx index 69679d6a..8045254d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx @@ -333,9 +333,6 @@ Move down - - Order saved - The metadata providers used to enrich the items of this library, in the order they are tried. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx index 285d7a4f..903099e8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx @@ -333,9 +333,6 @@ Mută în jos - - Ordine salvată - Furnizorii de metadate folosiți pentru a îmbogăți elementele acestei biblioteci, în ordinea în care sunt încercați. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx index 4de84f09..c5f835d3 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx @@ -333,9 +333,6 @@ Вниз - - Порядок збережено - Постачальники метаданих, які використовуються для збагачення елементів цієї бібліотеки, у порядку, в якому вони випробовуються. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx index ca2f34b4..c75d97e5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx @@ -333,9 +333,6 @@ 下移 - - 顺序已保存 - 用于丰富此库项目内容的元数据提供程序,按其尝试顺序排列。 diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml index e312d8cc..d656fd66 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml @@ -5,7 +5,10 @@ @using Lumina.Presentation.Web.Common.DTO.Libraries @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization +@using System.Collections.Generic @using System.Security.Claims +@using System.Text.Json +@model LibrariesIndexPageDto @{ // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. @@ -165,58 +168,89 @@ // Create cleanup registry for this view. const cleanupFunctions = []; let isInitialized = false; - const jsLocalizedLibraryScanStatuses = { - Completed: '@_localizer["Completed"]', - Failed: '@_localizer["Failed"]', - Canceled: '@_localizer["Canceled"]', - Cancelling: '@_localizer["Cancelling"]' - }; - const jsLocalizedLibraryScanJobsStatuses = { - DiscoveringFiles: '@_localizer["DiscoveringFiles"]', - ComparingFileHashes: '@_localizer["ComparingFileHashes"]', - HashingFileContents: '@_localizer["HashingFileContents"]', - ExtractingMetadata: '@_localizer["ExtractingMetadata"]', - SavingScanData: '@_localizer["SavingScanData"]', - InvalidatingStaleEnrichment: '@_localizer["InvalidatingStaleEnrichment"]', - EnrichingMetadata: '@_localizer["EnrichingMetadata"]', - ResolvingArtwork: '@_localizer["ResolvingArtwork"]', - Queued: '@_localizer["Queued"]' - }; - const jsLocalizedLibraryTypes = { - Book: '@_localizer["Book"]', - EBook: '@_localizer["EBook"]', - BookSeries: '@_localizer["BookSeries"]', - ComicBook: '@_localizer["ComicBook"]', - ComicSeries: '@_localizer["ComicSeries"]', - Magazine: '@_localizer["Magazine"]', - Manga: '@_localizer["Manga"]', - GraphicNovel: '@_localizer["GraphicNovel"]', - AcademicPaper: '@_localizer["AcademicPaper"]', - SheetMusic: '@_localizer["SheetMusic"]', - Screenplay: '@_localizer["Screenplay"]', - TvShow: '@_localizer["TvShow"]', - Movie: '@_localizer["Movie"]', - FilmSeries: '@_localizer["FilmSeries"]', - FilmFranchise: '@_localizer["FilmFranchise"]', - Concert: '@_localizer["Concert"]', - Documentary: '@_localizer["Documentary"]', - Tutorial: '@_localizer["Tutorial"]', - Personal: '@_localizer["Personal"]', - Anime: '@_localizer["Anime"]', - Youtube: '@_localizer["Youtube"]', - Videoclip: '@_localizer["Videoclip"]', - Music: '@_localizer["Music"]', - AudioBook: '@_localizer["AudioBook"]', - LivePerformance: '@_localizer["LivePerformance"]', - Interview: '@_localizer["Interview"]', - Cover: '@_localizer["Cover"]', - Remix: '@_localizer["Remix"]', - Soundeffect: '@_localizer["Soundeffect"]', - Podcast: '@_localizer["Podcast"]', - RadioShow: '@_localizer["RadioShow"]', - PhotoAlbum: '@_localizer["PhotoAlbum"]', - Other: '@_localizer["Other"]' - }; + // Changing and deleting a media library takes the permission to manage media libraries, or the administrator role, so the edit and delete actions are + // only rendered for the users the server would let through. + const canManageLibraries = @(Model.CanManageLibraries ? "true" : "false"); + // The localized strings used inside this script are injected as JSON, not as raw HTML text: Razor HTML-encodes non-ASCII characters into numeric + // entities, which the browser does not decode inside a script element, and a translation containing a quote, a backtick or "${" would break out of + // the string or template literal it was placed in. JSON escapes them, so the script reads them correctly. + const jsLocalizedLibraryScanStatuses = @Html.Raw(JsonSerializer.Serialize(new Dictionary + { + ["Completed"] = _localizer["Completed"].Value, + ["Failed"] = _localizer["Failed"].Value, + ["Canceled"] = _localizer["Canceled"].Value, + ["Cancelling"] = _localizer["Cancelling"].Value + })); + const jsLocalizedLibraryScanJobsStatuses = @Html.Raw(JsonSerializer.Serialize(new Dictionary + { + ["DiscoveringFiles"] = _localizer["DiscoveringFiles"].Value, + ["ComparingFileHashes"] = _localizer["ComparingFileHashes"].Value, + ["HashingFileContents"] = _localizer["HashingFileContents"].Value, + ["ExtractingMetadata"] = _localizer["ExtractingMetadata"].Value, + ["SavingScanData"] = _localizer["SavingScanData"].Value, + ["InvalidatingStaleEnrichment"] = _localizer["InvalidatingStaleEnrichment"].Value, + ["EnrichingMetadata"] = _localizer["EnrichingMetadata"].Value, + ["ResolvingArtwork"] = _localizer["ResolvingArtwork"].Value, + ["Queued"] = _localizer["Queued"].Value + })); + const jsLocalizedLibraryTypes = @Html.Raw(JsonSerializer.Serialize(new Dictionary + { + ["Book"] = _localizer["Book"].Value, + ["EBook"] = _localizer["EBook"].Value, + ["BookSeries"] = _localizer["BookSeries"].Value, + ["ComicBook"] = _localizer["ComicBook"].Value, + ["ComicSeries"] = _localizer["ComicSeries"].Value, + ["Magazine"] = _localizer["Magazine"].Value, + ["Manga"] = _localizer["Manga"].Value, + ["GraphicNovel"] = _localizer["GraphicNovel"].Value, + ["AcademicPaper"] = _localizer["AcademicPaper"].Value, + ["SheetMusic"] = _localizer["SheetMusic"].Value, + ["Screenplay"] = _localizer["Screenplay"].Value, + ["TvShow"] = _localizer["TvShow"].Value, + ["Movie"] = _localizer["Movie"].Value, + ["FilmSeries"] = _localizer["FilmSeries"].Value, + ["FilmFranchise"] = _localizer["FilmFranchise"].Value, + ["Concert"] = _localizer["Concert"].Value, + ["Documentary"] = _localizer["Documentary"].Value, + ["Tutorial"] = _localizer["Tutorial"].Value, + ["Personal"] = _localizer["Personal"].Value, + ["Anime"] = _localizer["Anime"].Value, + ["Youtube"] = _localizer["Youtube"].Value, + ["Videoclip"] = _localizer["Videoclip"].Value, + ["Music"] = _localizer["Music"].Value, + ["AudioBook"] = _localizer["AudioBook"].Value, + ["LivePerformance"] = _localizer["LivePerformance"].Value, + ["Interview"] = _localizer["Interview"].Value, + ["Cover"] = _localizer["Cover"].Value, + ["Remix"] = _localizer["Remix"].Value, + ["Soundeffect"] = _localizer["Soundeffect"].Value, + ["Podcast"] = _localizer["Podcast"].Value, + ["RadioShow"] = _localizer["RadioShow"].Value, + ["PhotoAlbum"] = _localizer["PhotoAlbum"].Value, + ["Other"] = _localizer["Other"].Value + })); + const jsLocalizedLabels = @Html.Raw(JsonSerializer.Serialize(new Dictionary + { + ["Yes"] = _localizer["Yes"].Value, + ["No"] = _localizer["No"].Value, + ["Completed"] = _localizer["Completed"].Value, + ["Failed"] = _localizer["Failed"].Value, + ["Canceled"] = _localizer["Canceled"].Value, + ["CancelScan"] = _localizer["CancelScan"].Value, + ["Scan"] = _localizer["Scan"].Value, + ["Edit"] = _localizer["Edit"].Value, + ["Remove"] = _localizer["Remove"].Value, + ["DeleteLibraryConfirm"] = _localizer["DeleteLibraryConfirm"].Value, + ["LibraryDeleted"] = _localizer["LibraryDeleted"].Value + })); + + // Escapes a value for use as text or as a quoted attribute value inside markup, since the titles of the libraries are typed by their users. + function escapeHtml(value) { + const div = document.createElement('div'); + div.textContent = value ?? ''; + return div.innerHTML.replace(/"/g, '"'); + } + // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. const btnScanAllLibraries = document.getElementById('btn-scan-all-libraries'); const btnCancelLibrariesScan = document.getElementById('btn-cancel-libraries-scan'); @@ -250,13 +284,13 @@ btnScanAllLibraries.style.display = 'block'; tbody.innerHTML = response.map(library => { const editUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.EDIT_LIBRARY, new { id = default(Guid) })' - .replace('/@(default(Guid))', `/${library.id}`); + .replace('/@(default(Guid))', `/${encodeURIComponent(library.id)}`); return ` - - ${library.title} - ${jsLocalizedLibraryTypes[library.libraryType]} - ${library.isEnabled === true ? `@_localizer["Yes"]` : `@_localizer["No"]`} - ${library.isLocked === true ? `@_localizer["Yes"]` : `@_localizer["No"]`} + + ${escapeHtml(library.title)} + ${escapeHtml(jsLocalizedLibraryTypes[library.libraryType] ?? library.libraryType)} + ${escapeHtml(library.isEnabled === true ? jsLocalizedLabels.Yes : jsLocalizedLabels.No)} + ${escapeHtml(library.isLocked === true ? jsLocalizedLabels.Yes : jsLocalizedLabels.No)} - @if (id is not null) - { + + + +
@@ -341,6 +346,23 @@ // Create cleanup registry for this view. const cleanupFunctions = []; + // The localized labels of the rows built by this script, injected as JSON for the same reason as the path part labels below, and so that a translation + // containing a backtick or "${" cannot break out of the template literals that render the rows. + const rowLabels = @Html.Raw(JsonSerializer.Serialize(new Dictionary + { + ["remove"] = _localizer["Remove"].Value, + ["moveUp"] = _localizer["MoveUp"].Value, + ["moveDown"] = _localizer["MoveDown"].Value + })); + + // Escapes a value for use as text or as a quoted attribute value inside markup, since the chosen paths and the names, Ids and extensions of the providers + // are not controlled by this page. + function escapeHtml(value) { + const div = document.createElement('div'); + div.textContent = value ?? ''; + return div.innerHTML.replace(/"/g, '"'); + } + // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. const saveSuccess = document.getElementById('save-success'); const btnBackToLibraries = document.getElementById('btn-back-to-libraries'); @@ -374,7 +396,6 @@ const completionThresholdPercentage = inputCompletionThresholdPercentage.value.trim(); const formData = { Id: form.querySelector('[name="Id"]').value || null, - UserId: form.querySelector('[name="UserId"]').value || null, Title: form.querySelector('[name="Title"]').value, LibraryType: form.querySelector('#library-selected-item').getAttribute('data-value'), ContentLocations: Array.from(mediaDirectoriesFormTable.querySelectorAll('.form-table-row span')) @@ -404,7 +425,12 @@ Representation: getPathTemplatePillRepresentation(pill), IsOptional: optional ? optional.checked : false }; - }) + }), + // The provider choices are saved together with the library. A list that could not be loaded is sent as null, so the server keeps + // or reconciles what it has, instead of being told that every provider was left out. + MetadataProviders: areMetadataProvidersLoaded ? getProviderSelections(metadataProvidersTbody, 'metadata-provider-enabled') : null, + ArtworkProviders: areArtworkProvidersLoaded ? getProviderSelections(artworkProvidersTbody, 'artwork-provider-enabled') : null, + BookReaders: areBookReadersLoaded ? getProviderSelections(bookReadersTbody, 'book-reader-enabled') : null }; const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SAVE_LIBRARY)', formData); if (data) { @@ -428,8 +454,8 @@ if (!isDuplicate) { mediaDirectoriesFormTable.insertAdjacentHTML('beforeend', `
- ${normalizedPath} - @_localizer[ + ${escapeHtml(normalizedPath)} + ${escapeHtml(rowLabels.remove)}
`); } @@ -446,8 +472,8 @@ const path = paths[0]; // Only use the first path. mediaCoverFormTable.insertAdjacentHTML('beforeend', `
- ${path} - @_localizer[ + ${escapeHtml(path)} + ${escapeHtml(rowLabels.remove)}
`); } @@ -494,169 +520,121 @@ }; const id = '@id'; - const metadataProvidersTable = document.getElementById('metadata-providers-table'); - const metadataProvidersTbody = metadataProvidersTable ? metadataProvidersTable.querySelector('tbody') : null; + const metadataProvidersSection = document.getElementById('metadata-providers-section'); + const metadataProvidersTbody = document.getElementById('metadata-providers-table').querySelector('tbody'); + const artworkProvidersSection = document.getElementById('artwork-providers-section'); + const artworkProvidersTbody = document.getElementById('artwork-providers-table').querySelector('tbody'); + const bookReadersSection = document.getElementById('book-readers-section'); + const bookReadersTbody = document.getElementById('book-readers-table').querySelector('tbody'); + // Whether each provider list was loaded for the selected library type. A list that failed to load is not sent when the library is saved. + let areMetadataProvidersLoaded = false; + let areArtworkProvidersLoaded = false; + let areBookReadersLoaded = false; + // Incremented on every load, so that the responses of a load started for a previously selected library type are discarded. + let providersLoadVersion = 0; - // Loads the metadata providers configured for the library, when editing an existing library. - async function loadMetadataProvidersAsync() { - if (!id || !metadataProvidersTbody) return; - const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_METADATA_PROVIDERS, new { libraryId = default(Guid) })' - .replace('/@(default(Guid))', `/${id}`); // The libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. - const response = await callApiGetAsync(url); - if (response && response.length > 0) { - metadataProvidersTbody.innerHTML = response.map((provider, index) => renderMetadataProviderRow(provider, index, response.length)).join(''); + // Loads the metadata providers, artwork providers and book readers of the selected library type. A new library lists the providers available for the + // type, the way a new library of that type starts. An existing library merges its stored configuration with them, the same way the server reconciles + // the configuration when the library is saved: the stored providers that the type still supports keep their state and order, the newly supported + // ones are added disabled after them, and the stored providers that the type no longer supports are left out, so they are never submitted. + async function loadProvidersAsync() { + const libraryType = getSelectedLibraryType(); + const loadVersion = ++providersLoadVersion; + areMetadataProvidersLoaded = false; + areArtworkProvidersLoaded = false; + areBookReadersLoaded = false; + if (!libraryType) { + renderProviders(null, null, null); + return; } + // The Id and the type need to be replaced here, because GetAbsoluteUrl is server side, while the library Id and the selected type are client side. + const encodedLibraryType = encodeURIComponent(libraryType); + const requests = [ + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_METADATA_PROVIDERS, new { libraryType = "Book" })'.replace('/Book', `/${encodedLibraryType}`)), + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS, new { libraryType = "Book" })'.replace('/Book', `/${encodedLibraryType}`)), + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_BOOK_READERS, new { libraryType = "Book" })'.replace('/Book', `/${encodedLibraryType}`)) + ]; + if (id) { + requests.push( + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_METADATA_PROVIDERS, new { libraryId = default(Guid) })'.replace('/@(default(Guid))', `/${id}`)), + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ARTWORK_PROVIDERS, new { libraryId = default(Guid) })'.replace('/@(default(Guid))', `/${id}`)), + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_BOOK_READERS, new { libraryId = default(Guid) })'.replace('/@(default(Guid))', `/${id}`))); + } + const [availableMetadataProviders, availableArtworkProviders, availableBookReaders, storedMetadataProviders, storedArtworkProviders, storedBookReaders] = await Promise.all(requests); + if (loadVersion !== providersLoadVersion) + return; + if (!id) { + renderProviders(availableMetadataProviders, availableArtworkProviders, availableBookReaders); + return; + } + renderProviders( + mergeStoredProviders(availableMetadataProviders, storedMetadataProviders), + mergeStoredProviders(availableArtworkProviders, storedArtworkProviders), + mergeStoredProviders(availableBookReaders, storedBookReaders)); } - // Renders a metadata provider row of the library. - function renderMetadataProviderRow(provider, index, count) { + // Merges the stored configuration of a library with the providers available for the selected type. Returns null when either list could not be + // loaded, so that the list is not submitted and the server keeps what it has. An empty list of available providers is treated the same way: + // while stored providers exist, it means that no loaded plugin currently reports support for the type, not that the user left every provider + // out. Submitting it would tell the server that the whole list is a choice, which deletes the stored rows along with their enablement and + // order, and the next plugin sync would re-add them disabled. + function mergeStoredProviders(availableProviders, storedProviders) { + if (!Array.isArray(availableProviders) || !Array.isArray(storedProviders)) + return null; + if (availableProviders.length === 0 && storedProviders.length > 0) + return null; + const availableProvidersById = new Map(availableProviders.map(provider => [provider.pluginId, provider])); + const keptProviders = storedProviders + .filter(provider => availableProvidersById.has(provider.pluginId)) + .sort((first, second) => (first.rank ?? 0) - (second.rank ?? 0)) + .map(provider => ({ ...availableProvidersById.get(provider.pluginId), isEnabled: provider.isEnabled })); + const keptPluginIds = new Set(keptProviders.map(provider => provider.pluginId)); + return keptProviders.concat(availableProviders.filter(provider => !keptPluginIds.has(provider.pluginId))); + } + + // Renders the provider lists, and shows only the sections whose list has at least one provider. + function renderProviders(metadataProviders, artworkProviders, bookReaders) { + areMetadataProvidersLoaded = Array.isArray(metadataProviders); + areArtworkProvidersLoaded = Array.isArray(artworkProviders); + areBookReadersLoaded = Array.isArray(bookReaders); + const metadataProviderRows = areMetadataProvidersLoaded ? metadataProviders : []; + const artworkProviderRows = areArtworkProvidersLoaded ? artworkProviders : []; + const bookReaderRows = areBookReadersLoaded ? bookReaders : []; + metadataProvidersTbody.innerHTML = metadataProviderRows.map(provider => renderRankedProviderRow(provider, 'metadata-provider')).join(''); + artworkProvidersTbody.innerHTML = artworkProviderRows.map(provider => renderRankedProviderRow(provider, 'artwork-provider')).join(''); + bookReadersTbody.innerHTML = bookReaderRows.map(reader => renderBookReaderRow(reader)).join(''); + refreshMoveButtons(metadataProvidersTbody, 'metadata-provider'); + refreshMoveButtons(artworkProvidersTbody, 'artwork-provider'); + metadataProvidersSection.classList.toggle('hidden', metadataProviderRows.length === 0); + artworkProvidersSection.classList.toggle('hidden', artworkProviderRows.length === 0); + bookReadersSection.classList.toggle('hidden', bookReaderRows.length === 0); + } + + // Renders a metadata or artwork provider row, whose position in the table is the order in which the provider is tried. + function renderRankedProviderRow(provider, classPrefix) { return ` - - ${provider.name} + + ${escapeHtml(provider.name)} - - + + `; } - // On metadata provider move button click, reorders the providers and persists the new order. - async function handleMetadataProviderReorderAsync(e) { - const button = e.target.closest('.metadata-provider-move-up, .metadata-provider-move-down'); - if (!button || !metadataProvidersTbody) return; - const row = button.closest('tr'); - if (button.classList.contains('metadata-provider-move-up')) { - const previousRow = row.previousElementSibling; - if (previousRow) metadataProvidersTbody.insertBefore(row, previousRow); - } else { - const nextRow = row.nextElementSibling; - if (nextRow) metadataProvidersTbody.insertBefore(nextRow, row); - } - await saveMetadataProviderOrderAsync(); - } - - // Persists the current order of the metadata providers of the library. - async function saveMetadataProviderOrderAsync() { - if (!id || !metadataProvidersTbody) return; - const pluginIds = Array.from(metadataProvidersTbody.querySelectorAll('tr[data-provider-plugin-id]')) - .map(row => row.getAttribute('data-provider-plugin-id')); - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.REORDER_METADATA_PROVIDERS)', { libraryId: id, pluginIds: pluginIds }); - if (result.success) { - notificationService.show('@_localizer["OrderSaved"]', NotificationType.SUCCESS); - } - } - - // On metadata provider enabled checkbox change, persists the new state. - async function handleMetadataProviderEnabledChangeAsync(e) { - if (e.target.matches('.metadata-provider-enabled')) { - const row = e.target.closest('tr'); - const pluginId = row.getAttribute('data-provider-plugin-id'); - const isEnabled = e.target.checked; - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SET_METADATA_PROVIDER_ENABLED)', { libraryId: id, pluginId: pluginId, isEnabled: isEnabled }); - if (!result.success) { - e.target.checked = !isEnabled; - } - } - }; - - const artworkProvidersTable = document.getElementById('artwork-providers-table'); - const artworkProvidersTbody = artworkProvidersTable ? artworkProvidersTable.querySelector('tbody') : null; - - // Loads the artwork providers configured for the library, when editing an existing library. - async function loadArtworkProvidersAsync() { - if (!id || !artworkProvidersTbody) return; - const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ARTWORK_PROVIDERS, new { libraryId = default(Guid) })' - .replace('/@(default(Guid))', `/${id}`); // The libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. - const response = await callApiGetAsync(url); - if (response && response.length > 0) { - artworkProvidersTbody.innerHTML = response.map((provider, index) => renderArtworkProviderRow(provider, index, response.length)).join(''); - } - } - - // Renders an artwork provider row of the library. - function renderArtworkProviderRow(provider, index, count) { - return ` - - ${provider.name} - - - - - - - - `; - } - - // On artwork provider move button click, reorders the providers and persists the new order. - async function handleArtworkProviderReorderAsync(e) { - const button = e.target.closest('.artwork-provider-move-up, .artwork-provider-move-down'); - if (!button || !artworkProvidersTbody) return; - const row = button.closest('tr'); - if (button.classList.contains('artwork-provider-move-up')) { - const previousRow = row.previousElementSibling; - if (previousRow) artworkProvidersTbody.insertBefore(row, previousRow); - } else { - const nextRow = row.nextElementSibling; - if (nextRow) artworkProvidersTbody.insertBefore(nextRow, row); - } - await saveArtworkProviderOrderAsync(); - } - - // Persists the current order of the artwork providers of the library. - async function saveArtworkProviderOrderAsync() { - if (!id || !artworkProvidersTbody) return; - const pluginIds = Array.from(artworkProvidersTbody.querySelectorAll('tr[data-provider-plugin-id]')) - .map(row => row.getAttribute('data-provider-plugin-id')); - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.REORDER_ARTWORK_PROVIDERS)', { libraryId: id, pluginIds: pluginIds }); - if (result.success) { - notificationService.show('@_localizer["OrderSaved"]', NotificationType.SUCCESS); - } - } - - // On artwork provider enabled checkbox change, persists the new state. - async function handleArtworkProviderEnabledChangeAsync(e) { - if (e.target.matches('.artwork-provider-enabled')) { - const row = e.target.closest('tr'); - const pluginId = row.getAttribute('data-provider-plugin-id'); - const isEnabled = e.target.checked; - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SET_ARTWORK_PROVIDER_ENABLED)', { libraryId: id, pluginId: pluginId, isEnabled: isEnabled }); - if (!result.success) { - e.target.checked = !isEnabled; - } - } - }; - - const bookReadersTable = document.getElementById('book-readers-table'); - const bookReadersTbody = bookReadersTable ? bookReadersTable.querySelector('tbody') : null; - - // Loads the book readers configured for the library, when editing an existing library. - async function loadBookReadersAsync() { - if (!id || !bookReadersTbody) return; - const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_BOOK_READERS, new { libraryId = default(Guid) })' - .replace('/@(default(Guid))', `/${id}`); // The libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. - const response = await callApiGetAsync(url); - if (response && response.length > 0) { - bookReadersTbody.innerHTML = response.map(reader => renderBookReaderRow(reader)).join(''); - } - } - - // Renders a book reader row of the library. + // Renders a book reader row. function renderBookReaderRow(reader) { const extensions = (reader.supportedExtensions || []).join(', '); return ` - - ${reader.name} - ${extensions} + + ${escapeHtml(reader.name)} + ${escapeHtml(extensions)}