mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #174 from BinaryAlley/feature/add-artwork-provider-and-metadata-aggregation
Feature/add artwork provider and metadata aggregation
This commit is contained in:
706 files changed
+27764
-4112
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
-15
@@ -8,8 +8,6 @@ using Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.OpenLibrary.Common.DependencyInjection;
|
||||
@@ -30,27 +28,20 @@ internal static class OpenLibraryServices
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
|
||||
// Build the runtime settings per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
|
||||
// Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
|
||||
services.TryAddScoped(serviceProvider =>
|
||||
{
|
||||
OpenLibrarySettingsDto openLibrarySettings = new();
|
||||
settingsCallback?.Invoke(openLibrarySettings);
|
||||
OpenLibrarySettingsDto defaults = new();
|
||||
settingsCallback?.Invoke(defaults);
|
||||
|
||||
IPluginSettingsStore? settingsStore = serviceProvider.GetService<IPluginSettingsStore>();
|
||||
if (settingsStore is not null)
|
||||
{
|
||||
IReadOnlyDictionary<string, string>? storedSettings = settingsStore.GetSettingsAsync(pluginId, CancellationToken.None).GetAwaiter().GetResult();
|
||||
if (storedSettings is not null)
|
||||
OpenLibrarySettingsLoader.Apply(openLibrarySettings, storedSettings);
|
||||
}
|
||||
|
||||
return openLibrarySettings;
|
||||
return new OpenLibrarySettingsProvider(settingsStore, pluginId, defaults);
|
||||
});
|
||||
|
||||
services.AddHttpClient<OpenLibraryHttpClient>();
|
||||
|
||||
// Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IRemoteMetadataProvider implementations.
|
||||
services.AddKeyedTransient<IRemoteMetadataProvider, OpenLibraryBookMetadataProvider>(pluginId);
|
||||
// Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IMetadataProvider implementations.
|
||||
services.AddKeyedTransient<IMetadataProvider, OpenLibraryBookMetadataProvider>(pluginId);
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Mapping;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
@@ -25,7 +26,7 @@ namespace Lumina.Plugins.OpenLibrary.Core.Api;
|
||||
internal sealed class OpenLibraryHttpClient
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly OpenLibrarySettingsDto _openLibrarySettings;
|
||||
private readonly OpenLibrarySettingsProvider _settingsProvider;
|
||||
private readonly SemaphoreSlim _requestGate = new(1, 1);
|
||||
private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
|
||||
|
||||
@@ -44,18 +45,26 @@ internal sealed class OpenLibraryHttpClient
|
||||
/// Initializes a new instance of the <see cref="OpenLibraryHttpClient"/> class.
|
||||
/// </summary>
|
||||
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the Open Library API.</param>
|
||||
/// <param name="openLibrarySettings">The settings that configure the Open Library API requests.</param>
|
||||
public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsDto openLibrarySettings)
|
||||
/// <param name="settingsProvider">The provider of the settings that configure the Open Library API requests.</param>
|
||||
public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsProvider settingsProvider)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_openLibrarySettings = openLibrarySettings;
|
||||
_settingsProvider = settingsProvider;
|
||||
|
||||
_httpClient.BaseAddress ??= new("https://openlibrary.org/");
|
||||
if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
|
||||
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(openLibrarySettings.UserAgent);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(openLibrarySettings.ContactEmail) && _httpClient.DefaultRequestHeaders.From is null)
|
||||
_httpClient.DefaultRequestHeaders.From = openLibrarySettings.ContactEmail!;
|
||||
/// <summary>
|
||||
/// Applies the request headers configured in the <paramref name="settings"/> onto the underlying HTTP client, unless they are already set.
|
||||
/// </summary>
|
||||
/// <param name="settings">The settings that configure the Open Library API requests.</param>
|
||||
private void EnsureRequestHeaders(OpenLibrarySettingsDto settings)
|
||||
{
|
||||
if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
|
||||
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(settings.UserAgent);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(settings.ContactEmail) && _httpClient.DefaultRequestHeaders.From is null)
|
||||
_httpClient.DefaultRequestHeaders.From = settings.ContactEmail!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -214,10 +223,13 @@ internal sealed class OpenLibraryHttpClient
|
||||
/// <returns>The HTTP response message for the request.</returns>
|
||||
private async Task<HttpResponseMessage> SendAsync(string relativeUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
|
||||
EnsureRequestHeaders(settings);
|
||||
|
||||
await _requestGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
DateTimeOffset earliestNextRequest = _lastRequestAt + _openLibrarySettings.MinimumRequestInterval;
|
||||
DateTimeOffset earliestNextRequest = _lastRequestAt + settings.MinimumRequestInterval;
|
||||
TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
|
||||
if (delay > TimeSpan.Zero)
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -30,7 +30,7 @@ internal static partial class OpenLibraryMapper
|
||||
/// <summary>
|
||||
/// Matches a volume number in a series or volume string.
|
||||
/// </summary>
|
||||
[GeneratedRegex(@"\b(?:volume|vol\.?|book|no\.?|#)\s*(?<number>\d+)\b", RegexOptions.IgnoreCase)]
|
||||
[GeneratedRegex(@"\b(?:volume|vol\.?|book|no\.?|#)\s*(?<number>\d+(?:\.\d+)?)\b", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex VolumePattern();
|
||||
|
||||
/// <summary>
|
||||
@@ -111,8 +111,8 @@ internal static partial class OpenLibraryMapper
|
||||
editionRelease.Date?.Year ?? editionRelease.Year,
|
||||
NullIfWhiteSpace(releaseCountry),
|
||||
NullIfWhiteSpace(releaseVersion)),
|
||||
genreNames.Select(name => new GenreDto(name)).ToList(),
|
||||
subjects.Select(name => new TagDto(name)).ToList(),
|
||||
[.. genreNames.Select(name => new GenreDto(name))],
|
||||
[.. subjects.Select(name => new TagDto(name))],
|
||||
MapLanguage(currentLanguageCode),
|
||||
MapLanguage(originalLanguageCode),
|
||||
edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(),
|
||||
@@ -347,14 +347,14 @@ internal static partial class OpenLibraryMapper
|
||||
/// </summary>
|
||||
/// <param name="candidates">The strings that may contain a volume number.</param>
|
||||
/// <returns>The parsed volume number, or <see langword="null"/> when no candidate contains one.</returns>
|
||||
private static int? ParseVolumeNumber(params string?[] candidates)
|
||||
private static float? ParseVolumeNumber(params string?[] candidates)
|
||||
{
|
||||
foreach (string? candidate in candidates)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(candidate))
|
||||
continue;
|
||||
Match match = VolumePattern().Match(candidate);
|
||||
if (match.Success && int.TryParse(match.Groups["number"].Value, out int number))
|
||||
if (match.Success && float.TryParse(match.Groups["number"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out float number))
|
||||
return number;
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -7,6 +7,7 @@ using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Api;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Mapping;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -19,10 +20,10 @@ namespace Lumina.Plugins.OpenLibrary.Core;
|
||||
/// <summary>
|
||||
/// Provides book metadata from the Open Library by resolving lookups into book metadata DTOs.
|
||||
/// </summary>
|
||||
internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<BookMetadataLookupDto, BookMetadataDto>
|
||||
internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMetadataLookupDto, BookMetadataDto>
|
||||
{
|
||||
private readonly OpenLibraryHttpClient _openLibraryHttpClient;
|
||||
private readonly OpenLibrarySettingsDto _openLibrarySettings;
|
||||
private readonly OpenLibrarySettingsProvider _settingsProvider;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the metadata provider.
|
||||
@@ -30,9 +31,9 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
public string Name => "Open Library";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library type this metadata provider supports.
|
||||
/// Gets the media library types this metadata provider supports.
|
||||
/// </summary>
|
||||
public LibraryType SupportedLibraryType => LibraryType.Book;
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Book];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
|
||||
@@ -43,11 +44,11 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
/// Initializes a new instance of the <see cref="OpenLibraryBookMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
/// <param name="openLibraryHttpClient">The HTTP client used to call the Open Library API.</param>
|
||||
/// <param name="openLibrarySettings">The settings that configure the Open Library API requests.</param>
|
||||
public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsDto openLibrarySettings)
|
||||
/// <param name="settingsProvider">The provider of the settings that configure the Open Library API requests.</param>
|
||||
public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsProvider settingsProvider)
|
||||
{
|
||||
_openLibraryHttpClient = openLibraryHttpClient;
|
||||
_openLibrarySettings = openLibrarySettings;
|
||||
_settingsProvider = settingsProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -60,6 +61,8 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
{
|
||||
ValidateLookup(bookMetadataLookup);
|
||||
|
||||
OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) || !string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId))
|
||||
{
|
||||
AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
|
||||
@@ -90,11 +93,11 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
exactBookRequestMatch.ISBNs,
|
||||
exactBookRequestMatch.Contributors,
|
||||
exactBookRequestMatch.Ratings,
|
||||
CoverImageUrl: null
|
||||
CoverImagePath: null
|
||||
)];
|
||||
}
|
||||
|
||||
IReadOnlyList<OpenLibrarySearchDocumentResponse> openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, _openLibrarySettings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<OpenLibrarySearchDocumentResponse> openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return [.. openLibrarySearchDocuments
|
||||
.Where(openLibrarySearchDocument => !string.IsNullOrWhiteSpace(openLibrarySearchDocument.Title))
|
||||
@@ -128,7 +131,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
addBookRequest.ISBNs,
|
||||
addBookRequest.Contributors,
|
||||
addBookRequest.Ratings,
|
||||
CoverImageUrl: null
|
||||
CoverImagePath: null
|
||||
);
|
||||
})];
|
||||
}
|
||||
@@ -169,7 +172,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
exactBookRequestMatch.ISBNs,
|
||||
exactBookRequestMatch.Contributors,
|
||||
exactBookRequestMatch.Ratings,
|
||||
CoverImageUrl: null
|
||||
CoverImagePath: null
|
||||
);
|
||||
}
|
||||
|
||||
@@ -183,6 +186,8 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
{
|
||||
ValidateLookup(bookMetadataLookup);
|
||||
|
||||
OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
OpenLibraryEditionResponse? openLibraryEditionResponse = null;
|
||||
OpenLibraryWorkResponse? openLibraryWorkResponse = null;
|
||||
OpenLibrarySearchDocumentResponse? openLibrarySearchDocumentResponse = null;
|
||||
@@ -199,7 +204,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
// A work has no publisher-specific details on its own (no ISBN, page count, etc.), so we still need to pull it for its work-level fields (e.g. description, subjects).
|
||||
openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(olid, cancellationToken).ConfigureAwait(false);
|
||||
// A work can have many editions; SelectEdition picks the one that best matches the lookup criteria (language, format, etc.) instead of assuming the first result is right.
|
||||
openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(olid, _openLibrarySettings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
|
||||
openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(olid, settings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("A book Open Library ID must be a work ID ending in W or an edition ID ending in M.", nameof(bookMetadataLookup));
|
||||
@@ -221,7 +226,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
if (workId is not null)
|
||||
{
|
||||
openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(workId, cancellationToken).ConfigureAwait(false);
|
||||
openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(workId, _openLibrarySettings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
|
||||
openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(workId, settings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
|
||||
}
|
||||
|
||||
if (openLibraryEditionResponse is null && searchResults[0].EditionKeys.Count > 0)
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Provides the runtime settings of the Open Library metadata plugin, overlaying the settings persisted by the host over the configured defaults.
|
||||
/// </summary>
|
||||
internal sealed class OpenLibrarySettingsProvider
|
||||
{
|
||||
private readonly IPluginSettingsStore? _settingsStore;
|
||||
private readonly Guid _pluginId;
|
||||
private readonly OpenLibrarySettingsDto _defaults;
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private OpenLibrarySettingsDto? _runtimeSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OpenLibrarySettingsProvider"/> class.
|
||||
/// </summary>
|
||||
/// <param name="settingsStore">The store of the settings persisted by the host, or <see langword="null"/> when no store is available.</param>
|
||||
/// <param name="pluginId">The unique identifier of the plugin whose settings are read.</param>
|
||||
/// <param name="defaults">The runtime settings with the default values and the optional configuration callback already applied.</param>
|
||||
public OpenLibrarySettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, OpenLibrarySettingsDto defaults)
|
||||
{
|
||||
_settingsStore = settingsStore;
|
||||
_pluginId = pluginId;
|
||||
_defaults = defaults;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The runtime settings of the plugin.</returns>
|
||||
public async Task<OpenLibrarySettingsDto> GetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
OpenLibrarySettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings);
|
||||
if (runtimeSettings is not null)
|
||||
return runtimeSettings;
|
||||
|
||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
runtimeSettings = Volatile.Read(ref _runtimeSettings);
|
||||
if (runtimeSettings is null)
|
||||
{
|
||||
runtimeSettings = Clone(_defaults);
|
||||
if (_settingsStore is not null)
|
||||
{
|
||||
IReadOnlyDictionary<string, string>? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (storedSettings is not null)
|
||||
OpenLibrarySettingsLoader.Apply(runtimeSettings, storedSettings);
|
||||
}
|
||||
|
||||
Volatile.Write(ref _runtimeSettings, runtimeSettings);
|
||||
}
|
||||
|
||||
return runtimeSettings;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a copy of the given runtime settings.
|
||||
/// </summary>
|
||||
/// <param name="source">The runtime settings to copy.</param>
|
||||
/// <returns>A copy of the given runtime settings.</returns>
|
||||
private static OpenLibrarySettingsDto Clone(OpenLibrarySettingsDto source)
|
||||
{
|
||||
return new OpenLibrarySettingsDto
|
||||
{
|
||||
UserAgent = source.UserAgent,
|
||||
ContactEmail = source.ContactEmail,
|
||||
SearchResultLimit = source.SearchResultLimit,
|
||||
WorkEditionLimit = source.WorkEditionLimit,
|
||||
MinimumRequestInterval = source.MinimumRequestInterval
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -25,5 +25,5 @@ public record LibraryFilterDto : BaseFilterDto
|
||||
/// <summary>
|
||||
/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.
|
||||
/// </summary>
|
||||
public bool IgnoreThePrefixForAlphaPicker { get; init; }
|
||||
public bool ShouldIgnoreThePrefixForAlphaPicker { get; init; }
|
||||
}
|
||||
+1
-1
@@ -63,7 +63,7 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets whether this media library should update the metadata of its elements from the web, or not.
|
||||
/// </summary>
|
||||
public bool DownloadMetadataFromWeb { get; init; }
|
||||
public bool CanDownloadMetadataFromWeb { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not.
|
||||
|
||||
+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; }
|
||||
}
|
||||
+6
-1
@@ -35,13 +35,18 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
|
||||
/// </summary>
|
||||
public bool IgnoreThePrefixForAlphaPicker { get; set; }
|
||||
public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the theme data served to this user is cached, or not.
|
||||
/// </summary>
|
||||
public bool IsThemeCachingEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
|
||||
/// </summary>
|
||||
public bool ShouldAggregateMetadataWhenMissing { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
|
||||
+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);
|
||||
}
|
||||
@@ -71,6 +71,11 @@ public interface IUnitOfWork
|
||||
/// </summary>
|
||||
ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the library artwork provider configuration repository.
|
||||
/// </summary>
|
||||
IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the plugin repository.
|
||||
/// </summary>
|
||||
@@ -97,6 +102,11 @@ public interface IUnitOfWork
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
Task SaveChangesAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Detaches all the entities tracked by the unit of work, freeing the memory they occupy.
|
||||
/// </summary>
|
||||
void ClearTrackedEntities();
|
||||
|
||||
/// <summary>
|
||||
/// Begins a new database transaction.
|
||||
/// </summary>
|
||||
|
||||
+5
@@ -21,4 +21,9 @@ public class MediaSettingsDto
|
||||
/// Gets or sets the directory where media library files are stored.
|
||||
/// </summary>
|
||||
public required string LibrariesDirectory { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the directory where the media item files are stored.
|
||||
/// </summary>
|
||||
public required string BooksDirectory { get; init; }
|
||||
}
|
||||
+1
-4
@@ -1,9 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
@@ -27,7 +24,7 @@ public static class AddMediaLibraryRequestMapping
|
||||
request.CoverImage,
|
||||
request.IsEnabled,
|
||||
request.IsLocked,
|
||||
request.DownloadMetadataFromWeb,
|
||||
request.CanDownloadMetadataFromWeb,
|
||||
request.ShouldSaveMetadataInMediaDirectories,
|
||||
request.ShouldSkipUnchangedDirectoriesDuringScan
|
||||
);
|
||||
|
||||
+5
-5
@@ -1,7 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
@@ -29,11 +29,11 @@ public static class LibraryEntityMapping
|
||||
repositoryEntity.UserId,
|
||||
repositoryEntity.Title,
|
||||
repositoryEntity.LibraryType,
|
||||
repositoryEntity.ContentLocations.Select(location => location.Path).ToList(),
|
||||
[.. repositoryEntity.ContentLocations.Select(location => location.Path)],
|
||||
repositoryEntity.CoverImage,
|
||||
repositoryEntity.IsEnabled,
|
||||
repositoryEntity.IsLocked,
|
||||
repositoryEntity.DownloadMetadataFromWeb,
|
||||
repositoryEntity.CanDownloadMetadataFromWeb,
|
||||
repositoryEntity.ShouldSaveMetadataInMediaDirectories,
|
||||
repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
repositoryEntity.CreatedOnUtc,
|
||||
@@ -59,10 +59,10 @@ public static class LibraryEntityMapping
|
||||
repositoryEntity.CoverImage,
|
||||
repositoryEntity.IsEnabled,
|
||||
repositoryEntity.IsLocked,
|
||||
repositoryEntity.DownloadMetadataFromWeb,
|
||||
repositoryEntity.CanDownloadMetadataFromWeb,
|
||||
repositoryEntity.ShouldSaveMetadataInMediaDirectories,
|
||||
repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList()
|
||||
[.. repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -25,14 +25,14 @@ public static class LibraryMapping
|
||||
Title = domainEntity.Title,
|
||||
LibraryType = domainEntity.LibraryType,
|
||||
UserId = domainEntity.UserId.Value,
|
||||
ContentLocations = domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path }).ToList(),
|
||||
ContentLocations = [.. domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path })],
|
||||
CoverImage = domainEntity.CoverImage,
|
||||
IsEnabled = domainEntity.IsEnabled,
|
||||
IsLocked = domainEntity.IsLocked,
|
||||
DownloadMetadataFromWeb = domainEntity.DownloadMetadataFromWeb,
|
||||
CanDownloadMetadataFromWeb = domainEntity.CanDownloadMetadataFromWeb,
|
||||
ShouldSaveMetadataInMediaDirectories = domainEntity.ShouldSaveMetadataInMediaDirectories,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan = domainEntity.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
LibraryScans = domainEntity.ScanIds.Select(scanId => new LibraryScanEntity()
|
||||
LibraryScans = [.. domainEntity.ScanIds.Select(scanId => new LibraryScanEntity()
|
||||
{
|
||||
Id = scanId.Value,
|
||||
LibraryId = domainEntity.Id.Value,
|
||||
@@ -43,7 +43,7 @@ public static class LibraryMapping
|
||||
CreatedBy = default,
|
||||
CreatedOnUtc = default,
|
||||
UpdatedBy = default,
|
||||
}).ToList(),
|
||||
})],
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null,
|
||||
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
@@ -27,7 +26,7 @@ public static class UpdateLibraryRequestMapping
|
||||
request.CoverImage,
|
||||
request.IsEnabled,
|
||||
request.IsLocked,
|
||||
request.DownloadMetadataFromWeb,
|
||||
request.CanDownloadMetadataFromWeb,
|
||||
request.ShouldSaveMetadataInMediaDirectories,
|
||||
request.ShouldSkipUnchangedDirectoriesDuringScan
|
||||
);
|
||||
|
||||
+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
|
||||
);
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -20,7 +20,9 @@ public static class UpdateUserSettingsRequestMapping
|
||||
return new UpdateUserSettingsCommand(
|
||||
request.IsPaginationEnabled,
|
||||
request.ItemsPerPage,
|
||||
request.IgnoreThePrefixForAlphaPicker,
|
||||
request.IsThemeCachingEnabled);
|
||||
request.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
request.IsThemeCachingEnabled,
|
||||
request.ShouldAggregateMetadataWhenMissing
|
||||
);
|
||||
}
|
||||
}
|
||||
+9
-5
@@ -1,7 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects;
|
||||
@@ -28,8 +28,10 @@ public static class UserSettingsEntityMapping
|
||||
UserId.Create(repositoryEntity.UserId),
|
||||
repositoryEntity.IsPaginationEnabled,
|
||||
repositoryEntity.ItemsPerPage,
|
||||
repositoryEntity.IgnoreThePrefixForAlphaPicker,
|
||||
repositoryEntity.IsThemeCachingEnabled);
|
||||
repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
repositoryEntity.IsThemeCachingEnabled,
|
||||
repositoryEntity.ShouldAggregateMetadataWhenMissing
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -43,7 +45,9 @@ public static class UserSettingsEntityMapping
|
||||
repositoryEntity.UserId,
|
||||
repositoryEntity.IsPaginationEnabled,
|
||||
repositoryEntity.ItemsPerPage,
|
||||
repositoryEntity.IgnoreThePrefixForAlphaPicker,
|
||||
repositoryEntity.IsThemeCachingEnabled);
|
||||
repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
repositoryEntity.IsThemeCachingEnabled,
|
||||
repositoryEntity.ShouldAggregateMetadataWhenMissing
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,9 @@ public static class UserSettingsMapping
|
||||
UserId = domainEntity.UserId.Value,
|
||||
IsPaginationEnabled = domainEntity.IsPaginationEnabled,
|
||||
ItemsPerPage = domainEntity.ItemsPerPage,
|
||||
IgnoreThePrefixForAlphaPicker = domainEntity.IgnoreThePrefixForAlphaPicker,
|
||||
IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled
|
||||
ShouldIgnoreThePrefixForAlphaPicker = domainEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled,
|
||||
ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing
|
||||
};
|
||||
}
|
||||
|
||||
@@ -40,7 +41,9 @@ public static class UserSettingsMapping
|
||||
domainEntity.UserId.Value,
|
||||
domainEntity.IsPaginationEnabled,
|
||||
domainEntity.ItemsPerPage,
|
||||
domainEntity.IgnoreThePrefixForAlphaPicker,
|
||||
domainEntity.IsThemeCachingEnabled);
|
||||
domainEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
domainEntity.IsThemeCachingEnabled,
|
||||
domainEntity.ShouldAggregateMetadataWhenMissing
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
+2
-3
@@ -1,6 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
@@ -15,7 +14,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
|
||||
/// <param name="CoverImage">The path of the image file used as the cover for the library.</param>
|
||||
/// <param name="IsEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed.</param>
|
||||
/// <param name="IsLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
|
||||
/// <param name="DownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="CanDownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="ShouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="ShouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
@@ -26,7 +25,7 @@ public record AddLibraryCommand(
|
||||
string? CoverImage,
|
||||
bool IsEnabled,
|
||||
bool IsLocked,
|
||||
bool DownloadMetadataFromWeb,
|
||||
bool CanDownloadMetadataFromWeb,
|
||||
bool ShouldSaveMetadataInMediaDirectories,
|
||||
bool ShouldSkipUnchangedDirectoriesDuringScan
|
||||
) : ICommand;
|
||||
+5
-6
@@ -1,8 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
@@ -10,14 +8,15 @@ using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
@@ -113,7 +112,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
|
||||
command.CoverImage,
|
||||
command.IsEnabled,
|
||||
command.IsLocked,
|
||||
command.DownloadMetadataFromWeb,
|
||||
command.CanDownloadMetadataFromWeb,
|
||||
command.ShouldSaveMetadataInMediaDirectories,
|
||||
command.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
[]
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary
|
||||
/// <param name="CoverImage">The path of the image file used as the cover for the library.</param>
|
||||
/// <param name="IsEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed.</param>
|
||||
/// <param name="IsLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
|
||||
/// <param name="DownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="CanDownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="ShouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="ShouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
@@ -30,7 +30,7 @@ public record UpdateLibraryCommand(
|
||||
string? CoverImage,
|
||||
bool IsEnabled,
|
||||
bool IsLocked,
|
||||
bool DownloadMetadataFromWeb,
|
||||
bool CanDownloadMetadataFromWeb,
|
||||
bool ShouldSaveMetadataInMediaDirectories,
|
||||
bool ShouldSkipUnchangedDirectoriesDuringScan
|
||||
) : ICommand;
|
||||
+6
-7
@@ -1,8 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
@@ -11,16 +9,17 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -127,10 +126,10 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
||||
command.CoverImage,
|
||||
command.IsEnabled,
|
||||
command.IsLocked,
|
||||
command.DownloadMetadataFromWeb,
|
||||
command.CanDownloadMetadataFromWeb,
|
||||
command.ShouldSaveMetadataInMediaDirectories,
|
||||
command.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList()
|
||||
[.. getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))]
|
||||
);
|
||||
if (createLibraryResult.IsFailure)
|
||||
return createLibraryResult.Errors;
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibrarySc
|
||||
|
||||
// start the media library scan
|
||||
Result<Success> startScanResult = await _mediaLibraryScanningService.StartScanAsync(
|
||||
libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, getLibraryScanResult.Value.Library.DownloadMetadataFromWeb, cancellationToken).ConfigureAwait(false);
|
||||
libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, cancellationToken).ConfigureAwait(false);
|
||||
if (startScanResult.IsFailure)
|
||||
throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors);
|
||||
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+24
-3
@@ -1,15 +1,18 @@
|
||||
#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 Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
|
||||
@@ -20,15 +23,21 @@ namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProvide
|
||||
public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler<ReorderLibraryMetadataProvidersCommand, Result<Success>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<ReorderLibraryMetadataProvidersCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersCommandHandler"/> 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 ReorderLibraryMetadataProvidersCommandHandler(IUnitOfWork unitOfWork, IValidator<ReorderLibraryMetadataProvidersCommand> validator)
|
||||
public ReorderLibraryMetadataProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<ReorderLibraryMetadataProvidersCommand> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
@@ -47,6 +56,18 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler<Reo
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// admins can reorder the metadata providers of any library; for everyone else, only their own libraries
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsFailure)
|
||||
return getConfigurationsResult.Errors;
|
||||
|
||||
+3
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
|
||||
@@ -18,6 +19,8 @@ public class ReorderLibraryMetadataProvidersCommandValidator : AbstractValidator
|
||||
{
|
||||
RuleFor(command => command.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty)
|
||||
.Must(id => id != Guid.Empty)
|
||||
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PluginIds)
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+24
-3
@@ -1,15 +1,18 @@
|
||||
#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 Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
|
||||
@@ -20,15 +23,21 @@ namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEna
|
||||
public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler<SetLibraryMetadataProviderEnabledCommand, Result<Success>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<SetLibraryMetadataProviderEnabledCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledCommandHandler"/> 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 SetLibraryMetadataProviderEnabledCommandHandler(IUnitOfWork unitOfWork, IValidator<SetLibraryMetadataProviderEnabledCommand> validator)
|
||||
public SetLibraryMetadataProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<SetLibraryMetadataProviderEnabledCommand> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
@@ -47,6 +56,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler<S
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// admins can configure the metadata providers of any library; for everyone else, only their own libraries
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryMetadataProviderConfigurationEntity?> getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationResult.IsFailure)
|
||||
return getConfigurationResult.Errors;
|
||||
|
||||
+5
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
|
||||
@@ -18,10 +19,14 @@ public class SetLibraryMetadataProviderEnabledCommandValidator : AbstractValidat
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
+3
@@ -2,6 +2,7 @@
|
||||
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.UpdatePluginSettings;
|
||||
@@ -18,6 +19,8 @@ public class UpdatePluginSettingsCommandValidator : AbstractValidator<UpdatePlug
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
+32
-3
@@ -1,16 +1,20 @@
|
||||
#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 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.GetLibraryMetadataProviders;
|
||||
@@ -21,14 +25,23 @@ namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders;
|
||||
public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler<GetLibraryMetadataProvidersQuery, Result<IReadOnlyList<LibraryMetadataProviderResponse>>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<GetLibraryMetadataProvidersQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersQueryHandler"/> 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>
|
||||
public GetLibraryMetadataProvidersQueryHandler(IUnitOfWork unitOfWork)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetLibraryMetadataProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator<GetLibraryMetadataProvidersQuery> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -41,6 +54,22 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler<GetLibraryM
|
||||
/// </returns>
|
||||
public async Task<Result<IReadOnlyList<LibraryMetadataProviderResponse>>> HandleAsync(GetLibraryMetadataProvidersQuery 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 metadata 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<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsFailure)
|
||||
return getConfigurationsResult.Errors;
|
||||
|
||||
+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.GetLibraryMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetLibraryMetadataProvidersQuery"/>.
|
||||
/// </summary>
|
||||
public class GetLibraryMetadataProvidersQueryValidator : AbstractValidator<GetLibraryMetadataProvidersQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryMetadataProvidersQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty)
|
||||
.Must(id => id != Guid.Empty)
|
||||
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+10
-3
@@ -1,13 +1,13 @@
|
||||
#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.Plugins;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Plugins;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -24,16 +24,19 @@ public class GetPluginSettingsQueryHandler : IQueryHandler<GetPluginSettingsQuer
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IPluginManager _pluginManager;
|
||||
private readonly IValidator<GetPluginSettingsQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginSettingsQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="pluginManager">Injected manager of the plugins loaded by the host application.</param>
|
||||
public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager)
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager, IValidator<GetPluginSettingsQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_pluginManager = pluginManager;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -46,6 +49,10 @@ public class GetPluginSettingsQueryHandler : IQueryHandler<GetPluginSettingsQuer
|
||||
/// </returns>
|
||||
public async Task<Result<PluginSettingsResponse>> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
Result<PluginEntity?> getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (getPluginResult.IsFailure)
|
||||
return getPluginResult.Errors;
|
||||
|
||||
+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.GetPluginSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetPluginSettingsQuery"/>.
|
||||
/// </summary>
|
||||
public class GetPluginSettingsQueryValidator : AbstractValidator<GetPluginSettingsQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginSettingsQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetPluginSettingsQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.PluginId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.PluginIdCannotBeEmpty)
|
||||
.Must(id => id != Guid.Empty)
|
||||
.WithError(Errors.Plugins.PluginIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -9,11 +9,13 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe
|
||||
/// </summary>
|
||||
/// <param name="IsPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="ItemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="IgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="ShouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
public record UpdateUserSettingsCommand(
|
||||
bool IsPaginationEnabled,
|
||||
int ItemsPerPage,
|
||||
bool IgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled
|
||||
bool ShouldIgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled,
|
||||
bool ShouldAggregateMetadataWhenMissing
|
||||
) : ICommand;
|
||||
+7
-6
@@ -1,13 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.UsersManagement.Users;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
|
||||
using System;
|
||||
@@ -72,8 +71,9 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
UserId.Create(userId),
|
||||
command.IsPaginationEnabled,
|
||||
command.ItemsPerPage,
|
||||
command.IgnoreThePrefixForAlphaPicker,
|
||||
command.IsThemeCachingEnabled);
|
||||
command.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
command.IsThemeCachingEnabled,
|
||||
command.ShouldAggregateMetadataWhenMissing);
|
||||
if (createSettingsResult.IsFailure)
|
||||
return createSettingsResult.Errors;
|
||||
|
||||
@@ -91,8 +91,9 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
Result<Updated> updateSettingsResult = toDomainEntityResult.Value.UpdateSettings(
|
||||
command.IsPaginationEnabled,
|
||||
command.ItemsPerPage,
|
||||
command.IgnoreThePrefixForAlphaPicker,
|
||||
command.IsThemeCachingEnabled);
|
||||
command.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
command.IsThemeCachingEnabled,
|
||||
command.ShouldAggregateMetadataWhenMissing);
|
||||
if (updateSettingsResult.IsFailure)
|
||||
return updateSettingsResult.Errors;
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -13,7 +13,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
/// <param name="CoverImage">The path of the image file used as the cover for the library. Optional.</param>
|
||||
/// <param name="IsEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.</param>
|
||||
/// <param name="IsLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.</param>
|
||||
/// <param name="DownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not. Optional.</param>
|
||||
/// <param name="CanDownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not. Optional.</param>
|
||||
/// <param name="ShouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.</param>
|
||||
/// <param name="ShouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
@@ -24,7 +24,7 @@ public record AddLibraryRequest(
|
||||
string? CoverImage,
|
||||
bool IsEnabled,
|
||||
bool IsLocked,
|
||||
bool DownloadMetadataFromWeb,
|
||||
bool CanDownloadMetadataFromWeb,
|
||||
bool ShouldSaveMetadataInMediaDirectories,
|
||||
bool ShouldSkipUnchangedDirectoriesDuringScan
|
||||
);
|
||||
@@ -1,8 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
@@ -18,7 +16,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
/// <param name="CoverImage">The path of the image file used as the cover for the library. Optional.</param>
|
||||
/// <param name="IsEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.</param>
|
||||
/// <param name="IsLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.</param>
|
||||
/// <param name="DownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not. Optional.</param>
|
||||
/// <param name="CanDownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not. Optional.</param>
|
||||
/// <param name="ShouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.
|
||||
/// <param name="ShouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
@@ -31,7 +29,7 @@ public record class UpdateLibraryRequest(
|
||||
string? CoverImage,
|
||||
bool IsEnabled,
|
||||
bool IsLocked,
|
||||
bool DownloadMetadataFromWeb,
|
||||
bool CanDownloadMetadataFromWeb,
|
||||
bool ShouldSaveMetadataInMediaDirectories,
|
||||
bool ShouldSkipUnchangedDirectoriesDuringScan
|
||||
);
|
||||
+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
|
||||
);
|
||||
@@ -9,12 +9,14 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
/// </summary>
|
||||
/// <param name="IsPaginationEnabled">Whether pagination is enabled for the user, or not. Required.</param>
|
||||
/// <param name="ItemsPerPage">The number of library items displayed per page when pagination is enabled. Required.</param>
|
||||
/// <param name="IgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required.</param>
|
||||
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required.</param>
|
||||
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not. Required.</param>
|
||||
/// <param name="ShouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. Required.</param>
|
||||
[DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")]
|
||||
public sealed record UpdateUserSettingsRequest(
|
||||
bool IsPaginationEnabled,
|
||||
int ItemsPerPage,
|
||||
bool IgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled
|
||||
bool ShouldIgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled,
|
||||
bool ShouldAggregateMetadataWhenMissing
|
||||
);
|
||||
@@ -16,6 +16,11 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
/// <param name="LibraryType">The type of the media library.</param>
|
||||
/// <param name="ContentLocations">The file system paths of the directories where the media library elements are located.</param>
|
||||
/// <param name="CoverImage">The path of the image file used as the cover for the library.</param>
|
||||
/// <param name="IsEnabled">Whether the media library is enabled or not. A disabled media library is never shown or changed.</param>
|
||||
/// <param name="IsLocked">Whether the media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
|
||||
/// <param name="CanDownloadMetadataFromWeb">Whether the media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="ShouldSaveMetadataInMediaDirectories">Whether the media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="ShouldSkipUnchangedDirectoriesDuringScan">Whether the media library should skip the directories whose contents have not changed since the last scan, during the scan.</param>
|
||||
/// <param name="CreatedOnUtc">The date and time when the library was created.</param>
|
||||
/// <param name="UpdatedOnUtc">The optional date and time when the library was updated.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
@@ -28,7 +33,7 @@ public record LibraryResponse(
|
||||
string? CoverImage,
|
||||
bool IsEnabled,
|
||||
bool IsLocked,
|
||||
bool DownloadMetadataFromWeb,
|
||||
bool CanDownloadMetadataFromWeb,
|
||||
bool ShouldSaveMetadataInMediaDirectories,
|
||||
bool ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
DateTime CreatedOnUtc,
|
||||
|
||||
+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
|
||||
);
|
||||
@@ -11,13 +11,15 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
/// <param name="UserId">The unique identifier of the user that owns these settings.</param>
|
||||
/// <param name="IsPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
|
||||
/// <param name="ItemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
|
||||
/// <param name="IgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="ShouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
[DebuggerDisplay("UserId: {UserId}")]
|
||||
public sealed record UserSettingsResponse(
|
||||
Guid UserId,
|
||||
bool IsPaginationEnabled,
|
||||
int ItemsPerPage,
|
||||
bool IgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled
|
||||
bool ShouldIgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled,
|
||||
bool ShouldAggregateMetadataWhenMissing
|
||||
);
|
||||
+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 });
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
||||
builder.Property(library => library.IsLocked)
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.Property(library => library.DownloadMetadataFromWeb)
|
||||
builder.Property(library => library.CanDownloadMetadataFromWeb)
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Common.Configuration;
|
||||
@@ -43,10 +42,14 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEn
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
builder.Property(settings => settings.IgnoreThePrefixForAlphaPicker)
|
||||
builder.Property(settings => settings.ShouldIgnoreThePrefixForAlphaPicker)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
builder.Property(settings => settings.ShouldAggregateMetadataWhenMissing)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(10);
|
||||
|
||||
builder.Property(settings => settings.IsThemeCachingEnabled)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(9);
|
||||
|
||||
+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);
|
||||
|
||||
@@ -132,7 +132,7 @@ internal sealed class BookRepository : IBookRepository
|
||||
booksQuery = booksQuery.Where(filterSpecification.ToExpression());
|
||||
|
||||
// apply sorting based on the specified sortBy and sortOrder parameters
|
||||
booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.IgnoreThePrefixForAlphaPicker);
|
||||
booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
|
||||
// if no pagination was requested, return all the books of the library
|
||||
if (paginationData is null)
|
||||
@@ -261,8 +261,8 @@ internal sealed class BookRepository : IBookRepository
|
||||
/// <param name="booksQuery">The query to sort.</param>
|
||||
/// <param name="sortBy">The field to sort by (case-insensitive).</param>
|
||||
/// <param name="sortOrder">The direction of the sorting.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not.</param>
|
||||
private static IOrderedQueryable<BookEntity> ApplySorting(IQueryable<BookEntity> booksQuery, string? sortBy, SortOrder sortOrder, bool ignoreThePrefixForAlphaPicker)
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not.</param>
|
||||
private static IOrderedQueryable<BookEntity> ApplySorting(IQueryable<BookEntity> booksQuery, string? sortBy, SortOrder sortOrder, bool shouldIgnoreThePrefixForAlphaPicker)
|
||||
{
|
||||
return sortBy?.ToLower() switch
|
||||
{
|
||||
@@ -276,8 +276,8 @@ internal sealed class BookRepository : IBookRepository
|
||||
? booksQuery.OrderByDescending(book => book.MetadataProvider)
|
||||
: booksQuery.OrderBy(book => book.MetadataProvider),
|
||||
_ => sortOrder == SortOrder.Descending
|
||||
? booksQuery.OrderByDescending(BuildTitleSortKey(ignoreThePrefixForAlphaPicker))
|
||||
: booksQuery.OrderBy(BuildTitleSortKey(ignoreThePrefixForAlphaPicker)),
|
||||
? booksQuery.OrderByDescending(BuildTitleSortKey(shouldIgnoreThePrefixForAlphaPicker))
|
||||
: booksQuery.OrderBy(BuildTitleSortKey(shouldIgnoreThePrefixForAlphaPicker)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -286,9 +286,9 @@ internal sealed class BookRepository : IBookRepository
|
||||
/// the title lowercased, falling back to the original title when the title is <see langword="null"/> or empty, and optionally
|
||||
/// stripped of a leading "the " prefix.
|
||||
/// </summary>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not.</param>
|
||||
/// <returns>An expression that evaluates to the title sort key of a book.</returns>
|
||||
private static Expression<Func<BookEntity, string>> BuildTitleSortKey(bool ignoreThePrefixForAlphaPicker)
|
||||
private static Expression<Func<BookEntity, string>> BuildTitleSortKey(bool shouldIgnoreThePrefixForAlphaPicker)
|
||||
{
|
||||
ParameterExpression book = Expression.Parameter(typeof(BookEntity), "book");
|
||||
|
||||
@@ -306,7 +306,7 @@ internal sealed class BookRepository : IBookRepository
|
||||
|
||||
// when ignoring the "The " prefix, strip a leading "the " from the lowercased title
|
||||
Expression effectiveTitle = lowerTitle;
|
||||
if (ignoreThePrefixForAlphaPicker)
|
||||
if (shouldIgnoreThePrefixForAlphaPicker)
|
||||
{
|
||||
MethodCallExpression startsWithThe = Expression.Call(lowerTitle, s_startsWithMethod, Expression.Constant("the "));
|
||||
MethodCallExpression strippedTitle = Expression.Call(lowerTitle, s_substringMethod, Expression.Constant(4));
|
||||
@@ -332,7 +332,7 @@ internal sealed class BookRepository : IBookRepository
|
||||
// include the alpha key filter, if provided
|
||||
if (libraryFilter.FilterAlphaKey is not null)
|
||||
{
|
||||
BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.IgnoreThePrefixForAlphaPicker);
|
||||
BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
filterSpecification = filterSpecification is null
|
||||
? alphaFilterSpecification
|
||||
: filterSpecification.And(alphaFilterSpecification);
|
||||
|
||||
+5
-5
@@ -23,17 +23,17 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification<BookEnt
|
||||
.GetMethod(nameof(SqliteDbFunctionsExtensions.Glob), [typeof(DbFunctions), typeof(string), typeof(string)])!;
|
||||
|
||||
private readonly string? _filterAlphaKey;
|
||||
private readonly bool _ignoreThePrefixForAlphaPicker;
|
||||
private readonly bool _shouldIgnoreThePrefixForAlphaPicker;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookAlphaFilterSpecification"/> class.
|
||||
/// </summary>
|
||||
/// <param name="filterAlphaKey">The alpha key to filter by. A single ASCII letter, <see cref="LibraryItemAlphaKeys.NUMBER"/>, or <see cref="LibraryItemAlphaKeys.SYMBOL"/>.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||
public BookAlphaFilterSpecification(string? filterAlphaKey, bool ignoreThePrefixForAlphaPicker)
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||
public BookAlphaFilterSpecification(string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker)
|
||||
{
|
||||
_filterAlphaKey = filterAlphaKey;
|
||||
_ignoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker;
|
||||
_shouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -82,7 +82,7 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification<BookEnt
|
||||
|
||||
// when ignoring the "The " prefix, strip a leading "the " from the lowercased title
|
||||
Expression effectiveTitle = lowerTitle;
|
||||
if (_ignoreThePrefixForAlphaPicker)
|
||||
if (_shouldIgnoreThePrefixForAlphaPicker)
|
||||
{
|
||||
MethodCallExpression startsWithThe = Expression.Call(lowerTitle, s_startsWithMethod, Expression.Constant("the "));
|
||||
MethodCallExpression strippedTitle = Expression.Call(lowerTitle, s_substringMethod, Expression.Constant(4));
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ public class LuminaDbContext : DbContext
|
||||
public virtual DbSet<RolePermissionEntity> RolePermissions { get; set; } = null!;
|
||||
public virtual DbSet<PluginEntity> Plugins { get; set; } = null!;
|
||||
public virtual DbSet<LibraryMetadataProviderConfigurationEntity> LibraryMetadataProviderConfigurations { get; set; } = null!;
|
||||
public virtual DbSet<LibraryArtworkProviderConfigurationEntity> LibraryArtworkProviderConfigurations { get; set; } = null!;
|
||||
public virtual DbSet<ThemeEntity> Themes { get; set; } = null!;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -39,6 +39,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
private ILibraryScanSnapshotRepository? _libraryScanSnapshotRepository;
|
||||
private ILibraryScanStagingResultsRepository? _libraryScanStagingResultsRepository;
|
||||
private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository;
|
||||
private IArtworkProviderConfigurationRepository? _artworkProviderConfigurationRepository;
|
||||
private IPluginRepository? _pluginRepository;
|
||||
private IThemeRepository? _themeRepository;
|
||||
private IUserRepository? _userRepository;
|
||||
@@ -176,6 +177,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the library artwork provider configuration repository.
|
||||
/// </summary>
|
||||
public IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_artworkProviderConfigurationRepository ??= new ArtworkProviderConfigurationRepository(_luminaDbContext);
|
||||
return _artworkProviderConfigurationRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the plugin repository.
|
||||
/// </summary>
|
||||
@@ -242,6 +255,14 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detaches all the entities tracked by the unit of work, freeing the memory they occupy.
|
||||
/// </summary>
|
||||
public void ClearTrackedEntities()
|
||||
{
|
||||
_luminaDbContext.ChangeTracker.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Begins a new database transaction.
|
||||
/// </summary>
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -35,16 +35,16 @@ public static class DomainLayerServices
|
||||
services.AddScoped<IDirectoryProviderService, DirectoryProviderService>();
|
||||
services.AddScoped<IFileProviderService, FileProviderService>();
|
||||
services.AddScoped<IThumbnailService, ThumbnailService>();
|
||||
services.AddScoped<IPathService, PathService>();
|
||||
services.AddSingleton<IPathService, PathService>();
|
||||
services.AddScoped<IFileTypeService, FileTypeService>();
|
||||
services.AddScoped<IEnvironmentContext, EnvironmentContext>();
|
||||
services.AddScoped<IPlatformContextFactory, PlatformContextFactory>();
|
||||
services.AddScoped<IUnixPlatformContext, UnixPlatformContext>();
|
||||
services.AddScoped<IWindowsPlatformContext, WindowsPlatformContext>();
|
||||
services.AddScoped<IPlatformContextManager, PlatformContextManager>();
|
||||
services.AddScoped<IUnixPathStrategy, UnixPathStrategy>();
|
||||
services.AddScoped<IWindowsPathStrategy, WindowsPathStrategy>();
|
||||
services.AddScoped<IOperatingSystemInfo, OperatingSystemInfo>();
|
||||
services.AddSingleton<IPlatformContextFactory, PlatformContextFactory>();
|
||||
services.AddSingleton<IUnixPlatformContext, UnixPlatformContext>();
|
||||
services.AddSingleton<IWindowsPlatformContext, WindowsPlatformContext>();
|
||||
services.AddSingleton<IPlatformContextManager, PlatformContextManager>();
|
||||
services.AddSingleton<IUnixPathStrategy, UnixPathStrategy>();
|
||||
services.AddSingleton<IWindowsPathStrategy, WindowsPathStrategy>();
|
||||
services.AddSingleton<IOperatingSystemInfo, OperatingSystemInfo>();
|
||||
services.AddScoped<IFileSystemStructureSeedService, FileSystemStructureSeedService>();
|
||||
services.AddScoped<IMediaLibraryScanJobFactory, MediaLibraryScanJobFactory>();
|
||||
services.AddScoped<IMediaLibraryScanningService, MediaLibraryScanningService>();
|
||||
|
||||
@@ -29,5 +29,6 @@ public static partial class Errors
|
||||
public static Error FileAlreadyExists => Error.Conflict(description: nameof(FileAlreadyExists));
|
||||
public static Error DirectoryNotFound => Error.NotFound(description: nameof(DirectoryNotFound));
|
||||
public static Error DirectoryAlreadyExists => Error.Conflict(description: nameof(DirectoryAlreadyExists));
|
||||
public static Error FileTooLarge => Error.Validation(description: nameof(FileTooLarge));
|
||||
}
|
||||
}
|
||||
+30
-13
@@ -1,6 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
#endregion
|
||||
@@ -38,23 +37,41 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService
|
||||
if (rootPathIdResult.IsFailure)
|
||||
return rootPathIdResult.Errors;
|
||||
|
||||
// create the libraries directory
|
||||
Result<string> librariesPathResult = _pathService.CombinePath(rootPath, "libraries");
|
||||
if (librariesPathResult.IsFailure)
|
||||
return librariesPathResult.Errors;
|
||||
Result<Created> createLibrariesDirectoryResult = EnsureDirectory(rootPathIdResult.Value, "libraries");
|
||||
if (createLibrariesDirectoryResult.IsFailure)
|
||||
return createLibrariesDirectoryResult.Errors;
|
||||
|
||||
Result<FileSystemPathId> libraryPathIdResult = FileSystemPathId.Create(librariesPathResult.Value);
|
||||
if (libraryPathIdResult.IsFailure)
|
||||
return libraryPathIdResult.Errors;
|
||||
Result<Created> createBooksDirectoryResult = EnsureDirectory(rootPathIdResult.Value, "books");
|
||||
if (createBooksDirectoryResult.IsFailure)
|
||||
return createBooksDirectoryResult.Errors;
|
||||
|
||||
Result<bool> librariesDirectoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(libraryPathIdResult.Value);
|
||||
if (librariesDirectoryExistsResult.IsFailure)
|
||||
return librariesDirectoryExistsResult.Errors;
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the directory with the provided <paramref name="directoryName"/> under the <paramref name="rootPathId"/>, when it does not already exist.
|
||||
/// </summary>
|
||||
/// <param name="rootPathId">The id of the root path under which the directory is created.</param>
|
||||
/// <param name="directoryName">The name of the directory to create.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private Result<Created> EnsureDirectory(FileSystemPathId rootPathId, string directoryName)
|
||||
{
|
||||
Result<string> directoryPathResult = _pathService.CombinePath(rootPathId.Path, directoryName);
|
||||
if (directoryPathResult.IsFailure)
|
||||
return directoryPathResult.Errors;
|
||||
|
||||
Result<FileSystemPathId> directoryPathIdResult = FileSystemPathId.Create(directoryPathResult.Value);
|
||||
if (directoryPathIdResult.IsFailure)
|
||||
return directoryPathIdResult.Errors;
|
||||
|
||||
Result<bool> directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value);
|
||||
if (directoryExistsResult.IsFailure)
|
||||
return directoryExistsResult.Errors;
|
||||
|
||||
// only create it if it doesn't already exist
|
||||
if (!librariesDirectoryExistsResult.Value)
|
||||
if (!directoryExistsResult.Value)
|
||||
{
|
||||
Result<FileSystemPathId> createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathIdResult.Value, "libraries");
|
||||
Result<FileSystemPathId> createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathId, directoryName);
|
||||
if (createDirectoryResult.IsFailure)
|
||||
return createDirectoryResult.Errors;
|
||||
}
|
||||
|
||||
+7
@@ -59,6 +59,13 @@ public interface IPathService
|
||||
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
|
||||
char[] GetInvalidPathCharsForPlatform();
|
||||
|
||||
/// <summary>
|
||||
/// Sanitizes a human-readable <paramref name="name"/> into a safe path segment.
|
||||
/// </summary>
|
||||
/// <param name="name">The human-readable name to sanitize.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the sanitized path segment, or an error.</returns>
|
||||
Result<PathSegment> SanitizeSegment(string name);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the root portion of the given path.
|
||||
/// </summary>
|
||||
|
||||
Loaded 100 of 706 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user