diff --git a/Directory.Packages.props b/Directory.Packages.props
index f98f56c2..7f669fa1 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -33,6 +33,7 @@
+
diff --git a/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs b/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs
new file mode 100644
index 00000000..20b7b97f
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs
@@ -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;
+
+///
+/// Provides extension methods for registering the Calibre metadata and artwork providers.
+///
+internal static class CalibreServices
+{
+ ///
+ /// Registers the Calibre book metadata provider, associated with the plugin that provides it.
+ ///
+ /// The service collection to register the services into.
+ /// The unique identifier of the plugin that provides the metadata.
+ /// The service collection, for chaining.
+ 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(pluginId);
+
+ return services;
+ }
+
+ ///
+ /// Registers the Calibre artwork provider, associated with the plugin that provides it.
+ ///
+ /// The service collection to register the services into.
+ /// The unique identifier of the plugin that provides the artwork.
+ /// The service collection, for chaining.
+ 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(pluginId);
+
+ return services;
+ }
+}
diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs
new file mode 100644
index 00000000..fb72a220
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs
@@ -0,0 +1,17 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
+
+///
+/// Data transfer object for a contributor of a book read from an OPF file.
+///
+/// The name of the contributor.
+/// The role code of the contributor, for example bkp for the book producer.
+[DebuggerDisplay("Name: {Name}")]
+internal sealed record OpfContributorDto(
+ string Name,
+ string? Role
+);
diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs
new file mode 100644
index 00000000..2f79c0f8
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs
@@ -0,0 +1,17 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
+
+///
+/// Data transfer object for a creator of a book read from an OPF file.
+///
+/// The name of the creator.
+/// The role code of the creator, for example aut for author.
+[DebuggerDisplay("Name: {Name}")]
+internal sealed record OpfCreatorDto(
+ string Name,
+ string? Role
+);
diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs
new file mode 100644
index 00000000..a49ca5e6
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs
@@ -0,0 +1,79 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
+
+///
+/// Data transfer object for the metadata read from a Calibre OPF file.
+///
+[DebuggerDisplay("Title: {Title}")]
+internal sealed class OpfDocumentDto
+{
+ ///
+ /// Gets or sets the title of the book.
+ ///
+ public string? Title { get; set; }
+
+ ///
+ /// Gets or sets the description of the book, in HTML format.
+ ///
+ public string? Description { get; set; }
+
+ ///
+ /// Gets or sets the publisher of the book.
+ ///
+ public string? Publisher { get; set; }
+
+ ///
+ /// Gets or sets the publication date of the book.
+ ///
+ public DateTimeOffset? PublishDate { get; set; }
+
+ ///
+ /// Gets or sets the language code of the book.
+ ///
+ public string? LanguageCode { get; set; }
+
+ ///
+ /// Gets or sets the name of the series the book belongs to, if applicable.
+ ///
+ public string? Series { get; set; }
+
+ ///
+ /// Gets or sets the index of the book within its series, if applicable.
+ ///
+ public double? SeriesIndex { get; set; }
+
+ ///
+ /// Gets or sets the personal rating of the book, on a scale of 0 to 10.
+ ///
+ public int? Rating { get; set; }
+
+ ///
+ /// Gets or sets the href of the cover image, relative to the directory of the book.
+ ///
+ public string? CoverHref { get; set; }
+
+ ///
+ /// Gets the creators of the book.
+ ///
+ public List Creators { get; } = [];
+
+ ///
+ /// Gets the contributors of the book.
+ ///
+ public List Contributors { get; } = [];
+
+ ///
+ /// Gets the identifiers of the book, with their schemes.
+ ///
+ public List Identifiers { get; } = [];
+
+ ///
+ /// Gets the subjects of the book, used as tags.
+ ///
+ public List Subjects { get; } = [];
+}
diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs
new file mode 100644
index 00000000..1d10d643
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs
@@ -0,0 +1,17 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
+
+///
+/// Data transfer object for an identifier of a book read from an OPF file, with its scheme.
+///
+/// The scheme of the identifier, for example ISBN or GOODREADS.
+/// The value of the identifier.
+[DebuggerDisplay("{Scheme}: {Value}")]
+internal sealed record OpfIdentifierDto(
+ string Scheme,
+ string Value
+);
diff --git a/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs b/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs
new file mode 100644
index 00000000..e3ffd5e3
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs
@@ -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;
+
+///
+/// Provides the cover of a book from the cover reference of the Calibre OPF file located next to the book file.
+///
+internal sealed class CalibreArtworkProvider : IArtworkProvider
+{
+ ///
+ /// Gets the display name of the artwork provider.
+ ///
+ public string Name => "Calibre";
+
+ ///
+ /// Gets the media library types this artwork provider supports.
+ ///
+ public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook];
+
+ ///
+ /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
+ ///
+ public bool RequiresWebAccess => false;
+
+ ///
+ /// Gets the cover of the book described by .
+ ///
+ /// The lookup describing the book to get the cover for.
+ /// Cancellation token that can be used to stop the execution.
+ /// The cover of the book, or when no cover was found.
+ public Task GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrWhiteSpace(lookup.Path))
+ return Task.FromResult(null);
+
+ string bookDirectory = Path.GetDirectoryName(lookup.Path) ?? string.Empty;
+ string opfFilePath = Path.Combine(bookDirectory, "metadata.opf");
+ if (!File.Exists(opfFilePath))
+ return Task.FromResult(null);
+
+ OpfDocumentDto document = OpfReader.Read(opfFilePath);
+ if (string.IsNullOrWhiteSpace(document.CoverHref))
+ return Task.FromResult(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(null);
+
+ string coverFilePath = Path.Combine(bookDirectory, coverFileName);
+ if (!File.Exists(coverFilePath))
+ return Task.FromResult(null);
+
+ return Task.FromResult(new ArtworkDto(LocalPath: coverFilePath, RemoteUrl: null));
+ }
+}
diff --git a/plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs b/plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs
new file mode 100644
index 00000000..950ddcab
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs
@@ -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;
+
+///
+/// Provides book metadata from Calibre OPF files by resolving lookups into book metadata DTOs.
+///
+internal sealed class CalibreBookMetadataProvider : IMetadataProvider
+{
+ ///
+ /// Gets the display name of the metadata provider.
+ ///
+ public string Name => "Calibre";
+
+ ///
+ /// Gets the media library types this metadata provider supports.
+ ///
+ public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook];
+
+ ///
+ /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
+ ///
+ public bool RequiresWebAccess => false;
+
+ ///
+ /// Searches for the metadata of the media item described by .
+ ///
+ /// The lookup describing the media item to search for.
+ /// Cancellation token that can be used to stop the execution.
+ /// The collection of metadata candidates found for the media item.
+ public Task> GetSearchResultsAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
+ {
+ BookMetadataDto? metadata = GetMetadata(bookMetadataLookup);
+ return Task.FromResult>(metadata is null ? [] : [metadata]);
+ }
+
+ ///
+ /// Gets the metadata of the media item described by .
+ ///
+ /// The lookup describing the media item to get the metadata for.
+ /// Cancellation token that can be used to stop the execution.
+ /// The metadata of the media item, or when no metadata was found.
+ public Task GetMetadataAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
+ {
+ return Task.FromResult(GetMetadata(bookMetadataLookup));
+ }
+
+ ///
+ /// Reads the metadata of the book from the OPF file located next to the book file described by .
+ ///
+ /// The lookup describing the book to get the metadata for.
+ /// The metadata of the book, or when no OPF file was found.
+ 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));
+ }
+}
diff --git a/plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs b/plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs
new file mode 100644
index 00000000..10138ea1
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs
@@ -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;
+
+///
+/// Plugin that provides book metadata and book covers from Calibre OPF files.
+///
+public sealed class CalibrePlugin : IPlugin, IPluginServiceRegistrator
+{
+ ///
+ /// The unique identifier of the plugin.
+ ///
+ public static readonly Guid s_pluginId = new("a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d");
+
+ ///
+ /// Gets the unique identifier of the plugin.
+ ///
+ public Guid Id => s_pluginId;
+
+ ///
+ /// Gets the display name of the plugin.
+ ///
+ public string Name => "Calibre Metadata";
+
+ ///
+ /// Gets the author of the plugin.
+ ///
+ public string Author => "Lumina";
+
+ ///
+ /// Gets the version of the plugin.
+ ///
+ public Version Version => new(1, 0, 0);
+
+ ///
+ /// Gets the description of the plugin.
+ ///
+ public string Description => "Reads book metadata and covers from the OPF files of a Calibre library.";
+
+ ///
+ /// Gets the settings schema of the plugin.
+ ///
+ /// The settings descriptors of the plugin.
+ public IReadOnlyList GetSettingsSchema()
+ {
+ return [];
+ }
+
+ ///
+ /// Registers the services required by the plugin.
+ ///
+ /// The service collection to register the services into.
+ public void RegisterServices(IServiceCollection services)
+ {
+ services.AddCalibreBookMetadataProvider(pluginId: Id);
+ services.AddCalibreArtworkProvider(pluginId: Id);
+ }
+}
diff --git a/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs b/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs
new file mode 100644
index 00000000..60c2dc54
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs
@@ -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;
+
+///
+/// Maps the metadata read from a Calibre OPF file into the application's book metadata DTO.
+///
+internal static class CalibreMapper
+{
+ ///
+ /// Maps the metadata read from the OPF file into a book metadata DTO.
+ ///
+ /// The metadata read from the OPF file.
+ /// The mapped book metadata.
+ 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
+ );
+ }
+
+ ///
+ /// Builds the release information of the book from its publication date.
+ ///
+ /// The publication date of the book.
+ /// The release information of the book, always present even when the publication date is missing.
+ 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
+ );
+ }
+
+ ///
+ /// Maps the ISBN identifiers of the book into ISBN DTOs, de-duplicating normalized values.
+ ///
+ /// The identifiers read from the OPF file.
+ /// The mapped and de-duplicated ISBN DTOs.
+ private static List BuildIsbns(List identifiers)
+ {
+ List result = [];
+ HashSet 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;
+ }
+
+ ///
+ /// Maps the creators and contributors of the book into contributor DTOs, de-duplicating identical name and role pairs.
+ ///
+ /// The creators read from the OPF file.
+ /// The contributors read from the OPF file.
+ /// The mapped contributor DTOs.
+ private static List BuildContributors(List creators, List contributors)
+ {
+ List result = [];
+ HashSet 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;
+ }
+
+ ///
+ /// Maps a language code into a language info DTO by matching it against known cultures.
+ ///
+ /// The raw language code to map.
+ /// The mapped language info, or when the code is empty.
+ private static LanguageInfoDto? MapLanguage(string? rawCode)
+ {
+ if (string.IsNullOrWhiteSpace(rawCode))
+ return null;
+
+ string code = rawCode.Trim().ToLowerInvariant();
+ IEnumerable 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);
+ }
+
+ ///
+ /// Strips the HTML markup of a description, leaving the text content.
+ ///
+ /// The HTML value to strip.
+ /// The text content, or when the value is empty.
+ 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;
+ }
+
+ ///
+ /// Normalizes an ISBN into its canonical form without separators or whitespace.
+ ///
+ /// The ISBN to normalize.
+ /// The normalized ISBN, or when the value is not a valid ISBN.
+ 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;
+ }
+
+ ///
+ /// Gets the value of the first identifier whose scheme matches one of the .
+ ///
+ /// The identifiers read from the OPF file.
+ /// The identifier schemes to try, in order.
+ /// The identifier value, or when no identifier matches.
+ private static string? GetIdentifier(List 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;
+ }
+
+ ///
+ /// Maps a creator or contributor role code into a role name.
+ ///
+ /// The role code to map.
+ /// The mapped role name.
+ private static string MapContributorRole(string? role)
+ {
+ return string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) ? "Author" : string.IsNullOrWhiteSpace(role) ? "Contributor" : role;
+ }
+
+ ///
+ /// Maps a creator or contributor role code into a contributor category.
+ ///
+ /// The role code to map.
+ /// The mapped contributor category.
+ 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";
+ }
+}
diff --git a/plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs b/plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs
new file mode 100644
index 00000000..cb776e35
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs
@@ -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;
+
+///
+/// Reads the metadata of a book from a Calibre OPF file.
+///
+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/";
+
+ ///
+ /// Reads the metadata of the book from the OPF file at .
+ ///
+ /// The file system path of the OPF file to read.
+ /// The metadata read from the OPF file, with the fields that could not be read left empty.
+ 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;
+ }
+
+ ///
+ /// Parses the metadata elements of the into the .
+ ///
+ /// The parsed OPF document.
+ /// The model onto which the parsed metadata is written.
+ 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;
+ }
+
+ ///
+ /// Gets the trimmed text of the child element with the specified of the element.
+ ///
+ /// The parent element.
+ /// The name of the child element.
+ /// The trimmed text, or when the element is missing or empty.
+ private static string? GetElementText(XElement parent, XName name)
+ {
+ string? value = parent.Element(name)?.Value;
+ return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
+ }
+
+ ///
+ /// Parses a date string into a .
+ ///
+ /// The date string to parse.
+ /// The parsed date, or when the string is empty or cannot be parsed.
+ 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;
+ }
+
+ ///
+ /// Parses a double string.
+ ///
+ /// The string to parse.
+ /// The parsed value, or when the string is empty or cannot be parsed.
+ private static double? ParseDouble(string value)
+ {
+ return double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result) ? result : null;
+ }
+
+ ///
+ /// Parses an integer string.
+ ///
+ /// The string to parse.
+ /// The parsed value, or when the string is empty or cannot be parsed.
+ private static int? ParseInt(string value)
+ {
+ return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int result) ? result : null;
+ }
+}
diff --git a/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj b/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj
new file mode 100644
index 00000000..d8974eac
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj
@@ -0,0 +1,32 @@
+
+
+ net10.0
+ disable
+ enable
+ $(SolutionDir)..\bin\plugins\
+ false
+ true
+ true
+ $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904
+
+
+
+
+
+
+
+
+
+
+
+
+
+ false
+ runtime
+
+
+
+
+
+
+
diff --git a/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs
new file mode 100644
index 00000000..c7bf9b3a
--- /dev/null
+++ b/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs
@@ -0,0 +1,4 @@
+using System.Runtime.CompilerServices;
+
+[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")]
+[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.Fixtures")]
diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs
index d102ba55..3505cf7c 100644
--- a/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs
+++ b/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs
@@ -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();
- if (settingsStore is not null)
- {
- IReadOnlyDictionary? 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();
- // Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IRemoteMetadataProvider implementations.
- services.AddKeyedTransient(pluginId);
+ // Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IMetadataProvider implementations.
+ services.AddKeyedTransient(pluginId);
return services;
}
diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs
index 7749f4a2..e5a606a8 100644
--- a/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs
+++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs
@@ -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 class.
///
/// The used to send requests to the Open Library API.
- /// The settings that configure the Open Library API requests.
- public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsDto openLibrarySettings)
+ /// The provider of the settings that configure the Open Library API requests.
+ 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!;
+ ///
+ /// Applies the request headers configured in the onto the underlying HTTP client, unless they are already set.
+ ///
+ /// The settings that configure the Open Library API requests.
+ 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!;
}
///
@@ -214,10 +223,13 @@ internal sealed class OpenLibraryHttpClient
/// The HTTP response message for the request.
private async Task 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);
diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs
index 041f7146..04058a62 100644
--- a/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs
+++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs
@@ -30,7 +30,7 @@ internal static partial class OpenLibraryMapper
///
/// Matches a volume number in a series or volume string.
///
- [GeneratedRegex(@"\b(?:volume|vol\.?|book|no\.?|#)\s*(?\d+)\b", RegexOptions.IgnoreCase)]
+ [GeneratedRegex(@"\b(?:volume|vol\.?|book|no\.?|#)\s*(?\d+(?:\.\d+)?)\b", RegexOptions.IgnoreCase)]
private static partial Regex VolumePattern();
///
@@ -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
///
/// The strings that may contain a volume number.
/// The parsed volume number, or when no candidate contains one.
- 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;
diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs
index 570b837d..b247c5dd 100644
--- a/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs
+++ b/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs
@@ -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;
///
/// Provides book metadata from the Open Library by resolving lookups into book metadata DTOs.
///
-internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider
+internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider
{
private readonly OpenLibraryHttpClient _openLibraryHttpClient;
- private readonly OpenLibrarySettingsDto _openLibrarySettings;
+ private readonly OpenLibrarySettingsProvider _settingsProvider;
///
/// Gets the display name of the metadata provider.
@@ -30,9 +31,9 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
public string Name => "Open Library";
///
- /// Gets the media library type this metadata provider supports.
+ /// Gets the media library types this metadata provider supports.
///
- public LibraryType SupportedLibraryType => LibraryType.Book;
+ public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book];
///
/// 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 class.
///
/// The HTTP client used to call the Open Library API.
- /// The settings that configure the Open Library API requests.
- public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsDto openLibrarySettings)
+ /// The provider of the settings that configure the Open Library API requests.
+ public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsProvider settingsProvider)
{
_openLibraryHttpClient = openLibraryHttpClient;
- _openLibrarySettings = openLibrarySettings;
+ _settingsProvider = settingsProvider;
}
///
@@ -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 openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, _openLibrarySettings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
+ IReadOnlyList 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)
diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsProvider.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsProvider.cs
new file mode 100644
index 00000000..931db570
--- /dev/null
+++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsProvider.cs
@@ -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;
+
+///
+/// Provides the runtime settings of the Open Library metadata plugin, overlaying the settings persisted by the host over the configured defaults.
+///
+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;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The store of the settings persisted by the host, or when no store is available.
+ /// The unique identifier of the plugin whose settings are read.
+ /// The runtime settings with the default values and the optional configuration callback already applied.
+ public OpenLibrarySettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, OpenLibrarySettingsDto defaults)
+ {
+ _settingsStore = settingsStore;
+ _pluginId = pluginId;
+ _defaults = defaults;
+ }
+
+ ///
+ /// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call.
+ ///
+ /// Cancellation token that can be used to stop the execution.
+ /// The runtime settings of the plugin.
+ public async Task 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? 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();
+ }
+ }
+
+ ///
+ /// Creates a copy of the given runtime settings.
+ ///
+ /// The runtime settings to copy.
+ /// A copy of the given runtime settings.
+ private static OpenLibrarySettingsDto Clone(OpenLibrarySettingsDto source)
+ {
+ return new OpenLibrarySettingsDto
+ {
+ UserAgent = source.UserAgent,
+ ContactEmail = source.ContactEmail,
+ SearchResultLimit = source.SearchResultLimit,
+ WorkEditionLimit = source.WorkEditionLimit,
+ MinimumRequestInterval = source.MinimumRequestInterval
+ };
+ }
+}
diff --git a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs
index 6b77d3dc..c13e4250 100644
--- a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs
+++ b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs
@@ -25,5 +25,5 @@ public record LibraryFilterDto : BaseFilterDto
///
/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.
///
- public bool IgnoreThePrefixForAlphaPicker { get; init; }
+ public bool ShouldIgnoreThePrefixForAlphaPicker { get; init; }
}
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs
index ef17ab05..a7c07954 100644
--- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs
+++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs
@@ -63,7 +63,7 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
///
/// Gets whether this media library should update the metadata of its elements from the web, or not.
///
- public bool DownloadMetadataFromWeb { get; init; }
+ public bool CanDownloadMetadataFromWeb { get; init; }
///
/// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not.
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs
index b526c7b5..dd02ed01 100644
--- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs
+++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs
@@ -138,7 +138,7 @@ public class BookEntity : IStorageEntity, IAuditableEntity
///
/// Gets or sets the volume or book number in the series, if applicable.
///
- public int? VolumeNumber { get; set; }
+ public float? VolumeNumber { get; set; }
// TODO: uncomment when series is implemented
///
/// Gets or sets the series id, if the book is part of a series.
@@ -190,6 +190,11 @@ public class BookEntity : IStorageEntity, IAuditableEntity
///
public string? AppleBooksId { get; set; }
+ ///
+ /// Gets or sets the file system path of the cover image of the book, if applicable.
+ ///
+ public string? CoverImagePath { get; set; }
+
///
/// Gets or sets the list of ISBN (International Standard Book Number) of the book.
///
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs
new file mode 100644
index 00000000..3bd58781
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs
@@ -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;
+
+///
+/// Repository entity for the configuration of an artwork provider of a media library.
+///
+[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
+public class LibraryArtworkProviderConfigurationEntity : IStorageEntity, IAuditableEntity
+{
+ ///
+ /// Gets or sets the Id of the configuration.
+ ///
+ public required Guid Id { get; init; }
+
+ ///
+ /// Gets or sets the Id of the media library the configuration belongs to.
+ ///
+ public required Guid LibraryId { get; set; }
+
+ ///
+ /// Gets or sets the Id of the plugin providing the artwork.
+ ///
+ public required Guid PluginId { get; set; }
+
+ ///
+ /// Gets or sets whether the artwork provider is enabled for the media library.
+ ///
+ public required bool IsEnabled { get; set; }
+
+ ///
+ /// Gets or sets the rank of the artwork provider, determining the order in which providers are tried.
+ ///
+ public required int Rank { get; set; }
+
+ ///
+ /// Gets or sets the time and date when the entity was added.
+ ///
+ public required DateTime CreatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the Id of the user that created the entity.
+ ///
+ public required Guid CreatedBy { get; set; }
+
+ ///
+ /// Gets or sets the optional time and date when the entity was updated.
+ ///
+ public DateTime? UpdatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the optional Id of the user that updated the entity.
+ ///
+ public required Guid? UpdatedBy { get; set; }
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs
index 524544bb..5e8de0bf 100644
--- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs
+++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs
@@ -35,13 +35,18 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity
///
/// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
///
- public bool IgnoreThePrefixForAlphaPicker { get; set; }
+ public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; }
///
/// Gets or sets whether the theme data served to this user is cached, or not.
///
public bool IsThemeCachingEnabled { get; set; } = true;
+ ///
+ /// Gets or sets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
+ ///
+ public bool ShouldAggregateMetadataWhenMissing { get; set; }
+
///
/// Gets or sets the time and date when the entity was added.
///
diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs
new file mode 100644
index 00000000..5f1ddb1f
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs
@@ -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;
+
+///
+/// Interface for the repository for the artwork provider configurations of media libraries.
+///
+public interface IArtworkProviderConfigurationRepository : IRepository
+{
+ ///
+ /// Gets all the artwork provider configurations of the media library identified by .
+ ///
+ /// The Id of the media library whose artwork provider configurations are retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either a collection of , or an error.
+ Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
+
+ ///
+ /// Gets the artwork provider configuration of the media library identified by for the plugin identified by .
+ ///
+ /// The Id of the media library whose artwork provider configuration is retrieved.
+ /// The Id of the plugin whose artwork provider configuration is retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the , or an error.
+ Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken);
+
+ ///
+ /// Inserts the provided into the storage medium, or updates it when it already exists.
+ ///
+ /// The artwork provider configuration to insert or update.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> UpsertAsync(LibraryArtworkProviderConfigurationEntity configuration, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
index dc49b1f4..17a48b83 100644
--- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
+++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
@@ -71,6 +71,11 @@ public interface IUnitOfWork
///
ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository { get; }
+ ///
+ /// Gets the library artwork provider configuration repository.
+ ///
+ IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository { get; }
+
///
/// Gets the plugin repository.
///
@@ -97,6 +102,11 @@ public interface IUnitOfWork
/// Cancellation token that can be used to stop the execution.
Task SaveChangesAsync(CancellationToken cancellationToken);
+ ///
+ /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy.
+ ///
+ void ClearTrackedEntities();
+
///
/// Begins a new database transaction.
///
diff --git a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs
index f68feee4..c77c25f4 100644
--- a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs
+++ b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs
@@ -21,4 +21,9 @@ public class MediaSettingsDto
/// Gets or sets the directory where media library files are stored.
///
public required string LibrariesDirectory { get; init; }
+
+ ///
+ /// Gets or sets the directory where the media item files are stored.
+ ///
+ public required string BooksDirectory { get; init; }
}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs
index 8e74f24c..f524961e 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs
@@ -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
);
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs
index 1484cf34..fe652e54 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs
@@ -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))]
);
}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs
index dac14f8a..90f36343 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs
@@ -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,
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs
index c0dfc446..374f9e15 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs
@@ -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
);
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs
index 5fa6a3a7..ed2abbc8 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs
@@ -110,14 +110,14 @@ public static class BookEntityMapping
Optional bookFormat = Optional.FromNullable(repositoryEntity.Format);
- return Book.Create(
+ Result bookResult = Book.Create(
BookId.Create(repositoryEntity.Id),
LibraryId.Create(repositoryEntity.LibraryId),
repositoryEntity.Path,
writtenContentMetadataResult.Value,
bookFormat,
Optional.FromNullable(repositoryEntity.Edition),
- Optional.FromNullable(repositoryEntity.VolumeNumber),
+ Optional.FromNullable(repositoryEntity.VolumeNumber),
Optional.None(),
Optional.FromNullable(repositoryEntity.ASIN),
Optional.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;
}
///
@@ -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
);
}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs
index 1a61e61c..3ad75ac6 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs
@@ -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,
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs
index e295cd5b..59747d48 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs
@@ -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 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 releaseInfoResult = ReleaseInfo.Create(
Optional.FromNullable(metadata.ReleaseInfo.OriginalReleaseDate),
@@ -115,7 +114,7 @@ public static class BookMetadataDtoMapping
writtenContentMetadataResult.Value,
Optional.FromNullable(metadata.Format.HasValue ? (BookFormat)(int)metadata.Format.Value : (BookFormat?)null),
Optional.FromNullable(metadata.Edition),
- Optional.FromNullable(metadata.VolumeNumber),
+ Optional.FromNullable(metadata.VolumeNumber),
Optional.None(),
Optional.FromNullable(metadata.ASIN),
Optional.FromNullable(metadata.GoodreadsId),
@@ -132,6 +131,9 @@ public static class BookMetadataDtoMapping
lastUpdateUtc
);
+ if (!string.IsNullOrWhiteSpace(metadata.CoverImagePath))
+ book.SetBookCoverImagePath(metadata.CoverImagePath);
+
return Result.Success;
}
}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs
index c3fa2f9f..1a7ca813 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs
@@ -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);
diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs
new file mode 100644
index 00000000..5dc3051b
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs
@@ -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;
+
+///
+/// Extension methods for converting .
+///
+public static class GetLibraryArtworkProvidersRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted query.
+ public static GetLibraryArtworkProvidersQuery ToQuery(this GetLibraryArtworkProvidersRequest request)
+ {
+ return new GetLibraryArtworkProvidersQuery(LibraryId: request.LibraryId);
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs
new file mode 100644
index 00000000..d21150ff
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs
@@ -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;
+
+///
+/// Extension methods for converting .
+///
+public static class LibraryArtworkProviderConfigurationEntityMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The repository entity to be converted.
+ /// The display name of the artwork provider.
+ /// The converted response.
+ public static LibraryArtworkProviderResponse ToResponse(this LibraryArtworkProviderConfigurationEntity configuration, string providerName)
+ {
+ return new LibraryArtworkProviderResponse(
+ PluginId: configuration.PluginId,
+ Name: providerName,
+ IsEnabled: configuration.IsEnabled,
+ Rank: configuration.Rank
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs
new file mode 100644
index 00000000..7b0ab2fc
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs
@@ -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;
+
+///
+/// Extension methods for converting .
+///
+public static class ReorderLibraryArtworkProvidersRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static ReorderLibraryArtworkProvidersCommand ToCommand(this ReorderLibraryArtworkProvidersRequest request)
+ {
+ return new ReorderLibraryArtworkProvidersCommand(
+ LibraryId: request.LibraryId,
+ PluginIds: request.PluginIds
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs
new file mode 100644
index 00000000..4494aeb8
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs
@@ -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;
+
+///
+/// Extension methods for converting .
+///
+public static class SetLibraryArtworkProviderEnabledRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static SetLibraryArtworkProviderEnabledCommand ToCommand(this SetLibraryArtworkProviderEnabledRequest request)
+ {
+ return new SetLibraryArtworkProviderEnabledCommand(
+ LibraryId: request.LibraryId,
+ PluginId: request.PluginId,
+ IsEnabled: request.IsEnabled
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs
index 23504a3c..aff25a7d 100644
--- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs
@@ -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
+ );
}
}
diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs
index b96f8fdb..b53990fd 100644
--- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs
@@ -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
+ );
}
///
@@ -43,7 +45,9 @@ public static class UserSettingsEntityMapping
repositoryEntity.UserId,
repositoryEntity.IsPaginationEnabled,
repositoryEntity.ItemsPerPage,
- repositoryEntity.IgnoreThePrefixForAlphaPicker,
- repositoryEntity.IsThemeCachingEnabled);
+ repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker,
+ repositoryEntity.IsThemeCachingEnabled,
+ repositoryEntity.ShouldAggregateMetadataWhenMissing
+ );
}
}
diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs
index 7a22ee1e..cde37e56 100644
--- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs
@@ -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
+ );
}
}
diff --git a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs
index 2e14e2f2..c0c5d385 100644
--- a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs
+++ b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs
@@ -93,6 +93,33 @@ public static class ValidatorUtilities
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
}
+ ///
+ /// Defines a validation rule that ensures the float property is greater than the specified value.
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, float valueToCompare)
+ {
+ return ruleBuilder.Must(value => value > valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the nullable float property is greater than the specified value.
+ ///
+ ///
+ /// If the property is , this rule passes (use to check for missing values).
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, float valueToCompare)
+ {
+ return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
+ }
+
///
/// Defines a validation rule that ensures the time span property is greater than the specified value.
///
diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs
index a9345eca..995a3ee6 100644
--- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs
@@ -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;
/// The path of the image file used as the cover for the library.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.
-/// Whether this media library should update the metadata of its elements from the web, or not.
+/// Whether this media library should update the metadata of its elements from the web, or not.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.
[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;
diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs
index 320cd84f..c4ad4181 100644
--- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs
@@ -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 : ICommandHandlerThe path of the image file used as the cover for the library.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.
-/// Whether this media library should update the metadata of its elements from the web, or not.
+/// Whether this media library should update the metadata of its elements from the web, or not.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.
[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;
diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs
index 1e13108a..8a210168 100644
--- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs
@@ -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 ScanId.Create(libraryScan.Id)).ToList()
+ [.. getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))]
);
if (createLibraryResult.IsFailure)
return createLibraryResult.Errors;
diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs
index 301727f5..d77ae07f 100644
--- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs
@@ -60,7 +60,7 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler 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);
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs
new file mode 100644
index 00000000..7967bf82
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs
@@ -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;
+
+///
+/// Interface for the service for storing the artwork of a book into the internal media directory and serving its relative path.
+///
+public interface IBookArtworkService
+{
+ ///
+ /// Stores the of the book into the internal media directory, and returns the relative path of the stored artwork.
+ ///
+ /// The Id of the media library the book belongs to.
+ /// The Id of the book.
+ /// The name of the media library the book belongs to.
+ /// The name of the author of the book.
+ /// The title of the book.
+ /// The artwork to store.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the relative path of the stored artwork, or an error.
+ Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken);
+
+ ///
+ /// Deletes the artwork of the book from the internal media directory.
+ ///
+ /// The Id of the media library the book belongs to.
+ /// The Id of the book.
+ /// The name of the media library the book belongs to.
+ /// The name of the author of the book.
+ /// The title of the book.
+ /// An representing either a successful operation, or an error.
+ Result DeleteBookArtwork(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle);
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs
index f75de677..0d0b29c9 100644
--- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs
@@ -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,
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs
index 78df6434..1e804b10 100644
--- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs
@@ -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
{
RuleFor(command => command.LibraryId)
.NotEmpty()
+ .WithError(Errors.WrittenContent.BookLibraryCannotBeNull)
+ .Must(id => id != Guid.Empty)
.WithError(Errors.WrittenContent.BookLibraryCannotBeNull);
RuleFor(command => command.Path)
diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs
new file mode 100644
index 00000000..a202a355
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs
@@ -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;
+
+///
+/// Command for reordering the artwork providers of a media library.
+///
+/// The Id of the media library whose artwork providers are reordered.
+/// The plugin Ids in the new order, from highest to lowest rank.
+public record ReorderLibraryArtworkProvidersCommand(
+ Guid LibraryId,
+ IReadOnlyList PluginIds
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs
new file mode 100644
index 00000000..eff8b941
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs
@@ -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;
+
+///
+/// Handler for the command to reorder the artwork providers of a media library.
+///
+public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public ReorderLibraryArtworkProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
+ {
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _unitOfWork = unitOfWork;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to reorder the artwork providers of a media library.
+ ///
+ /// The request to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An representing either a successful operation, or an error.
+ ///
+ public async Task> HandleAsync(ReorderLibraryArtworkProvidersCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // an authenticated request must always carry a user identity
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // admins can reorder the artwork providers of any library; for everyone else, only their own libraries
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
+ if (getConfigurationsResult.IsFailure)
+ return getConfigurationsResult.Errors;
+
+ Dictionary 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 upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
+ if (upsertResult.IsFailure)
+ return upsertResult.Errors;
+ }
+ }
+
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ return Result.Success;
+ }
+}
diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs
new file mode 100644
index 00000000..770f3f31
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs
@@ -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;
+
+///
+/// Validates the needed validation rules for .
+///
+public class ReorderLibraryArtworkProvidersCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ReorderLibraryArtworkProvidersCommandValidator()
+ {
+ RuleFor(command => command.LibraryId)
+ .NotEmpty()
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
+
+ RuleFor(command => command.PluginIds)
+ .NotNull()
+ .WithError(Errors.Plugins.PluginIdsListCannotBeNull)
+ .NotEmpty()
+ .WithError(Errors.Plugins.PluginIdsListCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs
index b04e7a35..8fc10e5b 100644
--- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs
+++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs
@@ -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>
{
private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
/// Injected validator for application validation rules.
- public ReorderLibraryMetadataProvidersCommandHandler(IUnitOfWork unitOfWork, IValidator validator)
+ public ReorderLibraryMetadataProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
@@ -47,6 +56,18 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler 0)
return validationResult;
+ // an authenticated request must always carry a user identity
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // admins can reorder the metadata providers of any library; for everyone else, only their own libraries
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return getConfigurationsResult.Errors;
diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs
index 1a9fd05c..95c01884 100644
--- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs
+++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs
@@ -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)
diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs
new file mode 100644
index 00000000..e4acf111
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs
@@ -0,0 +1,18 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
+
+///
+/// Command for enabling or disabling an artwork provider for a media library.
+///
+/// The Id of the media library whose artwork provider is enabled or disabled.
+/// The unique identifier of the plugin providing the artwork.
+/// Whether the artwork provider should be enabled for the media library.
+public record SetLibraryArtworkProviderEnabledCommand(
+ Guid LibraryId,
+ Guid PluginId,
+ bool IsEnabled
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs
new file mode 100644
index 00000000..c1974e81
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs
@@ -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;
+
+///
+/// Handler for the command to enable or disable an artwork provider for a media library.
+///
+public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public SetLibraryArtworkProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
+ {
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _unitOfWork = unitOfWork;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to enable or disable an artwork provider for a media library.
+ ///
+ /// The request to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An representing either a successful operation, or an error.
+ ///
+ public async Task> HandleAsync(SetLibraryArtworkProviderEnabledCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // an authenticated request must always carry a user identity
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // admins can configure the artwork providers of any library; for everyone else, only their own libraries
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ Result getConfigurationResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
+ if (getConfigurationResult.IsFailure)
+ return getConfigurationResult.Errors;
+
+ LibraryArtworkProviderConfigurationEntity configuration;
+ if (getConfigurationResult.Value is not null)
+ {
+ configuration = getConfigurationResult.Value;
+ configuration.IsEnabled = command.IsEnabled;
+ }
+ else
+ {
+ // compute the rank to assign to the new configuration, appending it after the existing ones
+ Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
+ if (getConfigurationsResult.IsFailure)
+ return getConfigurationsResult.Errors;
+ int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1;
+ configuration = new LibraryArtworkProviderConfigurationEntity
+ {
+ Id = Guid.NewGuid(),
+ LibraryId = command.LibraryId,
+ PluginId = command.PluginId,
+ IsEnabled = command.IsEnabled,
+ Rank = nextRank,
+ CreatedOnUtc = default,
+ CreatedBy = default,
+ UpdatedBy = default
+ };
+ }
+
+ Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
+ if (upsertResult.IsFailure)
+ return upsertResult.Errors;
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ return Result.Success;
+ }
+}
diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs
new file mode 100644
index 00000000..040a486f
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs
@@ -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;
+
+///
+/// Validates the needed validation rules for .
+///
+public class SetLibraryArtworkProviderEnabledCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public SetLibraryArtworkProviderEnabledCommandValidator()
+ {
+ RuleFor(command => command.LibraryId)
+ .NotEmpty()
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
+
+ RuleFor(command => command.PluginId)
+ .NotEmpty()
+ .WithError(Errors.Plugins.PluginIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.Plugins.PluginIdCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs
index d3d8eee5..21e21978 100644
--- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs
+++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs
@@ -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>
{
private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
/// Injected validator for application validation rules.
- public SetLibraryMetadataProviderEnabledCommandHandler(IUnitOfWork unitOfWork, IValidator validator)
+ public SetLibraryMetadataProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
@@ -47,6 +56,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler 0)
return validationResult;
+ // an authenticated request must always carry a user identity
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // admins can configure the metadata providers of any library; for everyone else, only their own libraries
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
Result getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
if (getConfigurationResult.IsFailure)
return getConfigurationResult.Errors;
diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs
index f631bc44..b910702f 100644
--- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs
+++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs
@@ -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);
}
}
diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs
index 283e4bf5..c100995f 100644
--- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs
+++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs
@@ -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 command.PluginId)
.NotEmpty()
+ .WithError(Errors.Plugins.PluginIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
.WithError(Errors.Plugins.PluginIdCannotBeEmpty);
}
}
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs
new file mode 100644
index 00000000..df65764d
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs
@@ -0,0 +1,14 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
+
+///
+/// Query for getting the artwork providers configured for a media library.
+///
+/// The Id of the media library whose artwork providers are retrieved.
+public record GetLibraryArtworkProvidersQuery(
+ Guid LibraryId
+) : IQuery;
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs
new file mode 100644
index 00000000..e5f518db
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs
@@ -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;
+
+///
+/// Handler for the query to get the artwork providers configured for a media library.
+///
+public class GetLibraryArtworkProvidersQueryHandler : IQueryHandler>>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected validator for application validation rules.
+ public GetLibraryArtworkProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
+ {
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _unitOfWork = unitOfWork;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the query to get the artwork providers configured for a media library.
+ ///
+ /// The request to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either a collection of , or an error.
+ ///
+ public async Task>> HandleAsync(GetLibraryArtworkProvidersQuery query, CancellationToken cancellationToken)
+ {
+ List 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(
+ userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ Result> 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> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
+ if (getPluginsResult.IsFailure)
+ return getPluginsResult.Errors;
+ Dictionary 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();
+ }
+}
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs
new file mode 100644
index 00000000..4231fb1a
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs
@@ -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;
+
+///
+/// Validates the needed validation rules for .
+///
+public class GetLibraryArtworkProvidersQueryValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetLibraryArtworkProvidersQueryValidator()
+ {
+ RuleFor(query => query.LibraryId)
+ .NotEmpty()
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs
index 6ed087fe..391cf371 100644
--- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs
@@ -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>>
{
private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
///
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
- public GetLibraryMetadataProvidersQueryHandler(IUnitOfWork unitOfWork)
+ /// Injected validator for application validation rules.
+ public GetLibraryMetadataProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
_unitOfWork = unitOfWork;
+ _validator = validator;
}
///
@@ -41,6 +54,22 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler
public async Task>> HandleAsync(GetLibraryMetadataProvidersQuery query, CancellationToken cancellationToken)
{
+ List 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(
+ userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return getConfigurationsResult.Errors;
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs
new file mode 100644
index 00000000..931c1ae3
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs
@@ -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;
+
+///
+/// Validates the needed validation rules for .
+///
+public class GetLibraryMetadataProvidersQueryValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetLibraryMetadataProvidersQueryValidator()
+ {
+ RuleFor(query => query.LibraryId)
+ .NotEmpty()
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs
index 5e26b31d..28a8eae3 100644
--- a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs
@@ -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 _validator;
///
/// Initializes a new instance of the class.
///
/// Injected unit of work for interacting with the data access layer repositories.
/// Injected manager of the plugins loaded by the host application.
- public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager)
+ /// Injected validator for application validation rules.
+ public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager, IValidator validator)
{
_unitOfWork = unitOfWork;
_pluginManager = pluginManager;
+ _validator = validator;
}
///
@@ -46,6 +49,10 @@ public class GetPluginSettingsQueryHandler : IQueryHandler
public async Task> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken)
{
+ List validationResult = _validator.Validate(query);
+ if (validationResult.Count > 0)
+ return validationResult;
+
Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false);
if (getPluginResult.IsFailure)
return getPluginResult.Errors;
diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs
new file mode 100644
index 00000000..2a94c3b5
--- /dev/null
+++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs
@@ -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;
+
+///
+/// Validates the needed validation rules for .
+///
+public class GetPluginSettingsQueryValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetPluginSettingsQueryValidator()
+ {
+ RuleFor(query => query.PluginId)
+ .NotEmpty()
+ .WithError(Errors.Plugins.PluginIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.Plugins.PluginIdCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs
index 0e798ccc..e29088bf 100644
--- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs
+++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs
@@ -9,11 +9,13 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe
///
/// Whether pagination is enabled for the user, or not.
/// The number of library items displayed per page when pagination is enabled.
-/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
+/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
/// Whether the theme data served to this user is cached, or not.
+/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
public record UpdateUserSettingsCommand(
bool IsPaginationEnabled,
int ItemsPerPage,
- bool IgnoreThePrefixForAlphaPicker,
- bool IsThemeCachingEnabled
+ bool ShouldIgnoreThePrefixForAlphaPicker,
+ bool IsThemeCachingEnabled,
+ bool ShouldAggregateMetadataWhenMissing
) : ICommand;
diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs
index 3028518b..9af3a222 100644
--- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs
+++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs
@@ -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 updateSettingsResult = toDomainEntityResult.Value.UpdateSettings(
command.IsPaginationEnabled,
command.ItemsPerPage,
- command.IgnoreThePrefixForAlphaPicker,
- command.IsThemeCachingEnabled);
+ command.ShouldIgnoreThePrefixForAlphaPicker,
+ command.IsThemeCachingEnabled,
+ command.ShouldAggregateMetadataWhenMissing);
if (updateSettingsResult.IsFailure)
return updateSettingsResult.Errors;
diff --git a/src/Lumina.Contracts/DTO/Common/ArtworkDto.cs b/src/Lumina.Contracts/DTO/Common/ArtworkDto.cs
new file mode 100644
index 00000000..725576a6
--- /dev/null
+++ b/src/Lumina.Contracts/DTO/Common/ArtworkDto.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.DTO.Common;
+
+///
+/// Data transfer object for the artwork of a media item, provided by an artwork provider.
+///
+/// The local file system path of the artwork, when the artwork is a local file.
+/// The remote URL of the artwork, when the artwork is fetched over the web.
+[DebuggerDisplay("LocalPath: {LocalPath}, RemoteUrl: {RemoteUrl}")]
+public sealed record ArtworkDto(
+ string? LocalPath,
+ string? RemoteUrl
+);
diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs
index f557fe73..d0d5f723 100644
--- a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs
+++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs
@@ -36,7 +36,7 @@ namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
/// The list of ISBN (International Standard Book Number) of the book.
/// The list of media contributors of the book.
/// The list of ratings for the book.
-/// The URL of the cover image of the book, if applicable.
+/// The path of the cover image of the book, if applicable.
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? Isbns,
List? Contributors,
List? Ratings,
- string? CoverImageUrl
+ string? CoverImagePath
) : MetadataDto;
diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs
index bfc717ba..df43eb8d 100644
--- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs
@@ -13,7 +13,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management;
/// The path of the image file used as the cover for the library. Optional.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.
-/// Whether this media library should update the metadata of its elements from the web, or not. Optional.
+/// Whether this media library should update the metadata of its elements from the web, or not. Optional.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.
[DebuggerDisplay("Title: {Title}")]
@@ -24,7 +24,7 @@ public record AddLibraryRequest(
string? CoverImage,
bool IsEnabled,
bool IsLocked,
- bool DownloadMetadataFromWeb,
+ bool CanDownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
);
diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs
index ad62394a..9590f10a 100644
--- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs
@@ -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;
/// The path of the image file used as the cover for the library. Optional.
/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.
/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.
-/// Whether this media library should update the metadata of its elements from the web, or not. Optional.
+/// Whether this media library should update the metadata of its elements from the web, or not. Optional.
/// Whether this media library should copy the downloaded metadata into the media library content locations, or not.
/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.
[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
);
diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs
index d46fa0c9..7754e087 100644
--- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs
@@ -39,7 +39,7 @@ public record AddBookRequest(
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
string? Edition,
- int? VolumeNumber,
+ float? VolumeNumber,
BookSeriesDto? Series,
string? ASIN,
string? GoodreadsId,
diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs
index 6a5a1dc1..03b500ac 100644
--- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs
@@ -18,7 +18,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
/// Can be 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.
///
-/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.
+/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.
/// The name of the field by which to sort the results. Optional.
/// The direction in which to sort the results. Optional.
[DebuggerDisplay("LibraryId: {LibraryId}")]
@@ -28,7 +28,7 @@ public record GetBooksLiteRequest(
int? PerPage,
string? SearchTerm,
string? FilterAlphaKey,
- bool IgnoreThePrefixForAlphaPicker,
+ bool ShouldIgnoreThePrefixForAlphaPicker,
string? SortBy,
SortOrder? SortOrder
);
diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs
new file mode 100644
index 00000000..ff504590
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs
@@ -0,0 +1,15 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Plugins;
+
+///
+/// Represents a request to get the artwork providers configured for a media library.
+///
+/// The unique identifier of the media library whose artwork providers are retrieved. Required.
+[DebuggerDisplay("LibraryId: {LibraryId}")]
+public sealed record GetLibraryArtworkProvidersRequest(
+ Guid LibraryId
+);
diff --git a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs
new file mode 100644
index 00000000..0e0f815c
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs
@@ -0,0 +1,18 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Plugins;
+
+///
+/// Represents a request to reorder the artwork providers of a media library.
+///
+/// The unique identifier of the media library whose artwork providers are reordered. Required.
+/// The plugin Ids in the new order, from highest to lowest rank. Required.
+[DebuggerDisplay("LibraryId: {LibraryId}")]
+public sealed record ReorderLibraryArtworkProvidersRequest(
+ Guid LibraryId,
+ IReadOnlyList PluginIds
+);
diff --git a/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs
new file mode 100644
index 00000000..bbfb2b95
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs
@@ -0,0 +1,19 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.Plugins;
+
+///
+/// Represents a request to enable or disable an artwork provider for a media library.
+///
+/// The unique identifier of the media library whose artwork provider is enabled or disabled. Required.
+/// The unique identifier of the plugin providing the artwork. Required.
+/// Whether the artwork provider should be enabled for the media library. Required.
+[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
+public sealed record SetLibraryArtworkProviderEnabledRequest(
+ Guid LibraryId,
+ Guid PluginId,
+ bool IsEnabled
+);
diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs
index 2b0ad237..b37216ac 100644
--- a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs
+++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs
@@ -9,12 +9,14 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings;
///
/// Whether pagination is enabled for the user, or not. Required.
/// The number of library items displayed per page when pagination is enabled. Required.
-/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required.
+/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required.
/// Whether the theme data served to this user is cached, or not. Required.
+/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. Required.
[DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")]
public sealed record UpdateUserSettingsRequest(
bool IsPaginationEnabled,
int ItemsPerPage,
- bool IgnoreThePrefixForAlphaPicker,
- bool IsThemeCachingEnabled
+ bool ShouldIgnoreThePrefixForAlphaPicker,
+ bool IsThemeCachingEnabled,
+ bool ShouldAggregateMetadataWhenMissing
);
diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs
index 9ec7de01..9dff6ddc 100644
--- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs
+++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs
@@ -16,6 +16,11 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management;
/// The type of the media library.
/// The file system paths of the directories where the media library elements are located.
/// The path of the image file used as the cover for the library.
+/// Whether the media library is enabled or not. A disabled media library is never shown or changed.
+/// Whether the media library is locked or not. A locked media library is displayed, but is never changed or updated.
+/// Whether the media library should update the metadata of its elements from the web, or not.
+/// Whether the media library should copy the downloaded metadata into the media library content locations, or not.
+/// Whether the media library should skip the directories whose contents have not changed since the last scan, during the scan.
/// The date and time when the library was created.
/// The optional date and time when the library was updated.
[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,
diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs
index 483b7579..bf4ea18d 100644
--- a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs
+++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs
@@ -38,6 +38,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibr
/// The name of the plugin that enriched the metadata of the book, if applicable.
/// The date and time when the book was created.
/// The optional date and time when the book was updated.
+/// The path of the cover image of the book, if available.
[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
);
diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs
new file mode 100644
index 00000000..c9b01c01
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs
@@ -0,0 +1,19 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+#endregion
+
+namespace Lumina.Contracts.Responses.Plugins;
+
+///
+/// Represents an artwork provider configured for a media library.
+///
+/// The unique identifier of the plugin providing the artwork.
+/// The display name of the artwork provider.
+/// Whether the artwork provider is enabled for the media library.
+/// The rank of the artwork provider, determining the order in which providers are tried.
+public sealed record LibraryArtworkProviderResponse(
+ Guid PluginId,
+ string Name,
+ bool IsEnabled,
+ int Rank
+);
diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs
index 3c362b34..3f5c59e3 100644
--- a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs
+++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs
@@ -11,13 +11,15 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings;
/// The unique identifier of the user that owns these settings.
/// Whether pagination is enabled for the user, or not.
/// The number of library items displayed per page when pagination is enabled.
-/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
+/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.
/// Whether the theme data served to this user is cached, or not.
+/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.
[DebuggerDisplay("UserId: {UserId}")]
public sealed record UserSettingsResponse(
Guid UserId,
bool IsPaginationEnabled,
int ItemsPerPage,
- bool IgnoreThePrefixForAlphaPicker,
- bool IsThemeCachingEnabled
+ bool ShouldIgnoreThePrefixForAlphaPicker,
+ bool IsThemeCachingEnabled,
+ bool ShouldAggregateMetadataWhenMissing
);
diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs
new file mode 100644
index 00000000..89618882
--- /dev/null
+++ b/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs
@@ -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;
+
+///
+/// Configures the entity mapping for the entity.
+///
+public class LibraryArtworkProviderConfigurationConfiguration : IEntityTypeConfiguration
+{
+ ///
+ /// Configures the entity.
+ ///
+ /// The builder to be used to configure the entity.
+ public void Configure(EntityTypeBuilder 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 });
+ }
+}
diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs
index 6e085ae3..8c27891a 100644
--- a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs
+++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs
@@ -46,7 +46,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration
builder.Property(library => library.IsLocked)
.HasColumnOrder(5);
- builder.Property(library => library.DownloadMetadataFromWeb)
+ builder.Property(library => library.CanDownloadMetadataFromWeb)
.HasDefaultValue(true)
.HasColumnOrder(6);
diff --git a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs
index ca160a72..84a4f221 100644
--- a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs
+++ b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs
@@ -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 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);
diff --git a/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs
new file mode 100644
index 00000000..f95ae4c2
--- /dev/null
+++ b/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs
@@ -0,0 +1,1358 @@
+//
+using System;
+using Lumina.DataAccess.Core.UoW;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+#nullable disable
+
+namespace Lumina.DataAccess.Common.Migrations
+{
+ [DbContext(typeof(LuminaDbContext))]
+ [Migration("20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation")]
+ partial class AddsArtworkProvidersAndBookCoverAndMetadataAggregation
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "10.0.11");
+
+ modelBuilder.Entity("BookGenres", b =>
+ {
+ b.Property("BookId")
+ .HasColumnType("TEXT");
+
+ b.Property("GenreId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("BookId", "GenreId");
+
+ b.HasIndex("GenreId");
+
+ b.ToTable("BookGenres", (string)null);
+ });
+
+ modelBuilder.Entity("BookTags", b =>
+ {
+ b.Property("BookId")
+ .HasColumnType("TEXT");
+
+ b.Property("TagId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("BookId", "TagId");
+
+ b.HasIndex("TagId");
+
+ b.ToTable("BookTags", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.Property("PermissionName")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(6);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(5);
+
+ b.HasKey("Id");
+
+ b.ToTable("Permissions", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.Property("RoleName")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(6);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(5);
+
+ b.HasKey("Id");
+
+ b.ToTable("Roles", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b =>
+ {
+ b.Property("RoleId")
+ .HasColumnType("TEXT");
+
+ b.Property("PermissionId")
+ .HasColumnType("TEXT");
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.HasKey("RoleId", "PermissionId");
+
+ b.HasIndex("PermissionId");
+
+ b.HasIndex("RoleId", "PermissionId")
+ .IsUnique();
+
+ b.ToTable("RolePermissions", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b =>
+ {
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.Property("PermissionId")
+ .HasColumnType("TEXT");
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.HasKey("UserId", "PermissionId");
+
+ b.HasIndex("PermissionId");
+
+ b.HasIndex("UserId", "PermissionId")
+ .IsUnique();
+
+ b.ToTable("UserPermissions", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b =>
+ {
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("RoleId")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.HasKey("UserId");
+
+ b.HasIndex("RoleId");
+
+ b.HasIndex("UserId", "RoleId")
+ .IsUnique();
+
+ b.ToTable("UserRoles", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b =>
+ {
+ b.Property("Name")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Name");
+
+ b.ToTable("Genres", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b =>
+ {
+ b.Property("Name")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Name");
+
+ b.ToTable("Tags", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b =>
+ {
+ b.Property("LibraryId")
+ .HasColumnType("TEXT");
+
+ b.Property("Path")
+ .HasMaxLength(1024)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("Id")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("LastWriteTimeUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.HasKey("LibraryId", "Path");
+
+ b.HasIndex("LibraryId");
+
+ b.ToTable("DirectoryScanFingerprints", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("CanDownloadMetadataFromWeb")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER")
+ .HasDefaultValue(true)
+ .HasColumnOrder(6);
+
+ b.Property("CoverImage")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(10);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(9);
+
+ b.Property("IsEnabled")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER")
+ .HasDefaultValue(true)
+ .HasColumnOrder(4);
+
+ b.Property("IsLocked")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(5);
+
+ b.Property("LibraryType")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("ShouldSaveMetadataInMediaDirectories")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(7);
+
+ b.Property("ShouldSkipUnchangedDirectoriesDuringScan")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(8);
+
+ b.Property("Title")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(12);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(11);
+
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("Libraries", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("LibraryId")
+ .HasColumnType("TEXT");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(5);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("LibraryId", "Status", "CreatedOnUtc")
+ .IsDescending(true, false, true);
+
+ b.ToTable("LibraryScans", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b =>
+ {
+ b.Property("LibraryScanId")
+ .HasColumnType("TEXT");
+
+ b.Property("Path")
+ .HasMaxLength(1024)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("ContentHash")
+ .HasMaxLength(24)
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(2);
+
+ b.Property("FileSize")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(3);
+
+ b.Property("Id")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(10)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(5);
+
+ b.Property("Ticks")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(4);
+
+ b.HasKey("LibraryScanId", "Path");
+
+ b.HasIndex("Path");
+
+ b.HasIndex("ContentHash", "FileSize", "Path");
+
+ b.ToTable("LibraryScanResults", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b =>
+ {
+ b.Property("LibraryId")
+ .HasColumnType("TEXT");
+
+ b.Property("Path")
+ .HasMaxLength(1024)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("ContentHash")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(2);
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(6);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(5);
+
+ b.Property("FileSize")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(3);
+
+ b.Property("Id")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("Ticks")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(4);
+
+ b.Property("UpdatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(8);
+
+ b.Property("UpdatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(7);
+
+ b.HasKey("LibraryId", "Path");
+
+ b.HasIndex("LibraryId");
+
+ b.ToTable("LibraryScanSnapshots", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b =>
+ {
+ b.Property("LibraryScanId")
+ .HasColumnType("TEXT");
+
+ b.Property("Path")
+ .HasMaxLength(1024)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(1);
+
+ b.Property("ContentHash")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(4);
+
+ b.Property("Id")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("IsNew")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(7);
+
+ b.Property("NeedsRehash")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(6);
+
+ b.Property("PreviousContentHash")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(5);
+
+ b.Property("Size")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(2);
+
+ b.Property("Ticks")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(3);
+
+ b.HasKey("LibraryScanId", "Path");
+
+ b.HasIndex("LibraryScanId", "NeedsRehash");
+
+ b.ToTable("LibraryScanStagingResults", (string)null);
+ });
+
+ modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(0);
+
+ b.Property("ASIN")
+ .HasMaxLength(10)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(21);
+
+ b.Property("AppleBooksId")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(29);
+
+ b.Property("BarnesAndNobleId")
+ .HasMaxLength(10)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(28);
+
+ b.Property("CoverImagePath")
+ .HasColumnType("TEXT");
+
+ b.Property("CreatedBy")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(33);
+
+ b.Property("CreatedOnUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(32);
+
+ b.Property("Description")
+ .HasMaxLength(2000)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(3);
+
+ b.Property("Edition")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(19);
+
+ b.Property("Format")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(18);
+
+ b.Property("GoodreadsId")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(22);
+
+ b.Property("GoogleBooksId")
+ .HasMaxLength(12)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(27);
+
+ b.Property("LCCN")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(23);
+
+ b.Property("LanguageCode")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(10);
+
+ b.Property("LanguageName")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(11);
+
+ b.Property("LanguageNativeName")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(12);
+
+ b.Property("LastMetadataUpdateUtc")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(39);
+
+ b.Property("LibraryId")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(36);
+
+ b.Property("LibraryThingId")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(26);
+
+ b.Property("MetadataProvider")
+ .HasMaxLength(100)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(40);
+
+ b.Property("MetadataStatus")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(38);
+
+ b.Property("OCLCNumber")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(24);
+
+ b.Property("OpenLibraryId")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(25);
+
+ b.Property("OriginalLanguageCode")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(13);
+
+ b.Property("OriginalLanguageName")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(14);
+
+ b.Property("OriginalLanguageNativeName")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(15);
+
+ b.Property("OriginalReleaseDate")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(4);
+
+ b.Property("OriginalReleaseYear")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(5);
+
+ b.Property("OriginalTitle")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(2);
+
+ b.Property("PageCount")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(17);
+
+ b.Property("Path")
+ .IsRequired()
+ .HasMaxLength(2048)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(37);
+
+ b.Property("Publisher")
+ .HasMaxLength(100)
+ .HasColumnType("TEXT")
+ .HasColumnOrder(16);
+
+ b.Property("ReReleaseDate")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(6);
+
+ b.Property("ReReleaseYear")
+ .HasColumnType("INTEGER")
+ .HasColumnOrder(7);
+
+ b.Property("ReleaseCountry")
+ .HasColumnType("TEXT")
+ .HasColumnOrder(8);
+
+ b.Property