mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 05:01:10 +00:00
Adds artwork provider system and Calibre plugin
This commit is contained in:
1 parent
c82fadc7a2
commit
6693ff3f60
124 files changed
+9715
-74
No files matched your search
+6
-1
@@ -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>
|
||||
|
||||
+59
@@ -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; }
|
||||
}
|
||||
+42
@@ -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);
|
||||
}
|
||||
+12
-5
@@ -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
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -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,
|
||||
|
||||
+7
-5
@@ -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;
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -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);
|
||||
|
||||
+22
@@ -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);
|
||||
}
|
||||
}
|
||||
+28
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
+25
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
+26
@@ -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>
|
||||
|
||||
+39
@@ -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);
|
||||
}
|
||||
+4
-4
@@ -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,
|
||||
|
||||
+4
-1
@@ -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)
|
||||
|
||||
+17
@@ -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;
|
||||
+92
@@ -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;
|
||||
}
|
||||
}
|
||||
+32
@@ -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);
|
||||
}
|
||||
}
|
||||
+18
@@ -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;
|
||||
+107
@@ -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;
|
||||
}
|
||||
}
|
||||
+32
@@ -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);
|
||||
}
|
||||
}
|
||||
+14
@@ -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;
|
||||
+88
@@ -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();
|
||||
}
|
||||
}
|
||||
+26
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the artwork of a media item, provided by an artwork provider.
|
||||
/// </summary>
|
||||
/// <param name="LocalPath">The local file system path of the artwork, when the artwork is a local file.</param>
|
||||
/// <param name="RemoteUrl">The remote URL of the artwork, when the artwork is fetched over the web.</param>
|
||||
[DebuggerDisplay("LocalPath: {LocalPath}, RemoteUrl: {RemoteUrl}")]
|
||||
public sealed record ArtworkDto(
|
||||
string? LocalPath,
|
||||
string? RemoteUrl
|
||||
);
|
||||
+3
-3
@@ -36,7 +36,7 @@ namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
/// <param name="Isbns">The list of ISBN (International Standard Book Number) of the book.</param>
|
||||
/// <param name="Contributors">The list of media contributors of the book.</param>
|
||||
/// <param name="Ratings">The list of ratings for the book.</param>
|
||||
/// <param name="CoverImageUrl">The URL of the cover image of the book, if applicable.</param>
|
||||
/// <param name="CoverImagePath">The path of the cover image of the book, if applicable.</param>
|
||||
public sealed record BookMetadataDto(
|
||||
string? Title,
|
||||
string? OriginalTitle,
|
||||
@@ -50,7 +50,7 @@ public sealed record BookMetadataDto(
|
||||
int? PageCount,
|
||||
BookFormat? Format,
|
||||
string? Edition,
|
||||
int? VolumeNumber,
|
||||
float? VolumeNumber,
|
||||
BookSeriesDto? Series,
|
||||
string? ASIN,
|
||||
string? GoodreadsId,
|
||||
@@ -64,5 +64,5 @@ public sealed record BookMetadataDto(
|
||||
List<IsbnDto>? Isbns,
|
||||
List<MediaContributorDto>? Contributors,
|
||||
List<BookRatingDto>? Ratings,
|
||||
string? CoverImageUrl
|
||||
string? CoverImagePath
|
||||
) : MetadataDto;
|
||||
+1
-1
@@ -39,7 +39,7 @@ public record AddBookRequest(
|
||||
WrittenContentMetadataDto? Metadata,
|
||||
BookFormat? Format,
|
||||
string? Edition,
|
||||
int? VolumeNumber,
|
||||
float? VolumeNumber,
|
||||
BookSeriesDto? Series,
|
||||
string? ASIN,
|
||||
string? GoodreadsId,
|
||||
|
||||
+2
-2
@@ -18,7 +18,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
|
||||
/// Can be <see langword="null"/> to disable alpha filtering, a single ASCII letter (case-insensitive) to filter by that letter,
|
||||
/// "#" to filter by titles whose first character is a digit, or "*" to filter by titles whose first character is neither a letter nor a digit.
|
||||
/// </param>
|
||||
/// <param name="IgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||
/// <param name="SortBy">The name of the field by which to sort the results. Optional.</param>
|
||||
/// <param name="SortOrder">The direction in which to sort the results. Optional.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}")]
|
||||
@@ -28,7 +28,7 @@ public record GetBooksLiteRequest(
|
||||
int? PerPage,
|
||||
string? SearchTerm,
|
||||
string? FilterAlphaKey,
|
||||
bool IgnoreThePrefixForAlphaPicker,
|
||||
bool ShouldIgnoreThePrefixForAlphaPicker,
|
||||
string? SortBy,
|
||||
SortOrder? SortOrder
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to get the artwork providers configured for a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The unique identifier of the media library whose artwork providers are retrieved. Required.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}")]
|
||||
public sealed record GetLibraryArtworkProvidersRequest(
|
||||
Guid LibraryId
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to reorder the artwork providers of a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The unique identifier of the media library whose artwork providers are reordered. Required.</param>
|
||||
/// <param name="PluginIds">The plugin Ids in the new order, from highest to lowest rank. Required.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}")]
|
||||
public sealed record ReorderLibraryArtworkProvidersRequest(
|
||||
Guid LibraryId,
|
||||
IReadOnlyList<Guid> PluginIds
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to enable or disable an artwork provider for a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The unique identifier of the media library whose artwork provider is enabled or disabled. Required.</param>
|
||||
/// <param name="PluginId">The unique identifier of the plugin providing the artwork. Required.</param>
|
||||
/// <param name="IsEnabled">Whether the artwork provider should be enabled for the media library. Required.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
|
||||
public sealed record SetLibraryArtworkProviderEnabledRequest(
|
||||
Guid LibraryId,
|
||||
Guid PluginId,
|
||||
bool IsEnabled
|
||||
);
|
||||
+4
-2
@@ -38,6 +38,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibr
|
||||
/// <param name="MetadataProvider">The name of the plugin that enriched the metadata of the book, if applicable.</param>
|
||||
/// <param name="CreatedOnUtc">The date and time when the book was created.</param>
|
||||
/// <param name="UpdatedOnUtc">The optional date and time when the book was updated.</param>
|
||||
/// <param name="CoverPath">The path of the cover image of the book, if available.</param>
|
||||
[DebuggerDisplay("Title: {Metadata.Title}")]
|
||||
public record BookResponse(
|
||||
Guid Id,
|
||||
@@ -46,7 +47,7 @@ public record BookResponse(
|
||||
WrittenContentMetadataDto Metadata,
|
||||
BookFormat? Format,
|
||||
string? Edition,
|
||||
int? VolumeNumber,
|
||||
float? VolumeNumber,
|
||||
BookSeriesDto? Series,
|
||||
string? ASIN,
|
||||
string? GoodreadsId,
|
||||
@@ -64,5 +65,6 @@ public record BookResponse(
|
||||
DateTime? LastMetadataUpdateUtc,
|
||||
string? MetadataProvider,
|
||||
DateTime CreatedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
DateTime? UpdatedOnUtc,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an artwork provider configured for a media library.
|
||||
/// </summary>
|
||||
/// <param name="PluginId">The unique identifier of the plugin providing the artwork.</param>
|
||||
/// <param name="Name">The display name of the artwork provider.</param>
|
||||
/// <param name="IsEnabled">Whether the artwork provider is enabled for the media library.</param>
|
||||
/// <param name="Rank">The rank of the artwork provider, determining the order in which providers are tried.</param>
|
||||
public sealed record LibraryArtworkProviderResponse(
|
||||
Guid PluginId,
|
||||
string Name,
|
||||
bool IsEnabled,
|
||||
int Rank
|
||||
);
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="LibraryArtworkProviderConfigurationEntity"/> entity.
|
||||
/// </summary>
|
||||
public class LibraryArtworkProviderConfigurationConfiguration : IEntityTypeConfiguration<LibraryArtworkProviderConfigurationEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="LibraryArtworkProviderConfigurationEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<LibraryArtworkProviderConfigurationEntity> builder)
|
||||
{
|
||||
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
|
||||
.HasColumnOrder(0);
|
||||
builder.Property(configuration => configuration.LibraryId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
builder.Property(configuration => configuration.PluginId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(2);
|
||||
builder.Property(configuration => configuration.IsEnabled)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
builder.Property(configuration => configuration.Rank)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
// audit
|
||||
builder.Property(configuration => configuration.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.Property(configuration => configuration.CreatedBy)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(6);
|
||||
|
||||
builder.Property(configuration => configuration.UpdatedOnUtc)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(7);
|
||||
|
||||
builder.Property(configuration => configuration.UpdatedBy)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(8);
|
||||
|
||||
builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId });
|
||||
}
|
||||
}
|
||||
+1358
File diff suppressed because it is too large.
Load diff
+106
@@ -0,0 +1,106 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddsArtworkProvidersAndBookCoverAndMetadataAggregation : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.RenameColumn(
|
||||
name: "IgnoreThePrefixForAlphaPicker",
|
||||
table: "UserSettings",
|
||||
newName: "ShouldIgnoreThePrefixForAlphaPicker");
|
||||
|
||||
migrationBuilder.RenameColumn(
|
||||
name: "DownloadMetadataFromWeb",
|
||||
table: "Libraries",
|
||||
newName: "CanDownloadMetadataFromWeb");
|
||||
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "ShouldAggregateMetadataWhenMissing",
|
||||
table: "UserSettings",
|
||||
type: "INTEGER",
|
||||
nullable: false,
|
||||
defaultValue: false)
|
||||
.Annotation("Relational:ColumnOrder", 10);
|
||||
|
||||
migrationBuilder.AlterColumn<float>(
|
||||
name: "VolumeNumber",
|
||||
table: "Books",
|
||||
type: "REAL",
|
||||
nullable: true,
|
||||
oldClrType: typeof(int),
|
||||
oldType: "INTEGER",
|
||||
oldNullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "CoverImagePath",
|
||||
table: "Books",
|
||||
type: "TEXT",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "LibraryArtworkProviderConfigurations",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
LibraryId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
PluginId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
IsEnabled = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
Rank = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_LibraryArtworkProviderConfigurations", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId",
|
||||
table: "LibraryArtworkProviderConfigurations",
|
||||
columns: new[] { "LibraryId", "PluginId" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "LibraryArtworkProviderConfigurations");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ShouldAggregateMetadataWhenMissing",
|
||||
table: "UserSettings");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CoverImagePath",
|
||||
table: "Books");
|
||||
|
||||
migrationBuilder.RenameColumn(
|
||||
name: "ShouldIgnoreThePrefixForAlphaPicker",
|
||||
table: "UserSettings",
|
||||
newName: "IgnoreThePrefixForAlphaPicker");
|
||||
|
||||
migrationBuilder.RenameColumn(
|
||||
name: "CanDownloadMetadataFromWeb",
|
||||
table: "Libraries",
|
||||
newName: "DownloadMetadataFromWeb");
|
||||
|
||||
migrationBuilder.AlterColumn<int>(
|
||||
name: "VolumeNumber",
|
||||
table: "Books",
|
||||
type: "INTEGER",
|
||||
nullable: true,
|
||||
oldClrType: typeof(float),
|
||||
oldType: "REAL",
|
||||
oldNullable: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -270,6 +270,12 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<bool>("CanDownloadMetadataFromWeb")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<string>("CoverImage")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
@@ -283,12 +289,6 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<bool>("DownloadMetadataFromWeb")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<bool>("IsEnabled")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
@@ -535,6 +535,9 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(28);
|
||||
|
||||
b.Property<string>("CoverImagePath")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(33);
|
||||
@@ -685,8 +688,8 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(34);
|
||||
|
||||
b.Property<int?>("VolumeNumber")
|
||||
.HasColumnType("INTEGER")
|
||||
b.Property<float?>("VolumeNumber")
|
||||
.HasColumnType("REAL")
|
||||
.HasColumnOrder(20);
|
||||
|
||||
b.HasKey("Id");
|
||||
@@ -698,6 +701,51 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.ToTable("Books", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<bool>("IsEnabled")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid>("PluginId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<int>("Rank")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("LibraryId", "PluginId");
|
||||
|
||||
b.ToTable("LibraryArtworkProviderConfigurations", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -964,10 +1012,6 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<bool>("IgnoreThePrefixForAlphaPicker")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<bool>("IsPaginationEnabled")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(2);
|
||||
@@ -980,6 +1024,14 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<bool>("ShouldAggregateMetadataWhenMissing")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<bool>("ShouldIgnoreThePrefixForAlphaPicker")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Core.Repositories.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for the artwork provider configurations of media libraries.
|
||||
/// </summary>
|
||||
internal sealed class ArtworkProviderConfigurationRepository : IArtworkProviderConfigurationRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ArtworkProviderConfigurationRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public ArtworkProviderConfigurationRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
public async Task<Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _luminaDbContext.LibraryArtworkProviderConfigurations
|
||||
.Where(configuration => configuration.LibraryId == libraryId)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <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>
|
||||
public async Task<Result<LibraryArtworkProviderConfigurationEntity?>> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _luminaDbContext.LibraryArtworkProviderConfigurations
|
||||
.FirstOrDefaultAsync(configuration => configuration.LibraryId == libraryId && configuration.PluginId == pluginId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts an artwork provider 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>
|
||||
public async Task<Result<Updated>> UpsertAsync(LibraryArtworkProviderConfigurationEntity configuration, CancellationToken cancellationToken)
|
||||
{
|
||||
LibraryArtworkProviderConfigurationEntity? existingConfiguration = await _luminaDbContext.LibraryArtworkProviderConfigurations
|
||||
.FirstOrDefaultAsync(repositoryConfiguration => repositoryConfiguration.LibraryId == configuration.LibraryId && repositoryConfiguration.PluginId == configuration.PluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (existingConfiguration is null)
|
||||
_luminaDbContext.LibraryArtworkProviderConfigurations.Add(configuration);
|
||||
else
|
||||
{
|
||||
// update only the mutable fields, preserving the Id of the existing configuration
|
||||
existingConfiguration.LibraryId = configuration.LibraryId;
|
||||
existingConfiguration.PluginId = configuration.PluginId;
|
||||
existingConfiguration.IsEnabled = configuration.IsEnabled;
|
||||
existingConfiguration.Rank = configuration.Rank;
|
||||
}
|
||||
return Result.Updated;
|
||||
}
|
||||
}
|
||||
@@ -29,4 +29,9 @@ public enum BookRatingSource
|
||||
/// Ratings from Google Books, a service that searches the full text of books and magazines that Google has scanned and converted to text.
|
||||
/// </summary>
|
||||
GoogleBooks,
|
||||
|
||||
/// <summary>
|
||||
/// Ratings sourced from Calibre, an ebook management application.
|
||||
/// </summary>
|
||||
Calibre,
|
||||
}
|
||||
+21
-6
@@ -1,11 +1,11 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
@@ -66,7 +66,7 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
/// <summary>
|
||||
/// Gets the volume or book number in the series, if applicable.
|
||||
/// </summary>
|
||||
public Optional<int> VolumeNumber { get; private set; }
|
||||
public Optional<float> VolumeNumber { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the series name, if the book is part of a series.
|
||||
@@ -118,6 +118,11 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
/// </summary>
|
||||
public Optional<string> AppleBooksId { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the file system path of the cover image of the book, if applicable.
|
||||
/// </summary>
|
||||
public Optional<string> CoverImagePath { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of ISBN (International Standard Book Number) of the book.
|
||||
/// </summary>
|
||||
@@ -165,7 +170,7 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
WrittenContentMetadata metadata,
|
||||
Optional<BookFormat> format,
|
||||
Optional<string> edition,
|
||||
Optional<int> volumeNumber,
|
||||
Optional<float> volumeNumber,
|
||||
Optional<BookSeries> series,
|
||||
Optional<string> asin,
|
||||
Optional<string> goodreadsId,
|
||||
@@ -202,6 +207,7 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
GoogleBooksId = googleBooksId;
|
||||
BarnesAndNobleId = barnesAndNobleId;
|
||||
AppleBooksId = appleBooksId;
|
||||
CoverImagePath = Optional<string>.None();
|
||||
CreatedOnUtc = createdOnUtc;
|
||||
UpdatedOnUtc = updatedOnUtc.HasValue ? updatedOnUtc.Value : null;
|
||||
_isbns = isbns;
|
||||
@@ -240,7 +246,7 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
WrittenContentMetadata metadata,
|
||||
Optional<BookFormat> format,
|
||||
Optional<string> edition,
|
||||
Optional<int> volumeNumber,
|
||||
Optional<float> volumeNumber,
|
||||
Optional<BookSeries> series,
|
||||
Optional<string> asin,
|
||||
Optional<string> goodreadsId,
|
||||
@@ -317,7 +323,7 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
WrittenContentMetadata metadata,
|
||||
Optional<BookFormat> format,
|
||||
Optional<string> edition,
|
||||
Optional<int> volumeNumber,
|
||||
Optional<float> volumeNumber,
|
||||
Optional<BookSeries> series,
|
||||
Optional<string> asin,
|
||||
Optional<string> goodreadsId,
|
||||
@@ -381,6 +387,15 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
MetadataStatus = MetadataStatus.Failed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the file system path of the cover image of the book.
|
||||
/// </summary>
|
||||
/// <param name="coverImagePath">The file system path of the cover image of the book.</param>
|
||||
public void SetBookCoverImagePath(string coverImagePath)
|
||||
{
|
||||
CoverImagePath = coverImagePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the enriched <paramref name="metadata"/> and the related fields to the book, marking its metadata as enriched by the provided <paramref name="providerName"/>.
|
||||
/// </summary>
|
||||
@@ -406,7 +421,7 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
WrittenContentMetadata metadata,
|
||||
Optional<BookFormat> format,
|
||||
Optional<string> edition,
|
||||
Optional<int> volumeNumber,
|
||||
Optional<float> volumeNumber,
|
||||
Optional<BookSeries> series,
|
||||
Optional<string> asin,
|
||||
Optional<string> goodreadsId,
|
||||
|
||||
+7
-10
@@ -33,9 +33,8 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
|
||||
/// Creates the media library scan jobs for the provided media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Whether the library permits downloading data from the web, or not.</param>
|
||||
/// <returns>A collection of media library scan jobs.</returns>
|
||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMetadataFromWeb)
|
||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId)
|
||||
{
|
||||
// declare the list of jobs that this scanner requires
|
||||
IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IBooksFileSystemDiscoveryJob>(libraryId);
|
||||
@@ -53,14 +52,12 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
|
||||
mediaLibraryScanHashJob.AddChild(mediaLibraryScanResultsSaveJob);
|
||||
mediaLibraryScanResultsSaveJob.AddParent(mediaLibraryScanHashJob);
|
||||
|
||||
// when the library permits downloading data from the web, the metadata enrichment job is the last job in the directed acyclic job graph,
|
||||
// running after the scan results save job, so that the books are materialized before their metadata is enriched
|
||||
if (downloadMetadataFromWeb)
|
||||
{
|
||||
IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanMetadataEnrichmentJob);
|
||||
mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanResultsSaveJob);
|
||||
}
|
||||
// the metadata enrichment job is always the last job in the directed acyclic job graph, running after the scan results save job,
|
||||
// so that the books are materialized before their metadata is enriched. The job itself is the host-side gate that skips the providers
|
||||
// requiring access to the web when the media library does not permit downloading data from the web, so that the local providers still run offline
|
||||
IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanMetadataEnrichmentJob);
|
||||
mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanResultsSaveJob);
|
||||
|
||||
// return the top level jobs that will be triggered when the scan will be started
|
||||
yield return fileSystemDiscoveryJob;
|
||||
|
||||
@@ -11,6 +11,7 @@ using Lumina.Application.Common.Infrastructure.Themes;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Progress;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
@@ -28,6 +29,7 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Infrastructure.Core.Themes;
|
||||
@@ -102,6 +104,10 @@ public static class InfrastructureLayerServices
|
||||
|
||||
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
|
||||
|
||||
// book artwork: stores the artwork of the books into the internal media directory
|
||||
services.AddHttpClient();
|
||||
services.AddScoped<IBookArtworkService, BookArtworkService>();
|
||||
|
||||
// plugins: load the plugin assemblies from the plugins directory, register their services and provide the plugin manager
|
||||
string pluginsDirectorySetting = configuration.GetSection(PluginsSettingsDto.SECTION_NAME)["Directory"] ?? "plugins";
|
||||
string pluginsDirectory = Path.Combine(AppContext.BaseDirectory, pluginsDirectorySetting);
|
||||
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
|
||||
/// <summary>
|
||||
/// Stores the artwork of a book into the internal media directory, under a per-book directory, and returns its relative path.
|
||||
/// </summary>
|
||||
internal sealed class BookArtworkService : IBookArtworkService
|
||||
{
|
||||
private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
private readonly IEnvironmentContext _environmentContext;
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly MediaSettingsDto _mediaSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookArtworkService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
|
||||
/// <param name="pathService">Injected service for handling file system paths.</param>
|
||||
/// <param name="httpClientFactory">Injected factory used to create the HTTP clients that download the remote artwork.</param>
|
||||
/// <param name="mediaSettingsOptions">Injected service for retrieving <see cref="MediaSettingsDto"/>.</param>
|
||||
public BookArtworkService(IEnvironmentContext environmentContext, IPathService pathService, IHttpClientFactory httpClientFactory, IOptions<MediaSettingsDto> mediaSettingsOptions)
|
||||
{
|
||||
_environmentContext = environmentContext;
|
||||
_pathService = pathService;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_mediaSettings = mediaSettingsOptions.Value;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
public async Task<Result<string>> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken)
|
||||
{
|
||||
// resolve the local file path of the artwork, downloading it to a temporary file when it is remote
|
||||
Result<ArtworkSourceResult> resolveSourceResult = await ResolveArtworkSourceAsync(artwork, cancellationToken).ConfigureAwait(false);
|
||||
if (resolveSourceResult.IsFailure)
|
||||
return resolveSourceResult.Errors;
|
||||
string sourcePath = resolveSourceResult.Value.Path;
|
||||
|
||||
try
|
||||
{
|
||||
Result<string> storeResult = await StoreArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, sourcePath, cancellationToken).ConfigureAwait(false);
|
||||
if (storeResult.IsFailure)
|
||||
return storeResult.Errors;
|
||||
return storeResult;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// remove the temporary file downloaded for the remote artwork, never a local file of the user
|
||||
if (resolveSourceResult.Value.IsTemporary && File.Exists(sourcePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(sourcePath);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// a failed cleanup of the temporary file must not mask the result of the operation
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// a failed cleanup of the temporary file must not mask the result of the operation
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
public Result<Deleted> DeleteBookArtwork(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle)
|
||||
{
|
||||
Result<string> artworkDirectoryPathResult = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
if (artworkDirectoryPathResult.IsFailure)
|
||||
return artworkDirectoryPathResult.Errors;
|
||||
DeleteCover(artworkDirectoryPathResult.Value);
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the artwork file at <paramref name="sourcePath"/> into 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>
|
||||
/// <param name="sourcePath">The file system path of the artwork file 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>
|
||||
private async Task<Result<string>> StoreArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, string sourcePath, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<FileSystemPathId> sourcePathIdResult = FileSystemPathId.Create(sourcePath);
|
||||
if (sourcePathIdResult.IsFailure)
|
||||
return sourcePathIdResult.Errors;
|
||||
|
||||
Result<bool> fileExistsResult = _environmentContext.FileProviderService.FileExists(sourcePathIdResult.Value);
|
||||
if (fileExistsResult.IsFailure)
|
||||
return fileExistsResult.Errors;
|
||||
if (!fileExistsResult.Value)
|
||||
return Errors.FileSystemManagement.FileNotFound;
|
||||
|
||||
// reject the artwork when it is a symbolic link or a reparse point, which could point to any file of the machine
|
||||
if (File.GetAttributes(sourcePath).HasFlag(FileAttributes.ReparsePoint))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
|
||||
// reject the artwork when it exceeds the maximum allowed size
|
||||
FileInfo sourceFileInfo = new(sourcePath);
|
||||
if (sourceFileInfo.Length > MAX_ARTWORK_SIZE_BYTES)
|
||||
return Errors.FileSystemManagement.FileTooLarge;
|
||||
|
||||
// make sure the file is an actual supported image
|
||||
Result<ImageType> imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(sourcePathIdResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (imageTypeResult.IsFailure)
|
||||
return imageTypeResult.Errors;
|
||||
if (imageTypeResult.Value == ImageType.None)
|
||||
return Errors.Library.CoverFileMustBeAnImage;
|
||||
|
||||
Result<string> artworkDirectoryPathResult = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
if (artworkDirectoryPathResult.IsFailure)
|
||||
return artworkDirectoryPathResult.Errors;
|
||||
|
||||
Result<Success> ensureDirectoryResult = EnsureDirectory(artworkDirectoryPathResult.Value);
|
||||
if (ensureDirectoryResult.IsFailure)
|
||||
return ensureDirectoryResult.Errors;
|
||||
|
||||
// delete the previous cover of the book, so that a changed artwork does not leave orphaned files behind
|
||||
DeleteCover(artworkDirectoryPathResult.Value);
|
||||
|
||||
Result<FileSystemPathId> artworkDirectoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPathResult.Value);
|
||||
if (artworkDirectoryPathIdResult.IsFailure)
|
||||
return artworkDirectoryPathIdResult.Errors;
|
||||
|
||||
// copy the artwork file from the source location
|
||||
Result<FileSystemPathId> copyFileResult = _environmentContext.FileProviderService.CopyFile(sourcePathIdResult.Value, artworkDirectoryPathIdResult.Value, true);
|
||||
if (copyFileResult.IsFailure)
|
||||
return copyFileResult.Errors;
|
||||
|
||||
// rename the copied file to the standard naming
|
||||
Result<FileSystemPathId> renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToString().ToLowerInvariant()}");
|
||||
if (renameFileResult.IsFailure)
|
||||
return renameFileResult.Errors;
|
||||
|
||||
// get the internal relative path for the copied file
|
||||
string relativePath = renameFileResult.Value.Path[AppContext.BaseDirectory.Length..];
|
||||
if (!relativePath.StartsWith(_pathService.PathSeparator))
|
||||
relativePath = $"{_pathService.PathSeparator}{relativePath}";
|
||||
return relativePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the local file system path of the <paramref name="artwork"/>, downloading it to a temporary file when it is remote.
|
||||
/// </summary>
|
||||
/// <param name="artwork">The artwork whose source path is resolved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the resolved local source of the artwork, or an error.</returns>
|
||||
private async Task<Result<ArtworkSourceResult>> ResolveArtworkSourceAsync(ArtworkDto artwork, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(artwork.LocalPath))
|
||||
return new ArtworkSourceResult(artwork.LocalPath, IsTemporary: false);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(artwork.RemoteUrl))
|
||||
return Errors.FileSystemManagement.FileNotFound;
|
||||
|
||||
// download the remote artwork into a temporary file, aborting when it exceeds the maximum allowed size
|
||||
using HttpClient httpClient = _httpClientFactory.CreateClient();
|
||||
string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}");
|
||||
bool downloaded = false;
|
||||
try
|
||||
{
|
||||
using HttpResponseMessage response = await httpClient.GetAsync(artwork.RemoteUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return Errors.FileSystemManagement.FileNotFound;
|
||||
|
||||
await using Stream responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using FileStream fileStream = new(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true);
|
||||
|
||||
byte[] buffer = new byte[81920];
|
||||
long totalRead = 0;
|
||||
int bytesRead;
|
||||
while ((bytesRead = await responseStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
totalRead += bytesRead;
|
||||
if (totalRead > MAX_ARTWORK_SIZE_BYTES)
|
||||
return Errors.FileSystemManagement.FileTooLarge;
|
||||
await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
downloaded = true;
|
||||
return new ArtworkSourceResult(tempPath, IsTemporary: true);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return Errors.FileSystemManagement.FileNotFound;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// remove the partially downloaded temporary file when the download failed
|
||||
if (!downloaded && File.Exists(tempPath))
|
||||
File.Delete(tempPath);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory of the book artwork, under 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}"/> containing either the file system path of the book artwork directory, or an error.</returns>
|
||||
private Result<string> BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle)
|
||||
{
|
||||
Result<string> mediaRootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettings.RootDirectory);
|
||||
if (mediaRootPathResult.IsFailure)
|
||||
return mediaRootPathResult.Errors;
|
||||
Result<string> booksPathResult = _pathService.CombinePath(mediaRootPathResult.Value, _mediaSettings.BooksDirectory);
|
||||
if (booksPathResult.IsFailure)
|
||||
return booksPathResult.Errors;
|
||||
|
||||
Result<PathSegment> librarySegmentResult = _pathService.SanitizeSegment($"{libraryName}-{libraryId}");
|
||||
if (librarySegmentResult.IsFailure)
|
||||
return librarySegmentResult.Errors;
|
||||
Result<PathSegment> authorSegmentResult = _pathService.SanitizeSegment(string.IsNullOrWhiteSpace(authorName) ? "Unknown" : authorName);
|
||||
if (authorSegmentResult.IsFailure)
|
||||
return authorSegmentResult.Errors;
|
||||
Result<PathSegment> bookSegmentResult = _pathService.SanitizeSegment($"{bookTitle}-{bookId}");
|
||||
if (bookSegmentResult.IsFailure)
|
||||
return bookSegmentResult.Errors;
|
||||
|
||||
Result<string> libraryPathResult = _pathService.CombinePath(booksPathResult.Value, librarySegmentResult.Value.Name);
|
||||
if (libraryPathResult.IsFailure)
|
||||
return libraryPathResult.Errors;
|
||||
Result<string> authorPathResult = _pathService.CombinePath(libraryPathResult.Value, authorSegmentResult.Value.Name);
|
||||
if (authorPathResult.IsFailure)
|
||||
return authorPathResult.Errors;
|
||||
return _pathService.CombinePath(authorPathResult.Value, bookSegmentResult.Value.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the directory at <paramref name="directoryPath"/>, along with its missing parents.
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">The file system path of the directory to create.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private Result<Success> EnsureDirectory(string directoryPath)
|
||||
{
|
||||
Result<FileSystemPathId> directoryPathIdResult = FileSystemPathId.Create(directoryPath);
|
||||
if (directoryPathIdResult.IsFailure)
|
||||
return directoryPathIdResult.Errors;
|
||||
|
||||
Result<bool> directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value);
|
||||
if (directoryExistsResult.IsFailure)
|
||||
return directoryExistsResult.Errors;
|
||||
if (directoryExistsResult.Value)
|
||||
return Result.Success;
|
||||
|
||||
string? parentDirectoryPath = Path.GetDirectoryName(directoryPath);
|
||||
if (!string.IsNullOrEmpty(parentDirectoryPath) && !string.Equals(parentDirectoryPath, directoryPath, StringComparison.Ordinal))
|
||||
{
|
||||
Result<Success> createParentResult = EnsureDirectory(parentDirectoryPath);
|
||||
if (createParentResult.IsFailure)
|
||||
return createParentResult.Errors;
|
||||
}
|
||||
|
||||
Result<FileSystemPathId> parentDirectoryPathIdResult = FileSystemPathId.Create(parentDirectoryPath ?? directoryPath);
|
||||
if (parentDirectoryPathIdResult.IsFailure)
|
||||
return parentDirectoryPathIdResult.Errors;
|
||||
|
||||
Result<FileSystemPathId> createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(parentDirectoryPathIdResult.Value, Path.GetFileName(directoryPath));
|
||||
if (createDirectoryResult.IsFailure)
|
||||
return createDirectoryResult.Errors;
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the cover files of the book from the <paramref name="artworkDirectoryPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="artworkDirectoryPath">The file system path of the directory of the book artwork.</param>
|
||||
private void DeleteCover(string artworkDirectoryPath)
|
||||
{
|
||||
Result<FileSystemPathId> directoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPath);
|
||||
if (directoryPathIdResult.IsFailure)
|
||||
return;
|
||||
|
||||
Result<IEnumerable<FileSystemPathId>> getFilesResult = _environmentContext.FileProviderService.GetFilePaths(directoryPathIdResult.Value, true);
|
||||
if (getFilesResult.IsFailure)
|
||||
return;
|
||||
|
||||
foreach (FileSystemPathId filePathId in getFilesResult.Value)
|
||||
if (Regex.IsMatch(filePathId.Path, @"[\\/]cover\.[^.\\/]+$", RegexOptions.IgnoreCase))
|
||||
_environmentContext.FileProviderService.DeleteFile(filePathId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes the resolved local source of the artwork.
|
||||
/// </summary>
|
||||
private sealed record ArtworkSourceResult(string Path, bool IsTemporary);
|
||||
}
|
||||
@@ -25,6 +25,7 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" />
|
||||
<PackageReference Include="Otp.NET" />
|
||||
<PackageReference Include="QRCoder" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" />
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Contracts.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contract for a plugin that provides artwork for media items (i.e., covers, banners, fanart, etc).
|
||||
/// </summary>
|
||||
public interface IArtworkProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the display name of the artwork provider.
|
||||
/// </summary>
|
||||
string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library types this artwork provider supports.
|
||||
/// </summary>
|
||||
IReadOnlyList<LibraryType> SupportedLibraryTypes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
|
||||
/// </summary>
|
||||
bool RequiresWebAccess { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artwork of the media item described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to get the artwork for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artwork of the media item, or <see langword="null"/> when no artwork was found.</returns>
|
||||
Task<ArtworkDto?> GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Contracts.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contract for a plugin that provides artwork for media items, typed to the media item lookup type.
|
||||
/// </summary>
|
||||
/// <typeparam name="TLookup">The type of the lookup describing the media item.</typeparam>
|
||||
public interface IArtworkProvider<TLookup> : IArtworkProvider
|
||||
where TLookup : MetadataLookupDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the artwork of the media item described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to get the artwork for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artwork of the media item, or <see langword="null"/> when no artwork was found.</returns>
|
||||
Task<ArtworkDto?> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artwork of the media item described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to get the artwork for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artwork of the media item, or <see langword="null"/> when no artwork was found or the lookup is of another runtime type.</returns>
|
||||
async Task<ArtworkDto?> IArtworkProvider.GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
return lookup is TLookup typedLookup ? await GetArtworkAsync(typedLookup, cancellationToken).ConfigureAwait(false) : null;
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -171,7 +171,14 @@ public static class PresentationApiLayerServices
|
||||
|
||||
services.AddAuthorization();
|
||||
|
||||
services.AddFastEndpoints(endpointDiscoveryOptions => endpointDiscoveryOptions.Assemblies = [ typeof(Program).Assembly ]);
|
||||
services.AddFastEndpoints(endpointDiscoveryOptions =>
|
||||
{
|
||||
endpointDiscoveryOptions.Assemblies = [ typeof(Program).Assembly ];
|
||||
// only scan the application assembly, so that duplicate copies of it loaded into other assembly load
|
||||
// contexts during the process lifetime are never scanned again; otherwise a single host can register
|
||||
// every endpoint multiple times and fail with duplicate routes
|
||||
endpointDiscoveryOptions.DisableAutoDiscovery = true;
|
||||
});
|
||||
|
||||
services.AddOpenApi();
|
||||
|
||||
|
||||
@@ -25,5 +25,8 @@ public static partial class ApiRoutes
|
||||
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";
|
||||
}
|
||||
}
|
||||
+7
-6
@@ -1,14 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Collections.Generic;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook;
|
||||
@@ -284,7 +284,8 @@ public class AddLibraryEndpointSummary : Summary<AddBookEndpoint, AddBookRequest
|
||||
LastMetadataUpdateUtc: default,
|
||||
MetadataProvider: default,
|
||||
CreatedOnUtc: DateTime.UtcNow,
|
||||
UpdatedOnUtc: default
|
||||
UpdatedOnUtc: default,
|
||||
CoverPath: null
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
+4
-2
@@ -154,7 +154,8 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint, GetBooksRequest
|
||||
LastMetadataUpdateUtc: default,
|
||||
MetadataProvider: default,
|
||||
CreatedOnUtc: DateTime.UtcNow,
|
||||
UpdatedOnUtc: default
|
||||
UpdatedOnUtc: default,
|
||||
CoverPath: null
|
||||
),
|
||||
new(
|
||||
Id: Guid.NewGuid(),
|
||||
@@ -260,7 +261,8 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint, GetBooksRequest
|
||||
LastMetadataUpdateUtc: default,
|
||||
MetadataProvider: default,
|
||||
CreatedOnUtc: DateTime.UtcNow,
|
||||
UpdatedOnUtc: default
|
||||
UpdatedOnUtc: default,
|
||||
CoverPath: null
|
||||
)
|
||||
],
|
||||
CurrentPage = 1,
|
||||
|
||||
+2
-2
@@ -31,7 +31,7 @@ public class GetBooksLiteEndpointSummary : Summary<GetBooksLiteEndpoint, GetBook
|
||||
PerPage: 48,
|
||||
SearchTerm: "fellowship",
|
||||
FilterAlphaKey: "f",
|
||||
IgnoreThePrefixForAlphaPicker: true,
|
||||
ShouldIgnoreThePrefixForAlphaPicker: true,
|
||||
SortBy: "title",
|
||||
SortOrder: SortOrder.Ascending
|
||||
);
|
||||
@@ -41,7 +41,7 @@ public class GetBooksLiteEndpointSummary : Summary<GetBooksLiteEndpoint, GetBook
|
||||
RequestParam(r => r.PerPage, "The maximum number of books to retrieve per page. Optional.");
|
||||
RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional.");
|
||||
RequestParam(r => r.FilterAlphaKey, "The alpha key used to filter the results by the first character of their title, for the alpha picker. Optional.");
|
||||
RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a title should be ignored when computing the alpha key, or not. Required.");
|
||||
RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a title should be ignored when computing the alpha key, or not. Required.");
|
||||
RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional.");
|
||||
RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional.");
|
||||
|
||||
|
||||
+56
@@ -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.GetLibraryArtworkProviders;
|
||||
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.GetLibraryArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artwork-providers</c> route.
|
||||
/// </summary>
|
||||
public class GetLibraryArtworkProvidersEndpoint : BaseEndpoint<GetLibraryArtworkProvidersRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetLibraryArtworkProvidersQuery, Result<IReadOnlyList<LibraryArtworkProviderResponse>>> _getLibraryArtworkProvidersQueryHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="getLibraryArtworkProvidersQueryHandler">Injected service for handling get library artwork providers queries.</param>
|
||||
public GetLibraryArtworkProvidersEndpoint(IQueryHandler<GetLibraryArtworkProvidersQuery, Result<IReadOnlyList<LibraryArtworkProviderResponse>>> getLibraryArtworkProvidersQueryHandler)
|
||||
{
|
||||
_getLibraryArtworkProvidersQueryHandler = getLibraryArtworkProvidersQueryHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(Http.GET);
|
||||
Routes(ApiRoutes.Libraries.GET_LIBRARY_ARTWORK_PROVIDERS);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artwork providers configured for the media library identified by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the Id of the media library whose artwork providers are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(GetLibraryArtworkProvidersRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _getLibraryArtworkProvidersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetLibraryArtworkProvidersEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryArtworkProvidersEndpointSummary : Summary<GetLibraryArtworkProvidersEndpoint, GetLibraryArtworkProvidersRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryArtworkProvidersEndpointSummary()
|
||||
{
|
||||
Summary = "Retrieves the artwork providers configured for a media library.";
|
||||
Description = "Retrieves the artwork providers configured for a media library, with their enabled state and rank.";
|
||||
|
||||
ExampleRequest = new GetLibraryArtworkProvidersRequest(
|
||||
LibraryId: Guid.NewGuid()
|
||||
);
|
||||
|
||||
RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are retrieved. Required.");
|
||||
|
||||
ResponseParam<LibraryArtworkProviderResponse>(r => r.PluginId, "The unique identifier of the plugin providing the artwork.");
|
||||
ResponseParam<LibraryArtworkProviderResponse>(r => r.Name, "The display name of the artwork provider.");
|
||||
ResponseParam<LibraryArtworkProviderResponse>(r => r.IsEnabled, "Whether the artwork provider is enabled for the media library.");
|
||||
ResponseParam<LibraryArtworkProviderResponse>(r => r.Rank, "The rank of the artwork provider, determining the order in which providers are tried.");
|
||||
|
||||
Response(200, "The artwork providers configured for the media library are returned.",
|
||||
example: new LibraryArtworkProviderResponse[] {
|
||||
new(
|
||||
PluginId: Guid.NewGuid(),
|
||||
Name: "Calibre",
|
||||
IsEnabled: true,
|
||||
Rank: 1
|
||||
),
|
||||
new(
|
||||
PluginId: Guid.NewGuid(),
|
||||
Name: "Goodreads",
|
||||
IsEnabled: false,
|
||||
Rank: 2
|
||||
)
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "You are not authorized",
|
||||
instance = "/api/v1/libraries/{libraryId}/artwork-providers"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
|
||||
instance = "/api/v1/libraries/{libraryId}/artwork-providers"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = "/api/v1/libraries/{libraryId}/artwork-providers"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
|
||||
title = "General.Failure",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = "/api/v1/libraries/{libraryId}/artwork-providers",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(404, "The request failed because the requested media library does not exist.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "LibraryNotFound",
|
||||
instance = "/api/v1/libraries/{libraryId}/artwork-providers",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = "/api/v1/libraries/{libraryId}/artwork-providers",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"LibraryIdCannotBeEmpty"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
#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;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artwork-providers/reorder</c> route.
|
||||
/// </summary>
|
||||
public class ReorderLibraryArtworkProvidersEndpoint : BaseEndpoint<ReorderLibraryArtworkProvidersRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<ReorderLibraryArtworkProvidersCommand, Result<Success>> _reorderLibraryArtworkProvidersCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="reorderLibraryArtworkProvidersCommandHandler">Injected service for handling reorder library artwork providers commands.</param>
|
||||
public ReorderLibraryArtworkProvidersEndpoint(ICommandHandler<ReorderLibraryArtworkProvidersCommand, Result<Success>> reorderLibraryArtworkProvidersCommandHandler)
|
||||
{
|
||||
_reorderLibraryArtworkProvidersCommandHandler = reorderLibraryArtworkProvidersCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.PUT);
|
||||
Routes(ApiRoutes.Libraries.REORDER_LIBRARY_ARTWORK_PROVIDERS);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reorders the artwork providers of the media library identified by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the Id of the media library and the plugin Ids in the new order.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(ReorderLibraryArtworkProvidersRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<Success> result = await _reorderLibraryArtworkProvidersCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="ReorderLibraryArtworkProvidersEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReorderLibraryArtworkProvidersEndpointSummary : Summary<ReorderLibraryArtworkProvidersEndpoint, ReorderLibraryArtworkProvidersRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
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 = "You are not authorized",
|
||||
instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
|
||||
instance = "/api/v1/libraries/{libraryId}/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<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"LibraryIdCannotBeEmpty",
|
||||
"PluginIdsListCannotBeNull",
|
||||
"PluginIdsListCannotBeEmpty"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
#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;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artwork-providers/{pluginId}/enabled</c> route.
|
||||
/// </summary>
|
||||
public class SetLibraryArtworkProviderEnabledEndpoint : BaseEndpoint<SetLibraryArtworkProviderEnabledRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<SetLibraryArtworkProviderEnabledCommand, Result<Success>> _setLibraryArtworkProviderEnabledCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="setLibraryArtworkProviderEnabledCommandHandler">Injected service for handling set library artwork provider enabled commands.</param>
|
||||
public SetLibraryArtworkProviderEnabledEndpoint(ICommandHandler<SetLibraryArtworkProviderEnabledCommand, Result<Success>> setLibraryArtworkProviderEnabledCommandHandler)
|
||||
{
|
||||
_setLibraryArtworkProviderEnabledCommandHandler = setLibraryArtworkProviderEnabledCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.PUT);
|
||||
Routes(ApiRoutes.Libraries.SET_LIBRARY_ARTWORK_PROVIDER_ENABLED);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enables or disables the artwork provider identified by <paramref name="request"/> for the media library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the Ids of the media library and of the artwork provider.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(SetLibraryArtworkProviderEnabledRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<Success> result = await _setLibraryArtworkProviderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="SetLibraryArtworkProviderEnabledEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetLibraryArtworkProviderEnabledEndpointSummary : Summary<SetLibraryArtworkProviderEnabledEndpoint, SetLibraryArtworkProviderEnabledRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
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 = "You are not authorized",
|
||||
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 = "Invalid token: The token expired at '01/01/2024 01:00:00'",
|
||||
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<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"LibraryIdCannotBeEmpty",
|
||||
"PluginIdCannotBeEmpty"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -166,7 +166,13 @@ public class Program
|
||||
app.UseStaticFiles(new StaticFileOptions
|
||||
{
|
||||
FileProvider = new PhysicalFileProvider(mediaRootPath),
|
||||
RequestPath = "/media"
|
||||
RequestPath = "/media",
|
||||
OnPrepareResponse = staticFileContext =>
|
||||
{
|
||||
// the served media must not run as active content, so that attacker-influenced files (e.g. SVG covers) cannot execute scripts on the API origin
|
||||
staticFileContext.Context.Response.Headers["X-Content-Type-Options"] = "nosniff";
|
||||
staticFileContext.Context.Response.Headers["Content-Security-Policy"] = "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:";
|
||||
}
|
||||
});
|
||||
|
||||
app.MapHub<MediaLibraryScanProgressHub>("/scanProgressHub");
|
||||
|
||||
@@ -137,7 +137,7 @@ public class BookDto
|
||||
/// <summary>
|
||||
/// Gets the volume or book number in the series, if applicable.
|
||||
/// </summary>
|
||||
public int? VolumeNumber { get; init; }
|
||||
public float? VolumeNumber { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the series id, if the book is part of a series.
|
||||
|
||||
@@ -29,4 +29,9 @@ public enum BookRatingSource
|
||||
/// Ratings from Google Books, a service that searches the full text of books and magazines that Google has scanned and converted to text.
|
||||
/// </summary>
|
||||
GoogleBooks,
|
||||
|
||||
/// <summary>
|
||||
/// Ratings sourced from Calibre, an ebook management application.
|
||||
/// </summary>
|
||||
Calibre,
|
||||
}
|
||||
@@ -42,7 +42,7 @@ public class GetBooksLiteRequest
|
||||
/// <summary>
|
||||
/// Gets or sets whether the leading "The " prefix of a title is ignored when computing the alpha key, or not.
|
||||
/// </summary>
|
||||
public bool IgnoreThePrefixForAlphaPicker { get; set; }
|
||||
public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the field by which to sort the results.
|
||||
|
||||
@@ -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>
|
||||
|
||||
+1
-2
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Requests.Libraries;
|
||||
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.Text;
|
||||
@@ -71,7 +70,7 @@ public class GetLibraryItemsEndpoint : BaseEndpoint<GetBooksLiteRequest, IResult
|
||||
endpoint.Append($"&searchTerm={Uri.EscapeDataString(query.SearchTerm)}");
|
||||
if (!string.IsNullOrWhiteSpace(query.FilterAlphaKey))
|
||||
endpoint.Append($"&filterAlphaKey={Uri.EscapeDataString(query.FilterAlphaKey)}");
|
||||
endpoint.Append($"&ignoreThePrefixForAlphaPicker={query.IgnoreThePrefixForAlphaPicker}");
|
||||
endpoint.Append($"&shouldIgnoreThePrefixForAlphaPicker={query.ShouldIgnoreThePrefixForAlphaPicker}");
|
||||
if (!string.IsNullOrWhiteSpace(query.SortBy))
|
||||
endpoint.Append($"&sortBy={Uri.EscapeDataString(query.SortBy)}");
|
||||
if (query.SortOrder is not null)
|
||||
|
||||
+1
-2
@@ -3,7 +3,6 @@ using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Requests.Libraries;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
@@ -28,7 +27,7 @@ public class GetLibraryItemsEndpointSummary : Summary<GetLibraryItemsEndpoint, G
|
||||
RequestParam(r => r.PerPage, "Optional. The maximum number of books to retrieve per page.");
|
||||
RequestParam(r => r.SearchTerm, "Optional. The search term used to filter results.");
|
||||
RequestParam(r => r.FilterAlphaKey, "Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker.");
|
||||
RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading The prefix of a title is ignored when computing the alpha key, or not.");
|
||||
RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading The prefix of a title is ignored when computing the alpha key, or not.");
|
||||
RequestParam(r => r.SortBy, "Optional. The name of the field by which to sort the results.");
|
||||
RequestParam(r => r.SortOrder, "Optional. The direction in which to sort the results.");
|
||||
|
||||
|
||||
+2
-2
@@ -100,7 +100,7 @@
|
||||
params.set('searchTerm', state.searchTerm);
|
||||
if (state.alphaKey !== null)
|
||||
params.set('filterAlphaKey', state.alphaKey);
|
||||
params.set('ignoreThePrefixForAlphaPicker', state.ignoreThePrefix);
|
||||
params.set('shouldIgnoreThePrefixForAlphaPicker', state.ignoreThePrefix);
|
||||
params.set('sortOrder', state.sortOrder);
|
||||
return `${url}?${params.toString()}`;
|
||||
}
|
||||
@@ -259,7 +259,7 @@
|
||||
async function loadSettingsAsync() {
|
||||
const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)');
|
||||
if (data) {
|
||||
state.ignoreThePrefix = data.ignoreThePrefixForAlphaPicker === true;
|
||||
state.ignoreThePrefix = data.shouldIgnoreThePrefixForAlphaPicker === true;
|
||||
state.perPage = data.isPaginationEnabled === true ? data.itemsPerPage : null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,6 +208,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "plugins", "plugins", "{02EA
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary", "..\plugins\Lumina.Plugins.OpenLibrary\Lumina.Plugins.OpenLibrary.csproj", "{EADCD78B-04D5-4FE3-855C-E3015531EC8E}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre", "..\plugins\Lumina.Plugins.Calibre\Lumina.Plugins.Calibre.csproj", "{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Domain.SharedKernel", "Lumina.Domain.SharedKernel\Lumina.Domain.SharedKernel.csproj", "{9450EAC6-1F33-4BE1-89E3-0275885FE3EE}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}"
|
||||
@@ -244,6 +246,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary.
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary.Fixtures", "..\tests\Common\Lumina.Plugins.OpenLibrary.Fixtures\Lumina.Plugins.OpenLibrary.Fixtures.csproj", "{16F65859-93AB-499F-A0BE-9EC05E20435F}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre.UnitTests", "..\tests\UnitTests\Lumina.Plugins.Calibre.UnitTests\Lumina.Plugins.Calibre.UnitTests.csproj", "{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre.Fixtures", "..\tests\Common\Lumina.Plugins.Calibre.Fixtures\Lumina.Plugins.Calibre.Fixtures.csproj", "{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.TestPlugin", "..\tests\Common\Lumina.TestPlugin\Lumina.TestPlugin.csproj", "{65AA7896-2DE2-4F07-A1B2-C1E1774521C2}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "theming", "theming", "{2872042D-061F-4C76-8017-0A518A7E28A7}"
|
||||
@@ -461,6 +467,18 @@ Global
|
||||
{EADCD78B-04D5-4FE3-855C-E3015531EC8E}.Release|x64.Build.0 = Release|Any CPU
|
||||
{EADCD78B-04D5-4FE3-855C-E3015531EC8E}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{EADCD78B-04D5-4FE3-855C-E3015531EC8E}.Release|x86.Build.0 = Release|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x86.Build.0 = Release|Any CPU
|
||||
{9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
@@ -665,6 +683,30 @@ Global
|
||||
{16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|x64.Build.0 = Release|Any CPU
|
||||
{16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|x86.Build.0 = Release|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x64.Build.0 = Release|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x86.Build.0 = Release|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x86.Build.0 = Release|Any CPU
|
||||
{65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
@@ -722,6 +764,7 @@ Global
|
||||
{788FADE4-342D-4919-8E5C-10CA8EDBE954} = {70B56088-6D3A-481E-9459-79AC6B16FEC1}
|
||||
{8CF6FEA4-624C-4EC9-93D6-EB7626059D7C} = {3C316ABB-08D5-4450-9A4E-91059DB54254}
|
||||
{EADCD78B-04D5-4FE3-855C-E3015531EC8E} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
{9450EAC6-1F33-4BE1-89E3-0275885FE3EE} = {3C316ABB-08D5-4450-9A4E-91059DB54254}
|
||||
{7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11}
|
||||
{E6449D94-C33A-41CE-9047-7298CF20C311} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}
|
||||
@@ -740,6 +783,8 @@ Global
|
||||
{C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}
|
||||
{FEC00EBD-6A64-4280-B0F7-1EC5321C294A} = {53B1231B-37F5-44BA-80D5-DBA979775F5C}
|
||||
{16F65859-93AB-499F-A0BE-9EC05E20435F} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}
|
||||
{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20} = {53B1231B-37F5-44BA-80D5-DBA979775F5C}
|
||||
{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}
|
||||
{65AA7896-2DE2-4F07-A1B2-C1E1774521C2} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}
|
||||
{2872042D-061F-4C76-8017-0A518A7E28A7} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2}
|
||||
EndGlobalSection
|
||||
|
||||
Reference in new issue
Block a user