Adds artwork provider system and Calibre plugin

This commit is contained in:
BinaryAlley committed 2026-08-24 14:18:14 -07:00
1 parent c82fadc7a2
commit 6693ff3f60
124 files changed
+9715 -74

No files matched your search

@@ -138,7 +138,7 @@ public class BookEntity : IStorageEntity, IAuditableEntity
/// <summary>
/// Gets or sets the volume or book number in the series, if applicable.
/// </summary>
public int? VolumeNumber { get; set; }
public float? VolumeNumber { get; set; }
// TODO: uncomment when series is implemented
/// <summary>
/// Gets or sets the series id, if the book is part of a series.
@@ -190,6 +190,11 @@ public class BookEntity : IStorageEntity, IAuditableEntity
/// </summary>
public string? AppleBooksId { get; set; }
/// <summary>
/// Gets or sets the file system path of the cover image of the book, if applicable.
/// </summary>
public string? CoverImagePath { get; set; }
/// <summary>
/// Gets or sets the list of ISBN (International Standard Book Number) of the book.
/// </summary>
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Plugins;
/// <summary>
/// Repository entity for the configuration of an artwork provider of a media library.
/// </summary>
[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
public class LibraryArtworkProviderConfigurationEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets or sets the Id of the configuration.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the Id of the media library the configuration belongs to.
/// </summary>
public required Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the Id of the plugin providing the artwork.
/// </summary>
public required Guid PluginId { get; set; }
/// <summary>
/// Gets or sets whether the artwork provider is enabled for the media library.
/// </summary>
public required bool IsEnabled { get; set; }
/// <summary>
/// Gets or sets the rank of the artwork provider, determining the order in which providers are tried.
/// </summary>
public required int Rank { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Plugins;
/// <summary>
/// Interface for the repository for the artwork provider configurations of media libraries.
/// </summary>
public interface IArtworkProviderConfigurationRepository : IRepository<LibraryArtworkProviderConfigurationEntity>
{
/// <summary>
/// Gets all the artwork provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork provider configurations are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryArtworkProviderConfigurationEntity"/>, or an error.</returns>
Task<Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Gets the artwork provider configuration of the media library identified by <paramref name="libraryId"/> for the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork provider configuration is retrieved.</param>
/// <param name="pluginId">The Id of the plugin whose artwork provider configuration is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="LibraryArtworkProviderConfigurationEntity"/>, or an error.</returns>
Task<Result<LibraryArtworkProviderConfigurationEntity?>> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken);
/// <summary>
/// Inserts the provided <paramref name="configuration"/> into the storage medium, or updates it when it already exists.
/// </summary>
/// <param name="configuration">The artwork provider configuration to insert or update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> UpsertAsync(LibraryArtworkProviderConfigurationEntity configuration, CancellationToken cancellationToken);
}
@@ -110,14 +110,14 @@ public static class BookEntityMapping
Optional<BookFormat> bookFormat = Optional<BookFormat>.FromNullable(repositoryEntity.Format);
return Book.Create(
Result<Book> bookResult = Book.Create(
BookId.Create(repositoryEntity.Id),
LibraryId.Create(repositoryEntity.LibraryId),
repositoryEntity.Path,
writtenContentMetadataResult.Value,
bookFormat,
Optional<string>.FromNullable(repositoryEntity.Edition),
Optional<int>.FromNullable(repositoryEntity.VolumeNumber),
Optional<float>.FromNullable(repositoryEntity.VolumeNumber),
Optional<BookSeries>.None(),
Optional<string>.FromNullable(repositoryEntity.ASIN),
Optional<string>.FromNullable(repositoryEntity.GoodreadsId),
@@ -133,6 +133,13 @@ public static class BookEntityMapping
[.. isbnsResult.Select(isbn => isbn.Value)],
[],
[.. bookRatingsResult.Select(bookRating => bookRating.Value)]);
if (bookResult.IsFailure)
return bookResult.Errors;
if (repositoryEntity.CoverImagePath is not null)
bookResult.Value.SetBookCoverImagePath(repositoryEntity.CoverImagePath);
return bookResult;
}
/// <summary>
@@ -217,7 +224,8 @@ public static class BookEntityMapping
repositoryEntity.LastMetadataUpdateUtc,
repositoryEntity.MetadataProvider,
repositoryEntity.CreatedOnUtc,
repositoryEntity.UpdatedOnUtc
repositoryEntity.UpdatedOnUtc,
repositoryEntity.CoverImagePath
);
}
@@ -259,8 +267,7 @@ public static class BookEntityMapping
repositoryEntity.Id,
repositoryEntity.Title,
repositoryEntity.ReReleaseYear ?? repositoryEntity.OriginalReleaseYear,
// TODO: populate from the book cover when cover support is implemented
null
repositoryEntity.CoverImagePath
);
}
@@ -56,6 +56,7 @@ public static class BookMapping
GoogleBooksId = domainEntity.GoogleBooksId.HasValue ? domainEntity.GoogleBooksId.Value : null,
BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null,
AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null,
CoverImagePath = domainEntity.CoverImagePath.HasValue ? domainEntity.CoverImagePath.Value : null,
ISBNs = [.. domainEntity.ISBNs.ToRepositoryEntities()],
Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()],
MetadataStatus = domainEntity.MetadataStatus,
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
@@ -30,9 +29,9 @@ public static class BookMetadataDtoMapping
public static Result<Success> ApplyMetadata(this Book book, BookMetadataDto metadata, string providerName, DateTime lastUpdateUtc)
{
if (string.IsNullOrWhiteSpace(metadata.Title))
return Lumina.Domain.Common.Errors.Errors.Metadata.TitleCannotBeEmpty;
return Domain.Common.Errors.Errors.Metadata.TitleCannotBeEmpty;
if (metadata.ReleaseInfo is null)
return Lumina.Domain.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull;
return Domain.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull;
Result<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(metadata.ReleaseInfo.OriginalReleaseDate),
@@ -115,7 +114,7 @@ public static class BookMetadataDtoMapping
writtenContentMetadataResult.Value,
Optional<BookFormat>.FromNullable(metadata.Format.HasValue ? (BookFormat)(int)metadata.Format.Value : (BookFormat?)null),
Optional<string>.FromNullable(metadata.Edition),
Optional<int>.FromNullable(metadata.VolumeNumber),
Optional<float>.FromNullable(metadata.VolumeNumber),
Optional<BookSeries>.None(),
Optional<string>.FromNullable(metadata.ASIN),
Optional<string>.FromNullable(metadata.GoodreadsId),
@@ -132,6 +131,9 @@ public static class BookMetadataDtoMapping
lastUpdateUtc
);
if (!string.IsNullOrWhiteSpace(metadata.CoverImagePath))
book.SetBookCoverImagePath(metadata.CoverImagePath);
return Result.Success;
}
}
@@ -21,18 +21,19 @@ public static class GetBooksLiteRequestMapping
{
PaginationDataDto? paginationData = null;
if (request.CurrentPage is not null || request.PerPage is not null)
{
paginationData = new PaginationDataDto
{
CurrentPage = request.CurrentPage ?? 1,
PerPage = request.PerPage ?? 200
};
}
LibraryFilterDto libraryFilter = new()
{
LibraryId = request.LibraryId,
SearchTerm = request.SearchTerm,
FilterAlphaKey = request.FilterAlphaKey,
IgnoreThePrefixForAlphaPicker = request.IgnoreThePrefixForAlphaPicker
ShouldIgnoreThePrefixForAlphaPicker = request.ShouldIgnoreThePrefixForAlphaPicker
};
return new GetBooksLiteQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder);
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
using Lumina.Contracts.Requests.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="GetLibraryArtworkProvidersRequest"/>.
/// </summary>
public static class GetLibraryArtworkProvidersRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetLibraryArtworkProvidersQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetLibraryArtworkProvidersQuery ToQuery(this GetLibraryArtworkProvidersRequest request)
{
return new GetLibraryArtworkProvidersQuery(LibraryId: request.LibraryId);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Responses.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="LibraryArtworkProviderConfigurationEntity"/>.
/// </summary>
public static class LibraryArtworkProviderConfigurationEntityMapping
{
/// <summary>
/// Converts <paramref name="configuration"/> to <see cref="LibraryArtworkProviderResponse"/>.
/// </summary>
/// <param name="configuration">The repository entity to be converted.</param>
/// <param name="providerName">The display name of the artwork provider.</param>
/// <returns>The converted response.</returns>
public static LibraryArtworkProviderResponse ToResponse(this LibraryArtworkProviderConfigurationEntity configuration, string providerName)
{
return new LibraryArtworkProviderResponse(
PluginId: configuration.PluginId,
Name: providerName,
IsEnabled: configuration.IsEnabled,
Rank: configuration.Rank
);
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Contracts.Requests.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="ReorderLibraryArtworkProvidersRequest"/>.
/// </summary>
public static class ReorderLibraryArtworkProvidersRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="ReorderLibraryArtworkProvidersCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static ReorderLibraryArtworkProvidersCommand ToCommand(this ReorderLibraryArtworkProvidersRequest request)
{
return new ReorderLibraryArtworkProvidersCommand(
LibraryId: request.LibraryId,
PluginIds: request.PluginIds
);
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Contracts.Requests.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="SetLibraryArtworkProviderEnabledRequest"/>.
/// </summary>
public static class SetLibraryArtworkProviderEnabledRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="SetLibraryArtworkProviderEnabledCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static SetLibraryArtworkProviderEnabledCommand ToCommand(this SetLibraryArtworkProviderEnabledRequest request)
{
return new SetLibraryArtworkProviderEnabledCommand(
LibraryId: request.LibraryId,
PluginId: request.PluginId,
IsEnabled: request.IsEnabled
);
}
}
@@ -93,6 +93,33 @@ public static class ValidatorUtilities
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the float property is greater than the specified value.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, float> GreaterThan<TRequest>(this IRuleBuilder<TRequest, float> ruleBuilder, float valueToCompare)
{
return ruleBuilder.Must(value => value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the nullable float property is greater than the specified value.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, float?> GreaterThan<TRequest>(this IRuleBuilder<TRequest, float?> ruleBuilder, float valueToCompare)
{
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the time span property is greater than the specified value.
/// </summary>
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.Common.Primitives;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
/// <summary>
/// Interface for the service for storing the artwork of a book into the internal media directory and serving its relative path.
/// </summary>
public interface IBookArtworkService
{
/// <summary>
/// Stores the <paramref name="artwork"/> of the book into the internal media directory, and returns the relative path of the stored artwork.
/// </summary>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryName">The name of the media library the book belongs to.</param>
/// <param name="authorName">The name of the author of the book.</param>
/// <param name="bookTitle">The title of the book.</param>
/// <param name="artwork">The artwork to store.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken);
/// <summary>
/// Deletes the artwork of the book from the internal media directory.
/// </summary>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryName">The name of the media library the book belongs to.</param>
/// <param name="authorName">The name of the author of the book.</param>
/// <param name="bookTitle">The title of the book.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Result<Deleted> DeleteBookArtwork(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle);
}
@@ -1,12 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
@@ -40,7 +40,7 @@ public record AddBookCommand(
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
string? Edition,
int? VolumeNumber,
float? VolumeNumber,
BookSeriesDto? Series,
string? ASIN,
string? GoodreadsId,
@@ -1,8 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
@@ -19,6 +20,8 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
{
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookLibraryCannotBeNull)
.Must(id => id != Guid.Empty)
.WithError(Errors.WrittenContent.BookLibraryCannotBeNull);
RuleFor(command => command.Path)
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
/// <summary>
/// Command for reordering the artwork providers of a media library.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose artwork providers are reordered.</param>
/// <param name="PluginIds">The plugin Ids in the new order, from highest to lowest rank.</param>
public record ReorderLibraryArtworkProvidersCommand(
Guid LibraryId,
IReadOnlyList<Guid> PluginIds
) : ICommand;
@@ -0,0 +1,92 @@
#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;
/// <summary>
/// Handler for the command to reorder the artwork providers of a media library.
/// </summary>
public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler<ReorderLibraryArtworkProvidersCommand, Result<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<ReorderLibraryArtworkProvidersCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public ReorderLibraryArtworkProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<ReorderLibraryArtworkProvidersCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command to reorder the artwork providers of a media library.
/// </summary>
/// <param name="command">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> representing either a successful operation, or an error.
/// </returns>
public async Task<Result<Success>> HandleAsync(ReorderLibraryArtworkProvidersCommand command, CancellationToken cancellationToken)
{
List<Error> 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<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return getConfigurationsResult.Errors;
Dictionary<Guid, LibraryArtworkProviderConfigurationEntity> configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId);
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<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return upsertResult.Errors;
}
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Result.Success;
}
}
@@ -0,0 +1,32 @@
#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;
/// <summary>
/// Validates the needed validation rules for <see cref="ReorderLibraryArtworkProvidersCommand"/>.
/// </summary>
public class ReorderLibraryArtworkProvidersCommandValidator : AbstractValidator<ReorderLibraryArtworkProvidersCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
#endregion
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Command for enabling or disabling an artwork provider for a media library.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose artwork provider is enabled or disabled.</param>
/// <param name="PluginId">The unique identifier of the plugin providing the artwork.</param>
/// <param name="IsEnabled">Whether the artwork provider should be enabled for the media library.</param>
public record SetLibraryArtworkProviderEnabledCommand(
Guid LibraryId,
Guid PluginId,
bool IsEnabled
) : ICommand;
@@ -0,0 +1,107 @@
#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;
/// <summary>
/// Handler for the command to enable or disable an artwork provider for a media library.
/// </summary>
public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler<SetLibraryArtworkProviderEnabledCommand, Result<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<SetLibraryArtworkProviderEnabledCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public SetLibraryArtworkProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<SetLibraryArtworkProviderEnabledCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command to enable or disable an artwork provider for a media library.
/// </summary>
/// <param name="command">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> representing either a successful operation, or an error.
/// </returns>
public async Task<Result<Success>> HandleAsync(SetLibraryArtworkProviderEnabledCommand command, CancellationToken cancellationToken)
{
List<Error> 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<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<LibraryArtworkProviderConfigurationEntity?> 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)
{
configuration = getConfigurationResult.Value;
configuration.IsEnabled = command.IsEnabled;
}
else
{
// compute the rank to assign to the new configuration, appending it after the existing ones
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> 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
};
}
Result<Updated> upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return upsertResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Result.Success;
}
}
@@ -0,0 +1,32 @@
#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;
/// <summary>
/// Validates the needed validation rules for <see cref="SetLibraryArtworkProviderEnabledCommand"/>.
/// </summary>
public class SetLibraryArtworkProviderEnabledCommandValidator : AbstractValidator<SetLibraryArtworkProviderEnabledCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
#endregion
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
/// <summary>
/// Query for getting the artwork providers configured for a media library.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose artwork providers are retrieved.</param>
public record GetLibraryArtworkProvidersQuery(
Guid LibraryId
) : IQuery;
@@ -0,0 +1,88 @@
#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.Application.Common.Mapping.Plugins;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
/// <summary>
/// Handler for the query to get the artwork providers configured for a media library.
/// </summary>
public class GetLibraryArtworkProvidersQueryHandler : IQueryHandler<GetLibraryArtworkProvidersQuery, Result<IReadOnlyList<LibraryArtworkProviderResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetLibraryArtworkProvidersQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetLibraryArtworkProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<GetLibraryArtworkProvidersQuery> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the query to get the artwork providers configured for a media library.
/// </summary>
/// <param name="query">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryArtworkProviderResponse"/>, or an error.
/// </returns>
public async Task<Result<IReadOnlyList<LibraryArtworkProviderResponse>>> HandleAsync(GetLibraryArtworkProvidersQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// admins can read the artwork providers of any library; for everyone else, only their own libraries
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return getConfigurationsResult.Errors;
// build a plugin name lookup from the detected plugins
Result<IEnumerable<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getPluginsResult.IsFailure)
return getPluginsResult.Errors;
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
return getConfigurationsResult.Value
.OrderBy(configuration => configuration.Rank)
.Select(configuration => configuration.ToResponse(pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty))
.ToList();
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
/// <summary>
/// Validates the needed validation rules for <see cref="GetLibraryArtworkProvidersQuery"/>.
/// </summary>
public class GetLibraryArtworkProvidersQueryValidator : AbstractValidator<GetLibraryArtworkProvidersQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersQueryValidator"/> class.
/// </summary>
public GetLibraryArtworkProvidersQueryValidator()
{
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
}