mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +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
@@ -33,6 +33,7 @@
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.11" />
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.11" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.11" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.11" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Http.Polly" Version="10.0.11" />
|
||||
<PackageVersion Include="Microsoft.Extensions.ObjectPool" Version="10.0.11" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.11" />
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Calibre.Core;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Provides extension methods for registering the Calibre metadata and artwork providers.
|
||||
/// </summary>
|
||||
internal static class CalibreServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the Calibre book metadata provider, associated with the plugin that provides it.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to register the services into.</param>
|
||||
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
|
||||
/// <returns>The service collection, for chaining.</returns>
|
||||
internal static IServiceCollection AddCalibreBookMetadataProvider(this IServiceCollection services, Guid pluginId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
|
||||
// Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IMetadataProvider implementations.
|
||||
services.AddKeyedTransient<IMetadataProvider, CalibreBookMetadataProvider>(pluginId);
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the Calibre artwork provider, associated with the plugin that provides it.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to register the services into.</param>
|
||||
/// <param name="pluginId">The unique identifier of the plugin that provides the artwork.</param>
|
||||
/// <returns>The service collection, for chaining.</returns>
|
||||
internal static IServiceCollection AddCalibreArtworkProvider(this IServiceCollection services, Guid pluginId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
|
||||
// Register the artwork provider as a keyed by pluginId transient service, so it can be resolved specifically among other IArtworkProvider implementations.
|
||||
services.AddKeyedTransient<IArtworkProvider, CalibreArtworkProvider>(pluginId);
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a contributor of a book read from an OPF file.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the contributor.</param>
|
||||
/// <param name="Role">The role code of the contributor, for example <c>bkp</c> for the book producer.</param>
|
||||
[DebuggerDisplay("Name: {Name}")]
|
||||
internal sealed record OpfContributorDto(
|
||||
string Name,
|
||||
string? Role
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a creator of a book read from an OPF file.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the creator.</param>
|
||||
/// <param name="Role">The role code of the creator, for example <c>aut</c> for author.</param>
|
||||
[DebuggerDisplay("Name: {Name}")]
|
||||
internal sealed record OpfCreatorDto(
|
||||
string Name,
|
||||
string? Role
|
||||
);
|
||||
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the metadata read from a Calibre OPF file.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
internal sealed class OpfDocumentDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the title of the book.
|
||||
/// </summary>
|
||||
public string? Title { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the description of the book, in HTML format.
|
||||
/// </summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the publisher of the book.
|
||||
/// </summary>
|
||||
public string? Publisher { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the publication date of the book.
|
||||
/// </summary>
|
||||
public DateTimeOffset? PublishDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the language code of the book.
|
||||
/// </summary>
|
||||
public string? LanguageCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the series the book belongs to, if applicable.
|
||||
/// </summary>
|
||||
public string? Series { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the index of the book within its series, if applicable.
|
||||
/// </summary>
|
||||
public double? SeriesIndex { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the personal rating of the book, on a scale of 0 to 10.
|
||||
/// </summary>
|
||||
public int? Rating { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the href of the cover image, relative to the directory of the book.
|
||||
/// </summary>
|
||||
public string? CoverHref { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the creators of the book.
|
||||
/// </summary>
|
||||
public List<OpfCreatorDto> Creators { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the contributors of the book.
|
||||
/// </summary>
|
||||
public List<OpfContributorDto> Contributors { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the identifiers of the book, with their schemes.
|
||||
/// </summary>
|
||||
public List<OpfIdentifierDto> Identifiers { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the subjects of the book, used as tags.
|
||||
/// </summary>
|
||||
public List<string> Subjects { get; } = [];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for an identifier of a book read from an OPF file, with its scheme.
|
||||
/// </summary>
|
||||
/// <param name="Scheme">The scheme of the identifier, for example <c>ISBN</c> or <c>GOODREADS</c>.</param>
|
||||
/// <param name="Value">The value of the identifier.</param>
|
||||
[DebuggerDisplay("{Scheme}: {Value}")]
|
||||
internal sealed record OpfIdentifierDto(
|
||||
string Scheme,
|
||||
string Value
|
||||
);
|
||||
@@ -0,0 +1,67 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
using Lumina.Plugins.Calibre.Core.Opf;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Provides the cover of a book from the cover reference of the Calibre OPF file located next to the book file.
|
||||
/// </summary>
|
||||
internal sealed class CalibreArtworkProvider : IArtworkProvider<BookMetadataLookupDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the display name of the artwork provider.
|
||||
/// </summary>
|
||||
public string Name => "Calibre";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library types this artwork provider supports.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
|
||||
/// </summary>
|
||||
public bool RequiresWebAccess => false;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cover of the book described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the book to get the cover for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The cover of the book, or <see langword="null"/> when no cover was found.</returns>
|
||||
public Task<ArtworkDto?> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(lookup.Path))
|
||||
return Task.FromResult<ArtworkDto?>(null);
|
||||
|
||||
string bookDirectory = Path.GetDirectoryName(lookup.Path) ?? string.Empty;
|
||||
string opfFilePath = Path.Combine(bookDirectory, "metadata.opf");
|
||||
if (!File.Exists(opfFilePath))
|
||||
return Task.FromResult<ArtworkDto?>(null);
|
||||
|
||||
OpfDocumentDto document = OpfReader.Read(opfFilePath);
|
||||
if (string.IsNullOrWhiteSpace(document.CoverHref))
|
||||
return Task.FromResult<ArtworkDto?>(null);
|
||||
|
||||
// the cover reference must be a bare file name contained in the directory of the book, so that no file outside of it can be accessed
|
||||
string coverFileName = Path.GetFileName(document.CoverHref);
|
||||
if (coverFileName != document.CoverHref || Path.IsPathRooted(document.CoverHref))
|
||||
return Task.FromResult<ArtworkDto?>(null);
|
||||
|
||||
string coverFilePath = Path.Combine(bookDirectory, coverFileName);
|
||||
if (!File.Exists(coverFilePath))
|
||||
return Task.FromResult<ArtworkDto?>(null);
|
||||
|
||||
return Task.FromResult<ArtworkDto?>(new ArtworkDto(LocalPath: coverFilePath, RemoteUrl: null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Plugins.Calibre.Core.Mapping;
|
||||
using Lumina.Plugins.Calibre.Core.Opf;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Provides book metadata from Calibre OPF files by resolving lookups into book metadata DTOs.
|
||||
/// </summary>
|
||||
internal sealed class CalibreBookMetadataProvider : IMetadataProvider<BookMetadataLookupDto, BookMetadataDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the display name of the metadata provider.
|
||||
/// </summary>
|
||||
public string Name => "Calibre";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library types this metadata provider supports.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
|
||||
/// </summary>
|
||||
public bool RequiresWebAccess => false;
|
||||
|
||||
/// <summary>
|
||||
/// Searches for the metadata of the media item described by <paramref name="bookMetadataLookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookMetadataLookup">The lookup describing the media item to search for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The collection of metadata candidates found for the media item.</returns>
|
||||
public Task<IReadOnlyList<BookMetadataDto>> GetSearchResultsAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
|
||||
{
|
||||
BookMetadataDto? metadata = GetMetadata(bookMetadataLookup);
|
||||
return Task.FromResult<IReadOnlyList<BookMetadataDto>>(metadata is null ? [] : [metadata]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the metadata of the media item described by <paramref name="bookMetadataLookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookMetadataLookup">The lookup describing the media item to get the metadata for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found.</returns>
|
||||
public Task<BookMetadataDto?> GetMetadataAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(GetMetadata(bookMetadataLookup));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the metadata of the book from the OPF file located next to the book file described by <paramref name="bookMetadataLookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookMetadataLookup">The lookup describing the book to get the metadata for.</param>
|
||||
/// <returns>The metadata of the book, or <see langword="null"/> when no OPF file was found.</returns>
|
||||
private static BookMetadataDto? GetMetadata(BookMetadataLookupDto bookMetadataLookup)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(bookMetadataLookup.Path))
|
||||
return null;
|
||||
|
||||
string opfFilePath = Path.Combine(Path.GetDirectoryName(bookMetadataLookup.Path) ?? string.Empty, "metadata.opf");
|
||||
if (!File.Exists(opfFilePath))
|
||||
return null;
|
||||
|
||||
return CalibreMapper.Map(OpfReader.Read(opfFilePath));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Lumina.Plugins.Calibre.Common.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Plugin that provides book metadata and book covers from Calibre OPF files.
|
||||
/// </summary>
|
||||
public sealed class CalibrePlugin : IPlugin, IPluginServiceRegistrator
|
||||
{
|
||||
/// <summary>
|
||||
/// The unique identifier of the plugin.
|
||||
/// </summary>
|
||||
public static readonly Guid s_pluginId = new("a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the unique identifier of the plugin.
|
||||
/// </summary>
|
||||
public Guid Id => s_pluginId;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the plugin.
|
||||
/// </summary>
|
||||
public string Name => "Calibre Metadata";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the author of the plugin.
|
||||
/// </summary>
|
||||
public string Author => "Lumina";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the version of the plugin.
|
||||
/// </summary>
|
||||
public Version Version => new(1, 0, 0);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the description of the plugin.
|
||||
/// </summary>
|
||||
public string Description => "Reads book metadata and covers from the OPF files of a Calibre library.";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the settings schema of the plugin.
|
||||
/// </summary>
|
||||
/// <returns>The settings descriptors of the plugin.</returns>
|
||||
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the services required by the plugin.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to register the services into.</param>
|
||||
public void RegisterServices(IServiceCollection services)
|
||||
{
|
||||
services.AddCalibreBookMetadataProvider(pluginId: Id);
|
||||
services.AddCalibreArtworkProvider(pluginId: Id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
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 Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Core.Mapping;
|
||||
|
||||
/// <summary>
|
||||
/// Maps the metadata read from a Calibre OPF file into the application's book metadata DTO.
|
||||
/// </summary>
|
||||
internal static class CalibreMapper
|
||||
{
|
||||
/// <summary>
|
||||
/// Maps the metadata read from the OPF file into a book metadata DTO.
|
||||
/// </summary>
|
||||
/// <param name="document">The metadata read from the OPF file.</param>
|
||||
/// <returns>The mapped book metadata.</returns>
|
||||
public static BookMetadataDto Map(OpfDocumentDto document)
|
||||
{
|
||||
float? volumeNumber = document.SeriesIndex is > 0 ? (float?)document.SeriesIndex : null;
|
||||
|
||||
return new BookMetadataDto(
|
||||
Title: document.Title,
|
||||
OriginalTitle: null,
|
||||
Description: StripHtml(document.Description),
|
||||
ReleaseInfo: BuildReleaseInfo(document.PublishDate),
|
||||
Genres: null,
|
||||
Tags: [.. document.Subjects.Select(subject => new TagDto(Name: subject))],
|
||||
Language: MapLanguage(document.LanguageCode),
|
||||
OriginalLanguage: null,
|
||||
Publisher: document.Publisher,
|
||||
PageCount: null,
|
||||
Format: null,
|
||||
Edition: null,
|
||||
VolumeNumber: volumeNumber,
|
||||
Series: document.Series is null ? null : new BookSeriesDto(Title: document.Series),
|
||||
ASIN: GetIdentifier(document.Identifiers, "asin", "amazon"),
|
||||
GoodreadsId: GetIdentifier(document.Identifiers, "goodreads"),
|
||||
LCCN: GetIdentifier(document.Identifiers, "lccn"),
|
||||
OCLCNumber: GetIdentifier(document.Identifiers, "oclc"),
|
||||
OpenLibraryId: GetIdentifier(document.Identifiers, "openlibrary"),
|
||||
LibraryThingId: null,
|
||||
GoogleBooksId: GetIdentifier(document.Identifiers, "google", "googlebooks"),
|
||||
BarnesAndNobleId: null,
|
||||
AppleBooksId: null,
|
||||
Isbns: BuildIsbns(document.Identifiers),
|
||||
Contributors: BuildContributors(document.Creators, document.Contributors),
|
||||
Ratings: document.Rating is null ? null : [new BookRatingDto(Value: document.Rating, MaxValue: 10m, Source: BookRatingSource.Calibre, VoteCount: null)],
|
||||
CoverImagePath: null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the release information of the book from its publication date.
|
||||
/// </summary>
|
||||
/// <param name="publishDate">The publication date of the book.</param>
|
||||
/// <returns>The release information of the book, always present even when the publication date is missing.</returns>
|
||||
private static ReleaseInfoDto BuildReleaseInfo(DateTimeOffset? publishDate)
|
||||
{
|
||||
// the release info must always be present, even when the publication date is missing, so that the metadata can be applied to the book
|
||||
if (publishDate is null)
|
||||
{
|
||||
return new ReleaseInfoDto(
|
||||
OriginalReleaseDate: null,
|
||||
OriginalReleaseYear: null,
|
||||
ReReleaseDate: null,
|
||||
ReReleaseYear: null,
|
||||
ReleaseCountry: null,
|
||||
ReleaseVersion: null
|
||||
);
|
||||
}
|
||||
|
||||
DateOnly? releaseDate = DateOnly.FromDateTime(publishDate.Value.Date);
|
||||
return new ReleaseInfoDto(
|
||||
OriginalReleaseDate: releaseDate,
|
||||
OriginalReleaseYear: releaseDate?.Year,
|
||||
ReReleaseDate: null,
|
||||
ReReleaseYear: null,
|
||||
ReleaseCountry: null,
|
||||
ReleaseVersion: null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the ISBN identifiers of the book into ISBN DTOs, de-duplicating normalized values.
|
||||
/// </summary>
|
||||
/// <param name="identifiers">The identifiers read from the OPF file.</param>
|
||||
/// <returns>The mapped and de-duplicated ISBN DTOs.</returns>
|
||||
private static List<IsbnDto> BuildIsbns(List<OpfIdentifierDto> identifiers)
|
||||
{
|
||||
List<IsbnDto> result = [];
|
||||
HashSet<string> seen = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (OpfIdentifierDto identifier in identifiers.Where(identifier => string.Equals(identifier.Scheme, "isbn", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
string? normalized = NormalizeIsbn(identifier.Value);
|
||||
if (normalized is null || !seen.Add(normalized))
|
||||
continue;
|
||||
result.Add(new IsbnDto(Value: normalized, Format: normalized.Length == 10 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the creators and contributors of the book into contributor DTOs, de-duplicating identical name and role pairs.
|
||||
/// </summary>
|
||||
/// <param name="creators">The creators read from the OPF file.</param>
|
||||
/// <param name="contributors">The contributors read from the OPF file.</param>
|
||||
/// <returns>The mapped contributor DTOs.</returns>
|
||||
private static List<MediaContributorDto> BuildContributors(List<OpfCreatorDto> creators, List<OpfContributorDto> contributors)
|
||||
{
|
||||
List<MediaContributorDto> result = [];
|
||||
HashSet<string> seen = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
void Add(string? displayName, string role, string category)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}"))
|
||||
return;
|
||||
result.Add(new MediaContributorDto(
|
||||
Name: new MediaContributorNameDto(DisplayName: displayName.Trim(), LegalName: null),
|
||||
Role: new MediaContributorRoleDto(Name: role, Category: category))
|
||||
);
|
||||
}
|
||||
|
||||
foreach (OpfCreatorDto creator in creators)
|
||||
Add(creator.Name, "Author", "Writing");
|
||||
foreach (OpfContributorDto contributor in contributors)
|
||||
Add(contributor.Name, MapContributorRole(contributor.Role), MapContributorCategory(contributor.Role));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a language code into a language info DTO by matching it against known cultures.
|
||||
/// </summary>
|
||||
/// <param name="rawCode">The raw language code to map.</param>
|
||||
/// <returns>The mapped language info, or <see langword="null"/> when the code is empty.</returns>
|
||||
private static LanguageInfoDto? MapLanguage(string? rawCode)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(rawCode))
|
||||
return null;
|
||||
|
||||
string code = rawCode.Trim().ToLowerInvariant();
|
||||
IEnumerable<CultureInfo> cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
|
||||
.Concat(CultureInfo.GetCultures(CultureTypes.NeutralCultures));
|
||||
|
||||
CultureInfo? culture = cultures.FirstOrDefault(candidate =>
|
||||
string.Equals(candidate.TwoLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(candidate.ThreeLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
return culture is null
|
||||
? new LanguageInfoDto(LanguageCode: code, LanguageName: code, NativeName: null)
|
||||
: new LanguageInfoDto(LanguageCode: culture.TwoLetterISOLanguageName, LanguageName: culture.EnglishName, NativeName: culture.NativeName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Strips the HTML markup of a description, leaving the text content.
|
||||
/// </summary>
|
||||
/// <param name="value">The HTML value to strip.</param>
|
||||
/// <returns>The text content, or <see langword="null"/> when the value is empty.</returns>
|
||||
private static string? StripHtml(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return null;
|
||||
|
||||
string decoded = WebUtility.HtmlDecode(value);
|
||||
string withoutTags = Regex.Replace(decoded, "<[^>]+>", " ");
|
||||
string collapsed = Regex.Replace(withoutTags, @"\s+", " ").Trim();
|
||||
return collapsed.Length == 0 ? null : collapsed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes an ISBN into its canonical form without separators or whitespace.
|
||||
/// </summary>
|
||||
/// <param name="isbn">The ISBN to normalize.</param>
|
||||
/// <returns>The normalized ISBN, or <see langword="null"/> when the value is not a valid ISBN.</returns>
|
||||
private static string? NormalizeIsbn(string isbn)
|
||||
{
|
||||
string normalized = new string([.. isbn.Where(character => character is not '-' && !char.IsWhiteSpace(character))]).ToUpperInvariant();
|
||||
// valid ISBNs must be 10 or 13 characters in length, all characters except the last one must be digits, and the last one must be a digit for ISBN-13 and X for ISBN-10
|
||||
if ((normalized.Length != 10 && normalized.Length != 13) ||
|
||||
normalized[..^1].Any(character => !char.IsDigit(character)) ||
|
||||
(!char.IsDigit(normalized[^1]) && !(normalized.Length == 10 && normalized[^1] == 'X')))
|
||||
return null;
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the first identifier whose scheme matches one of the <paramref name="schemes"/>.
|
||||
/// </summary>
|
||||
/// <param name="identifiers">The identifiers read from the OPF file.</param>
|
||||
/// <param name="schemes">The identifier schemes to try, in order.</param>
|
||||
/// <returns>The identifier value, or <see langword="null"/> when no identifier matches.</returns>
|
||||
private static string? GetIdentifier(List<OpfIdentifierDto> identifiers, params string[] schemes)
|
||||
{
|
||||
foreach (OpfIdentifierDto identifier in identifiers)
|
||||
if (schemes.Any(scheme => string.Equals(identifier.Scheme, scheme, StringComparison.OrdinalIgnoreCase)))
|
||||
return identifier.Value;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a creator or contributor role code into a role name.
|
||||
/// </summary>
|
||||
/// <param name="role">The role code to map.</param>
|
||||
/// <returns>The mapped role name.</returns>
|
||||
private static string MapContributorRole(string? role)
|
||||
{
|
||||
return string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) ? "Author" : string.IsNullOrWhiteSpace(role) ? "Contributor" : role;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a creator or contributor role code into a contributor category.
|
||||
/// </summary>
|
||||
/// <param name="role">The role code to map.</param>
|
||||
/// <returns>The mapped contributor category.</returns>
|
||||
private static string MapContributorCategory(string? role)
|
||||
{
|
||||
if (string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) || role?.Contains("author", StringComparison.OrdinalIgnoreCase) == true)
|
||||
return "Writing";
|
||||
if (string.Equals(role, "ill", StringComparison.OrdinalIgnoreCase))
|
||||
return "Art";
|
||||
if (string.Equals(role, "trl", StringComparison.OrdinalIgnoreCase))
|
||||
return "Translation";
|
||||
if (string.Equals(role, "bkp", StringComparison.OrdinalIgnoreCase))
|
||||
return "Production";
|
||||
return "Other";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Core.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the metadata of a book from a Calibre OPF file.
|
||||
/// </summary>
|
||||
internal static class OpfReader
|
||||
{
|
||||
private const long MAX_OPF_FILE_SIZE_BYTES = 5 * 1024 * 1024;
|
||||
private static readonly XNamespace s_opfNamespace = "http://www.idpf.org/2007/opf";
|
||||
private static readonly XNamespace s_dcNamespace = "http://purl.org/dc/elements/1.1/";
|
||||
|
||||
/// <summary>
|
||||
/// Reads the metadata of the book from the OPF file at <paramref name="opfFilePath"/>.
|
||||
/// </summary>
|
||||
/// <param name="opfFilePath">The file system path of the OPF file to read.</param>
|
||||
/// <returns>The metadata read from the OPF file, with the fields that could not be read left empty.</returns>
|
||||
public static OpfDocumentDto Read(string opfFilePath)
|
||||
{
|
||||
OpfDocumentDto document = new();
|
||||
FileInfo fileInfo = new(opfFilePath);
|
||||
if (!fileInfo.Exists || fileInfo.Length > MAX_OPF_FILE_SIZE_BYTES)
|
||||
return document;
|
||||
|
||||
try
|
||||
{
|
||||
using FileStream fileStream = File.OpenRead(opfFilePath);
|
||||
// the OPF file is untrusted XML, so DTD processing and external entity resolution are disabled, and the document size is bounded
|
||||
XmlReaderSettings xmlReaderSettings = new()
|
||||
{
|
||||
DtdProcessing = DtdProcessing.Prohibit,
|
||||
XmlResolver = null,
|
||||
MaxCharactersInDocument = MAX_OPF_FILE_SIZE_BYTES,
|
||||
MaxCharactersFromEntities = 0
|
||||
};
|
||||
using XmlReader xmlReader = XmlReader.Create(fileStream, xmlReaderSettings);
|
||||
XDocument xDocument = XDocument.Load(xmlReader, LoadOptions.None);
|
||||
Parse(xDocument, document);
|
||||
}
|
||||
catch (XmlException)
|
||||
{
|
||||
// a malformed OPF file must not prevent the enrichment of the book from proceeding
|
||||
}
|
||||
|
||||
return document;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the metadata elements of the <paramref name="xDocument"/> into the <paramref name="document"/>.
|
||||
/// </summary>
|
||||
/// <param name="xDocument">The parsed OPF document.</param>
|
||||
/// <param name="document">The model onto which the parsed metadata is written.</param>
|
||||
private static void Parse(XDocument xDocument, OpfDocumentDto document)
|
||||
{
|
||||
XElement? metadata = xDocument.Root?.Element(s_opfNamespace + "metadata");
|
||||
if (metadata is null)
|
||||
return;
|
||||
|
||||
document.Title = GetElementText(metadata, s_dcNamespace + "title");
|
||||
document.Description = GetElementText(metadata, s_dcNamespace + "description");
|
||||
document.Publisher = GetElementText(metadata, s_dcNamespace + "publisher");
|
||||
document.LanguageCode = GetElementText(metadata, s_dcNamespace + "language");
|
||||
document.PublishDate = ParseDate(GetElementText(metadata, s_dcNamespace + "date"));
|
||||
|
||||
foreach (XElement identifier in metadata.Elements(s_dcNamespace + "identifier"))
|
||||
{
|
||||
string? scheme = identifier.Attribute(s_opfNamespace + "scheme")?.Value;
|
||||
if (!string.IsNullOrWhiteSpace(scheme) && !string.IsNullOrWhiteSpace(identifier.Value))
|
||||
document.Identifiers.Add(new OpfIdentifierDto(Scheme: scheme.Trim(), Value: identifier.Value.Trim()));
|
||||
}
|
||||
|
||||
foreach (XElement subject in metadata.Elements(s_dcNamespace + "subject"))
|
||||
if (!string.IsNullOrWhiteSpace(subject.Value))
|
||||
document.Subjects.Add(subject.Value.Trim());
|
||||
|
||||
foreach (XElement creator in metadata.Elements(s_dcNamespace + "creator"))
|
||||
if (!string.IsNullOrWhiteSpace(creator.Value))
|
||||
document.Creators.Add(new OpfCreatorDto(Name: creator.Value.Trim(), Role: creator.Attribute(s_opfNamespace + "role")?.Value?.Trim()));
|
||||
|
||||
foreach (XElement contributor in metadata.Elements(s_dcNamespace + "contributor"))
|
||||
if (!string.IsNullOrWhiteSpace(contributor.Value))
|
||||
document.Contributors.Add(new OpfContributorDto(Name: contributor.Value.Trim(), Role: contributor.Attribute(s_opfNamespace + "role")?.Value?.Trim()));
|
||||
|
||||
foreach (XElement meta in metadata.Elements(s_opfNamespace + "meta"))
|
||||
{
|
||||
string? name = meta.Attribute("name")?.Value;
|
||||
string? content = meta.Attribute("content")?.Value;
|
||||
if (name is null || content is null)
|
||||
continue;
|
||||
|
||||
if (string.Equals(name, "calibre:series", StringComparison.OrdinalIgnoreCase))
|
||||
document.Series = content.Trim();
|
||||
else if (string.Equals(name, "calibre:series_index", StringComparison.OrdinalIgnoreCase))
|
||||
document.SeriesIndex = ParseDouble(content);
|
||||
else if (string.Equals(name, "calibre:rating", StringComparison.OrdinalIgnoreCase))
|
||||
document.Rating = ParseInt(content);
|
||||
}
|
||||
|
||||
XElement? coverReference = xDocument.Root
|
||||
?.Element(s_opfNamespace + "guide")
|
||||
?.Elements(s_opfNamespace + "reference")
|
||||
.FirstOrDefault(reference => string.Equals(reference.Attribute("type")?.Value, "cover", StringComparison.OrdinalIgnoreCase));
|
||||
document.CoverHref = coverReference?.Attribute("href")?.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the trimmed text of the child element with the specified <paramref name="name"/> of the <paramref name="parent"/> element.
|
||||
/// </summary>
|
||||
/// <param name="parent">The parent element.</param>
|
||||
/// <param name="name">The name of the child element.</param>
|
||||
/// <returns>The trimmed text, or <see langword="null"/> when the element is missing or empty.</returns>
|
||||
private static string? GetElementText(XElement parent, XName name)
|
||||
{
|
||||
string? value = parent.Element(name)?.Value;
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a date string into a <see cref="DateTimeOffset"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">The date string to parse.</param>
|
||||
/// <returns>The parsed date, or <see langword="null"/> when the string is empty or cannot be parsed.</returns>
|
||||
private static DateTimeOffset? ParseDate(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return null;
|
||||
return DateTimeOffset.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTimeOffset result) ? result : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a double string.
|
||||
/// </summary>
|
||||
/// <param name="value">The string to parse.</param>
|
||||
/// <returns>The parsed value, or <see langword="null"/> when the string is empty or cannot be parsed.</returns>
|
||||
private static double? ParseDouble(string value)
|
||||
{
|
||||
return double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result) ? result : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses an integer string.
|
||||
/// </summary>
|
||||
/// <param name="value">The string to parse.</param>
|
||||
/// <returns>The parsed value, or <see langword="null"/> when the string is empty or cannot be parsed.</returns>
|
||||
private static int? ParseInt(string value)
|
||||
{
|
||||
return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int result) ? result : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
|
||||
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||
<Private>false</Private>
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,4 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")]
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.Fixtures")]
|
||||
+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
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LibraryArtworkProviderConfigurationEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryArtworkProviderConfigurationEntityFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="LibraryArtworkProviderConfigurationEntity"/> for the provided media library, plugin and rank.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the configuration belongs to.</param>
|
||||
/// <param name="pluginId">The Id of the plugin providing the artwork.</param>
|
||||
/// <param name="rank">The rank of the artwork provider, determining the order in which providers are tried.</param>
|
||||
/// <param name="isEnabled">Whether the artwork provider is enabled or not.</param>
|
||||
/// <returns>The created <see cref="LibraryArtworkProviderConfigurationEntity"/>.</returns>
|
||||
public LibraryArtworkProviderConfigurationEntity Create(
|
||||
Guid libraryId,
|
||||
Guid pluginId,
|
||||
int rank,
|
||||
bool isEnabled = true)
|
||||
{
|
||||
return new Faker<LibraryArtworkProviderConfigurationEntity>()
|
||||
.RuleFor(configuration => configuration.Id, faker => faker.Random.Guid())
|
||||
.RuleFor(configuration => configuration.LibraryId, libraryId)
|
||||
.RuleFor(configuration => configuration.PluginId, pluginId)
|
||||
.RuleFor(configuration => configuration.IsEnabled, isEnabled)
|
||||
.RuleFor(configuration => configuration.Rank, rank)
|
||||
.RuleFor(configuration => configuration.CreatedOnUtc, faker => faker.Date.Past())
|
||||
.RuleFor(configuration => configuration.CreatedBy, faker => faker.Random.Guid())
|
||||
.RuleFor(configuration => configuration.UpdatedOnUtc, faker => faker.Date.Recent())
|
||||
.RuleFor(configuration => configuration.UpdatedBy, faker => faker.Random.Guid())
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="LibraryArtworkProviderConfigurationEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <param name="libraryId">The Id of the media library the configurations belong to.</param>
|
||||
/// <param name="pluginId">The Id of the plugin providing the artwork.</param>
|
||||
/// <param name="rank">The rank of the artwork providers.</param>
|
||||
/// <returns>List of configured <see cref="LibraryArtworkProviderConfigurationEntity"/> instances.</returns>
|
||||
public List<LibraryArtworkProviderConfigurationEntity> CreateMany(int count, Guid libraryId, Guid pluginId, int rank)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create(libraryId, pluginId, rank))];
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ReorderLibraryArtworkProvidersCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReorderLibraryArtworkProvidersCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command to reorder the artwork providers of a media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose artwork providers are reordered.</param>
|
||||
/// <param name="pluginIds">Optional. The plugin Ids in the new order.</param>
|
||||
/// <returns>The created command.</returns>
|
||||
public ReorderLibraryArtworkProvidersCommand Create(
|
||||
Guid? libraryId = null,
|
||||
IReadOnlyList<Guid>? pluginIds = null)
|
||||
{
|
||||
return new Faker<ReorderLibraryArtworkProvidersCommand>()
|
||||
.CustomInstantiator(f => new ReorderLibraryArtworkProvidersCommand(
|
||||
default,
|
||||
default!))
|
||||
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
|
||||
.RuleFor(x => x.PluginIds, f => pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()])
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ReorderLibraryArtworkProvidersCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<ReorderLibraryArtworkProvidersCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="SetLibraryArtworkProviderEnabledCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetLibraryArtworkProviderEnabledCommandFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid command to enable or disable an artwork provider for a media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose artwork provider is enabled or disabled.</param>
|
||||
/// <param name="pluginId">Optional. The Id of the plugin providing the artwork.</param>
|
||||
/// <param name="isEnabled">Whether the artwork provider should be enabled for the media library.</param>
|
||||
/// <returns>The created command.</returns>
|
||||
public SetLibraryArtworkProviderEnabledCommand Create(
|
||||
Guid? libraryId = null,
|
||||
Guid? pluginId = null,
|
||||
bool isEnabled = true)
|
||||
{
|
||||
return new Faker<SetLibraryArtworkProviderEnabledCommand>()
|
||||
.CustomInstantiator(f => new SetLibraryArtworkProviderEnabledCommand(
|
||||
default,
|
||||
default,
|
||||
true))
|
||||
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
|
||||
.RuleFor(x => x.PluginId, pluginId ?? Guid.NewGuid())
|
||||
.RuleFor(x => x.IsEnabled, isEnabled)
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="SetLibraryArtworkProviderEnabledCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<SetLibraryArtworkProviderEnabledCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetLibraryArtworkProvidersQuery"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryArtworkProvidersQueryFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get the artwork providers of a media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose artwork providers are retrieved.</param>
|
||||
/// <returns>The created query.</returns>
|
||||
public GetLibraryArtworkProvidersQuery Create(
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new Faker<GetLibraryArtworkProvidersQuery>()
|
||||
.CustomInstantiator(f => new GetLibraryArtworkProvidersQuery(
|
||||
libraryId ?? Guid.NewGuid()))
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetLibraryArtworkProvidersQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<GetLibraryArtworkProvidersQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ArtworkDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtworkDtoFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an <see cref="ArtworkDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="localPath">Optional. The local file system path of the artwork.</param>
|
||||
/// <param name="remoteUrl">Optional. The remote URL of the artwork.</param>
|
||||
/// <returns>The created <see cref="ArtworkDto"/>.</returns>
|
||||
public ArtworkDto Create(
|
||||
string? localPath = null,
|
||||
string? remoteUrl = null)
|
||||
{
|
||||
return new ArtworkDto(localPath, remoteUrl);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ArtworkDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<ArtworkDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetLibraryArtworkProvidersRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryArtworkProvidersRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetLibraryArtworkProvidersRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose artwork providers are retrieved.</param>
|
||||
/// <returns>The created <see cref="GetLibraryArtworkProvidersRequest"/>.</returns>
|
||||
public GetLibraryArtworkProvidersRequest Create(
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new GetLibraryArtworkProvidersRequest(
|
||||
libraryId ?? _faker.Random.Guid()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetLibraryArtworkProvidersRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<GetLibraryArtworkProvidersRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ReorderLibraryArtworkProvidersRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReorderLibraryArtworkProvidersRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ReorderLibraryArtworkProvidersRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose artwork providers are reordered.</param>
|
||||
/// <param name="pluginIds">Optional. The plugin Ids in the new order.</param>
|
||||
/// <returns>The created <see cref="ReorderLibraryArtworkProvidersRequest"/>.</returns>
|
||||
public ReorderLibraryArtworkProvidersRequest Create(
|
||||
Guid? libraryId = null,
|
||||
IReadOnlyList<Guid>? pluginIds = null)
|
||||
{
|
||||
return new ReorderLibraryArtworkProvidersRequest(
|
||||
libraryId ?? _faker.Random.Guid(),
|
||||
pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="ReorderLibraryArtworkProvidersRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<ReorderLibraryArtworkProvidersRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="SetLibraryArtworkProviderEnabledRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetLibraryArtworkProviderEnabledRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="SetLibraryArtworkProviderEnabledRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose artwork provider is enabled or disabled.</param>
|
||||
/// <param name="pluginId">Optional. The Id of the plugin providing the artwork.</param>
|
||||
/// <param name="isEnabled">Optional. Whether the artwork provider should be enabled.</param>
|
||||
/// <returns>The created <see cref="SetLibraryArtworkProviderEnabledRequest"/>.</returns>
|
||||
public SetLibraryArtworkProviderEnabledRequest Create(
|
||||
Guid? libraryId = null,
|
||||
Guid? pluginId = null,
|
||||
bool? isEnabled = null)
|
||||
{
|
||||
return new SetLibraryArtworkProviderEnabledRequest(
|
||||
libraryId ?? _faker.Random.Guid(),
|
||||
pluginId ?? _faker.Random.Guid(),
|
||||
isEnabled ?? _faker.Random.Bool()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="SetLibraryArtworkProviderEnabledRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<SetLibraryArtworkProviderEnabledRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="LibraryArtworkProviderResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryArtworkProviderResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="LibraryArtworkProviderResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">Optional. The Id of the plugin providing the artwork.</param>
|
||||
/// <param name="name">Optional. The display name of the artwork provider.</param>
|
||||
/// <param name="isEnabled">Optional. Whether the artwork provider is enabled for the media library.</param>
|
||||
/// <param name="rank">Optional. The rank of the artwork provider.</param>
|
||||
/// <returns>The created <see cref="LibraryArtworkProviderResponse"/>.</returns>
|
||||
public LibraryArtworkProviderResponse Create(
|
||||
Guid? pluginId = null,
|
||||
string? name = null,
|
||||
bool? isEnabled = null,
|
||||
int? rank = null)
|
||||
{
|
||||
return new LibraryArtworkProviderResponse(
|
||||
pluginId ?? Guid.NewGuid(),
|
||||
name ?? _faker.Company.CompanyName(),
|
||||
isEnabled ?? _faker.Random.Bool(),
|
||||
rank ?? _faker.Random.Int(1, 100));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="LibraryArtworkProviderResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<LibraryArtworkProviderResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Fixtures.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="HttpMessageHandler"/> test double that returns the configured response for every request, without performing any network I/O.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class StubHttpMessageHandler : HttpMessageHandler
|
||||
{
|
||||
private HttpStatusCode _statusCode;
|
||||
private byte[] _responseBody;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StubHttpMessageHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The initial status code of the response to return.</param>
|
||||
/// <param name="responseBody">The initial body of the response to return.</param>
|
||||
public StubHttpMessageHandler(HttpStatusCode statusCode = HttpStatusCode.OK, byte[]? responseBody = null)
|
||||
{
|
||||
_statusCode = statusCode;
|
||||
_responseBody = responseBody ?? [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the response to return for every subsequent request.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The status code of the response to return.</param>
|
||||
/// <param name="responseBody">The body of the response to return.</param>
|
||||
public void SetResponse(HttpStatusCode statusCode, byte[] responseBody)
|
||||
{
|
||||
_statusCode = statusCode;
|
||||
_responseBody = responseBody;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a response with the configured status code and body.
|
||||
/// </summary>
|
||||
/// <param name="request">The request, which is ignored.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to cancel the operation.</param>
|
||||
/// <returns>The configured response.</returns>
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(new HttpResponseMessage(_statusCode)
|
||||
{
|
||||
Content = new ByteArrayContent(_responseBody)
|
||||
});
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="OpfContributorDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class OpfContributorDtoFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an <see cref="OpfContributorDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the contributor.</param>
|
||||
/// <param name="role">The role code of the contributor, for example <c>bkp</c> for the book producer.</param>
|
||||
/// <returns>The created <see cref="OpfContributorDto"/>.</returns>
|
||||
public OpfContributorDto Create(
|
||||
string name = "Test Contributor",
|
||||
string? role = null)
|
||||
{
|
||||
return new OpfContributorDto(name, role);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="OpfContributorDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<OpfContributorDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="OpfCreatorDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class OpfCreatorDtoFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an <see cref="OpfCreatorDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the creator.</param>
|
||||
/// <param name="role">The role code of the creator, for example <c>aut</c> for author.</param>
|
||||
/// <returns>The created <see cref="OpfCreatorDto"/>.</returns>
|
||||
public OpfCreatorDto Create(
|
||||
string name = "Test Creator",
|
||||
string? role = null)
|
||||
{
|
||||
return new OpfCreatorDto(name, role);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="OpfCreatorDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<OpfCreatorDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="OpfDocumentDto"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class OpfDocumentDtoFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an <see cref="OpfDocumentDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="title">Optional. The title of the book.</param>
|
||||
/// <param name="description">Optional. The description of the book, in HTML format.</param>
|
||||
/// <param name="publisher">Optional. The publisher of the book.</param>
|
||||
/// <param name="publishDate">Optional. The publication date of the book.</param>
|
||||
/// <param name="languageCode">Optional. The language code of the book.</param>
|
||||
/// <param name="series">Optional. The name of the series the book belongs to.</param>
|
||||
/// <param name="seriesIndex">Optional. The index of the book within its series.</param>
|
||||
/// <param name="rating">Optional. The personal rating of the book, on a scale of 0 to 10.</param>
|
||||
/// <param name="coverHref">Optional. The href of the cover image, relative to the directory of the book.</param>
|
||||
/// <param name="subjects">Optional. The subjects of the book, used as tags.</param>
|
||||
/// <param name="creators">Optional. The creators of the book.</param>
|
||||
/// <param name="contributors">Optional. The contributors of the book.</param>
|
||||
/// <param name="identifiers">Optional. The identifiers of the book, with their schemes.</param>
|
||||
/// <returns>The created <see cref="OpfDocumentDto"/>.</returns>
|
||||
public OpfDocumentDto Create(
|
||||
string? title = null,
|
||||
string? description = null,
|
||||
string? publisher = null,
|
||||
DateTimeOffset? publishDate = null,
|
||||
string? languageCode = null,
|
||||
string? series = null,
|
||||
double? seriesIndex = null,
|
||||
int? rating = null,
|
||||
string? coverHref = null,
|
||||
IEnumerable<string>? subjects = null,
|
||||
IEnumerable<OpfCreatorDto>? creators = null,
|
||||
IEnumerable<OpfContributorDto>? contributors = null,
|
||||
IEnumerable<OpfIdentifierDto>? identifiers = null)
|
||||
{
|
||||
OpfDocumentDto document = new()
|
||||
{
|
||||
Title = title,
|
||||
Description = description,
|
||||
Publisher = publisher,
|
||||
PublishDate = publishDate,
|
||||
LanguageCode = languageCode,
|
||||
Series = series,
|
||||
SeriesIndex = seriesIndex,
|
||||
Rating = rating,
|
||||
CoverHref = coverHref
|
||||
};
|
||||
if (subjects is not null)
|
||||
document.Subjects.AddRange(subjects);
|
||||
if (creators is not null)
|
||||
document.Creators.AddRange(creators);
|
||||
if (contributors is not null)
|
||||
document.Contributors.AddRange(contributors);
|
||||
if (identifiers is not null)
|
||||
document.Identifiers.AddRange(identifiers);
|
||||
return document;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="OpfDocumentDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<OpfDocumentDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="OpfIdentifierDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class OpfIdentifierDtoFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an <see cref="OpfIdentifierDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="scheme">The scheme of the identifier, for example <c>ISBN</c> or <c>GOODREADS</c>.</param>
|
||||
/// <param name="value">The value of the identifier.</param>
|
||||
/// <returns>The created <see cref="OpfIdentifierDto"/>.</returns>
|
||||
public OpfIdentifierDto Create(
|
||||
string scheme = "ISBN",
|
||||
string value = "9780306406157")
|
||||
{
|
||||
return new OpfIdentifierDto(scheme, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="OpfIdentifierDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<OpfIdentifierDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Fixtures.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Concrete <see cref="MetadataLookupDto"/> used to represent a lookup that is not a book lookup.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed record TestMetadataLookup(Guid LibraryId, string Path) : MetadataLookupDto;
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.Fixtures.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="TestMetadataLookup"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class TestMetadataLookupFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="TestMetadataLookup"/> that is not a book lookup.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library, or <see langword="null"/> to generate a random one.</param>
|
||||
/// <param name="path">The file system path of the media item.</param>
|
||||
/// <returns>The created <see cref="TestMetadataLookup"/>.</returns>
|
||||
public TestMetadataLookup Create(
|
||||
Guid? libraryId = null,
|
||||
string? path = null)
|
||||
{
|
||||
return new TestMetadataLookup(libraryId ?? Guid.NewGuid(), path ?? "/some/path");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="TestMetadataLookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<TestMetadataLookup> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture" />
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" />
|
||||
<PackageReference Include="Bogus" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.Calibre\Lumina.Plugins.Calibre.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("Lumina.Plugins.Calibre.Fixtures")]
|
||||
[assembly: AssemblyProduct("Lumina.Plugins.Calibre.Fixtures")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31")]
|
||||
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")]
|
||||
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibraryArtworkProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryArtworkProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryArtworkProviders_WhenProvidersAreConfigured_ShouldReturnThemOrderedByRank()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
Guid pluginIdA = Guid.NewGuid();
|
||||
Guid pluginIdB = Guid.NewGuid();
|
||||
await SeedConfigurationAsync(libraryId, pluginIdA, pluginIdB);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<LibraryArtworkProviderResponse>? providers = await response.Content.ReadFromJsonAsync<List<LibraryArtworkProviderResponse>>(_jsonOptions);
|
||||
Assert.NotNull(providers);
|
||||
Assert.Equal(2, providers!.Count);
|
||||
Assert.Equal(pluginIdA, providers[0].PluginId);
|
||||
Assert.Equal(1, providers[0].Rank);
|
||||
Assert.Equal(pluginIdB, providers[1].PluginId);
|
||||
Assert.Equal(2, providers[1].Rank);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryArtworkProviders_WhenNoProvidersAreConfigured_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<LibraryArtworkProviderResponse>? providers = await response.Content.ReadFromJsonAsync<List<LibraryArtworkProviderResponse>>(_jsonOptions);
|
||||
Assert.NotNull(providers);
|
||||
Assert.Empty(providers!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds two <see cref="LibraryArtworkProviderConfigurationEntity"/> instances in the database.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="pluginIdA">The Id of the first plugin.</param>
|
||||
/// <param name="pluginIdB">The Id of the second plugin.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginIdA, Guid pluginIdB)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdA, rank: 1, isEnabled: true));
|
||||
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdB, rank: 2, isEnabled: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ReorderLibraryArtworkProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
|
||||
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ReorderLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReorderLibraryArtworkProviders_WhenCalledWithValidData_ShouldReorderTheProviders()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
Guid pluginIdA = Guid.NewGuid();
|
||||
Guid pluginIdB = Guid.NewGuid();
|
||||
await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1);
|
||||
await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2);
|
||||
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
pluginIds: [pluginIdB, pluginIdA]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<LibraryArtworkProviderConfigurationEntity> configurations = await dbContext.LibraryArtworkProviderConfigurations
|
||||
.Where(config => config.LibraryId == libraryId)
|
||||
.OrderBy(config => config.Rank)
|
||||
.ToListAsync();
|
||||
Assert.Equal(2, configurations.Count);
|
||||
Assert.Equal(pluginIdB, configurations[0].PluginId);
|
||||
Assert.Equal(1, configurations[0].Rank);
|
||||
Assert.Equal(pluginIdA, configurations[1].PluginId);
|
||||
Assert.Equal(2, configurations[1].Rank);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> in the database.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="pluginId">The Id of the plugin.</param>
|
||||
/// <param name="rank">The rank of the provider.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="SetLibraryArtworkProviderEnabledEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
|
||||
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public SetLibraryArtworkProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetLibraryArtworkProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations
|
||||
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
|
||||
Assert.NotNull(configuration);
|
||||
Assert.True(configuration!.IsEnabled);
|
||||
Assert.Equal(1, configuration.Rank);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetLibraryArtworkProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1);
|
||||
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations
|
||||
.FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
|
||||
Assert.NotNull(configuration);
|
||||
Assert.True(configuration!.IsEnabled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> in the database.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="pluginId">The Id of the plugin.</param>
|
||||
/// <param name="isEnabled">Whether the provider is enabled.</param>
|
||||
/// <param name="rank">The rank of the provider.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user