Adds artwork provider system and Calibre plugin

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

No files matched your search

@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Calibre.Core;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using System;
#endregion
namespace Lumina.Plugins.Calibre.Common.DependencyInjection;
/// <summary>
/// Provides extension methods for registering the Calibre metadata and artwork providers.
/// </summary>
internal static class CalibreServices
{
/// <summary>
/// Registers the Calibre book metadata provider, associated with the plugin that provides it.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
/// <returns>The service collection, for chaining.</returns>
internal static IServiceCollection AddCalibreBookMetadataProvider(this IServiceCollection services, Guid pluginId)
{
ArgumentNullException.ThrowIfNull(services);
// Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IMetadataProvider implementations.
services.AddKeyedTransient<IMetadataProvider, CalibreBookMetadataProvider>(pluginId);
return services;
}
/// <summary>
/// Registers the Calibre artwork provider, associated with the plugin that provides it.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the artwork.</param>
/// <returns>The service collection, for chaining.</returns>
internal static IServiceCollection AddCalibreArtworkProvider(this IServiceCollection services, Guid pluginId)
{
ArgumentNullException.ThrowIfNull(services);
// Register the artwork provider as a keyed by pluginId transient service, so it can be resolved specifically among other IArtworkProvider implementations.
services.AddKeyedTransient<IArtworkProvider, CalibreArtworkProvider>(pluginId);
return services;
}
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
/// <summary>
/// Data transfer object for a contributor of a book read from an OPF file.
/// </summary>
/// <param name="Name">The name of the contributor.</param>
/// <param name="Role">The role code of the contributor, for example <c>bkp</c> for the book producer.</param>
[DebuggerDisplay("Name: {Name}")]
internal sealed record OpfContributorDto(
string Name,
string? Role
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
/// <summary>
/// Data transfer object for a creator of a book read from an OPF file.
/// </summary>
/// <param name="Name">The name of the creator.</param>
/// <param name="Role">The role code of the creator, for example <c>aut</c> for author.</param>
[DebuggerDisplay("Name: {Name}")]
internal sealed record OpfCreatorDto(
string Name,
string? Role
);
@@ -0,0 +1,79 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
/// <summary>
/// Data transfer object for the metadata read from a Calibre OPF file.
/// </summary>
[DebuggerDisplay("Title: {Title}")]
internal sealed class OpfDocumentDto
{
/// <summary>
/// Gets or sets the title of the book.
/// </summary>
public string? Title { get; set; }
/// <summary>
/// Gets or sets the description of the book, in HTML format.
/// </summary>
public string? Description { get; set; }
/// <summary>
/// Gets or sets the publisher of the book.
/// </summary>
public string? Publisher { get; set; }
/// <summary>
/// Gets or sets the publication date of the book.
/// </summary>
public DateTimeOffset? PublishDate { get; set; }
/// <summary>
/// Gets or sets the language code of the book.
/// </summary>
public string? LanguageCode { get; set; }
/// <summary>
/// Gets or sets the name of the series the book belongs to, if applicable.
/// </summary>
public string? Series { get; set; }
/// <summary>
/// Gets or sets the index of the book within its series, if applicable.
/// </summary>
public double? SeriesIndex { get; set; }
/// <summary>
/// Gets or sets the personal rating of the book, on a scale of 0 to 10.
/// </summary>
public int? Rating { get; set; }
/// <summary>
/// Gets or sets the href of the cover image, relative to the directory of the book.
/// </summary>
public string? CoverHref { get; set; }
/// <summary>
/// Gets the creators of the book.
/// </summary>
public List<OpfCreatorDto> Creators { get; } = [];
/// <summary>
/// Gets the contributors of the book.
/// </summary>
public List<OpfContributorDto> Contributors { get; } = [];
/// <summary>
/// Gets the identifiers of the book, with their schemes.
/// </summary>
public List<OpfIdentifierDto> Identifiers { get; } = [];
/// <summary>
/// Gets the subjects of the book, used as tags.
/// </summary>
public List<string> Subjects { get; } = [];
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
/// <summary>
/// Data transfer object for an identifier of a book read from an OPF file, with its scheme.
/// </summary>
/// <param name="Scheme">The scheme of the identifier, for example <c>ISBN</c> or <c>GOODREADS</c>.</param>
/// <param name="Value">The value of the identifier.</param>
[DebuggerDisplay("{Scheme}: {Value}")]
internal sealed record OpfIdentifierDto(
string Scheme,
string Value
);
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
using Lumina.Plugins.Calibre.Core.Opf;
using Lumina.Plugins.Contracts.Core.Metadata;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Calibre.Core;
/// <summary>
/// Provides the cover of a book from the cover reference of the Calibre OPF file located next to the book file.
/// </summary>
internal sealed class CalibreArtworkProvider : IArtworkProvider<BookMetadataLookupDto>
{
/// <summary>
/// Gets the display name of the artwork provider.
/// </summary>
public string Name => "Calibre";
/// <summary>
/// Gets the media library types this artwork provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook];
/// <summary>
/// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Gets the cover of the book described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the book to get the cover for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The cover of the book, or <see langword="null"/> when no cover was found.</returns>
public Task<ArtworkDto?> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Path))
return Task.FromResult<ArtworkDto?>(null);
string bookDirectory = Path.GetDirectoryName(lookup.Path) ?? string.Empty;
string opfFilePath = Path.Combine(bookDirectory, "metadata.opf");
if (!File.Exists(opfFilePath))
return Task.FromResult<ArtworkDto?>(null);
OpfDocumentDto document = OpfReader.Read(opfFilePath);
if (string.IsNullOrWhiteSpace(document.CoverHref))
return Task.FromResult<ArtworkDto?>(null);
// the cover reference must be a bare file name contained in the directory of the book, so that no file outside of it can be accessed
string coverFileName = Path.GetFileName(document.CoverHref);
if (coverFileName != document.CoverHref || Path.IsPathRooted(document.CoverHref))
return Task.FromResult<ArtworkDto?>(null);
string coverFilePath = Path.Combine(bookDirectory, coverFileName);
if (!File.Exists(coverFilePath))
return Task.FromResult<ArtworkDto?>(null);
return Task.FromResult<ArtworkDto?>(new ArtworkDto(LocalPath: coverFilePath, RemoteUrl: null));
}
}
@@ -0,0 +1,75 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Calibre.Core.Mapping;
using Lumina.Plugins.Calibre.Core.Opf;
using Lumina.Plugins.Contracts.Core.Metadata;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.Calibre.Core;
/// <summary>
/// Provides book metadata from Calibre OPF files by resolving lookups into book metadata DTOs.
/// </summary>
internal sealed class CalibreBookMetadataProvider : IMetadataProvider<BookMetadataLookupDto, BookMetadataDto>
{
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "Calibre";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Searches for the metadata of the media item described by <paramref name="bookMetadataLookup"/>.
/// </summary>
/// <param name="bookMetadataLookup">The lookup describing the media item to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of metadata candidates found for the media item.</returns>
public Task<IReadOnlyList<BookMetadataDto>> GetSearchResultsAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
{
BookMetadataDto? metadata = GetMetadata(bookMetadataLookup);
return Task.FromResult<IReadOnlyList<BookMetadataDto>>(metadata is null ? [] : [metadata]);
}
/// <summary>
/// Gets the metadata of the media item described by <paramref name="bookMetadataLookup"/>.
/// </summary>
/// <param name="bookMetadataLookup">The lookup describing the media item to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found.</returns>
public Task<BookMetadataDto?> GetMetadataAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
{
return Task.FromResult(GetMetadata(bookMetadataLookup));
}
/// <summary>
/// Reads the metadata of the book from the OPF file located next to the book file described by <paramref name="bookMetadataLookup"/>.
/// </summary>
/// <param name="bookMetadataLookup">The lookup describing the book to get the metadata for.</param>
/// <returns>The metadata of the book, or <see langword="null"/> when no OPF file was found.</returns>
private static BookMetadataDto? GetMetadata(BookMetadataLookupDto bookMetadataLookup)
{
if (string.IsNullOrWhiteSpace(bookMetadataLookup.Path))
return null;
string opfFilePath = Path.Combine(Path.GetDirectoryName(bookMetadataLookup.Path) ?? string.Empty, "metadata.opf");
if (!File.Exists(opfFilePath))
return null;
return CalibreMapper.Map(OpfReader.Read(opfFilePath));
}
}
@@ -0,0 +1,65 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Calibre.Common.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.Calibre.Core;
/// <summary>
/// Plugin that provides book metadata and book covers from Calibre OPF files.
/// </summary>
public sealed class CalibrePlugin : IPlugin, IPluginServiceRegistrator
{
/// <summary>
/// The unique identifier of the plugin.
/// </summary>
public static readonly Guid s_pluginId = new("a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d");
/// <summary>
/// Gets the unique identifier of the plugin.
/// </summary>
public Guid Id => s_pluginId;
/// <summary>
/// Gets the display name of the plugin.
/// </summary>
public string Name => "Calibre Metadata";
/// <summary>
/// Gets the author of the plugin.
/// </summary>
public string Author => "Lumina";
/// <summary>
/// Gets the version of the plugin.
/// </summary>
public Version Version => new(1, 0, 0);
/// <summary>
/// Gets the description of the plugin.
/// </summary>
public string Description => "Reads book metadata and covers from the OPF files of a Calibre library.";
/// <summary>
/// Gets the settings schema of the plugin.
/// </summary>
/// <returns>The settings descriptors of the plugin.</returns>
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
{
return [];
}
/// <summary>
/// Registers the services required by the plugin.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
public void RegisterServices(IServiceCollection services)
{
services.AddCalibreBookMetadataProvider(pluginId: Id);
services.AddCalibreArtworkProvider(pluginId: Id);
}
}
@@ -0,0 +1,242 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Plugins.Calibre.Core.Mapping;
/// <summary>
/// Maps the metadata read from a Calibre OPF file into the application's book metadata DTO.
/// </summary>
internal static class CalibreMapper
{
/// <summary>
/// Maps the metadata read from the OPF file into a book metadata DTO.
/// </summary>
/// <param name="document">The metadata read from the OPF file.</param>
/// <returns>The mapped book metadata.</returns>
public static BookMetadataDto Map(OpfDocumentDto document)
{
float? volumeNumber = document.SeriesIndex is > 0 ? (float?)document.SeriesIndex : null;
return new BookMetadataDto(
Title: document.Title,
OriginalTitle: null,
Description: StripHtml(document.Description),
ReleaseInfo: BuildReleaseInfo(document.PublishDate),
Genres: null,
Tags: [.. document.Subjects.Select(subject => new TagDto(Name: subject))],
Language: MapLanguage(document.LanguageCode),
OriginalLanguage: null,
Publisher: document.Publisher,
PageCount: null,
Format: null,
Edition: null,
VolumeNumber: volumeNumber,
Series: document.Series is null ? null : new BookSeriesDto(Title: document.Series),
ASIN: GetIdentifier(document.Identifiers, "asin", "amazon"),
GoodreadsId: GetIdentifier(document.Identifiers, "goodreads"),
LCCN: GetIdentifier(document.Identifiers, "lccn"),
OCLCNumber: GetIdentifier(document.Identifiers, "oclc"),
OpenLibraryId: GetIdentifier(document.Identifiers, "openlibrary"),
LibraryThingId: null,
GoogleBooksId: GetIdentifier(document.Identifiers, "google", "googlebooks"),
BarnesAndNobleId: null,
AppleBooksId: null,
Isbns: BuildIsbns(document.Identifiers),
Contributors: BuildContributors(document.Creators, document.Contributors),
Ratings: document.Rating is null ? null : [new BookRatingDto(Value: document.Rating, MaxValue: 10m, Source: BookRatingSource.Calibre, VoteCount: null)],
CoverImagePath: null
);
}
/// <summary>
/// Builds the release information of the book from its publication date.
/// </summary>
/// <param name="publishDate">The publication date of the book.</param>
/// <returns>The release information of the book, always present even when the publication date is missing.</returns>
private static ReleaseInfoDto BuildReleaseInfo(DateTimeOffset? publishDate)
{
// the release info must always be present, even when the publication date is missing, so that the metadata can be applied to the book
if (publishDate is null)
{
return new ReleaseInfoDto(
OriginalReleaseDate: null,
OriginalReleaseYear: null,
ReReleaseDate: null,
ReReleaseYear: null,
ReleaseCountry: null,
ReleaseVersion: null
);
}
DateOnly? releaseDate = DateOnly.FromDateTime(publishDate.Value.Date);
return new ReleaseInfoDto(
OriginalReleaseDate: releaseDate,
OriginalReleaseYear: releaseDate?.Year,
ReReleaseDate: null,
ReReleaseYear: null,
ReleaseCountry: null,
ReleaseVersion: null
);
}
/// <summary>
/// Maps the ISBN identifiers of the book into ISBN DTOs, de-duplicating normalized values.
/// </summary>
/// <param name="identifiers">The identifiers read from the OPF file.</param>
/// <returns>The mapped and de-duplicated ISBN DTOs.</returns>
private static List<IsbnDto> BuildIsbns(List<OpfIdentifierDto> identifiers)
{
List<IsbnDto> result = [];
HashSet<string> seen = new(StringComparer.OrdinalIgnoreCase);
foreach (OpfIdentifierDto identifier in identifiers.Where(identifier => string.Equals(identifier.Scheme, "isbn", StringComparison.OrdinalIgnoreCase)))
{
string? normalized = NormalizeIsbn(identifier.Value);
if (normalized is null || !seen.Add(normalized))
continue;
result.Add(new IsbnDto(Value: normalized, Format: normalized.Length == 10 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13));
}
return result;
}
/// <summary>
/// Maps the creators and contributors of the book into contributor DTOs, de-duplicating identical name and role pairs.
/// </summary>
/// <param name="creators">The creators read from the OPF file.</param>
/// <param name="contributors">The contributors read from the OPF file.</param>
/// <returns>The mapped contributor DTOs.</returns>
private static List<MediaContributorDto> BuildContributors(List<OpfCreatorDto> creators, List<OpfContributorDto> contributors)
{
List<MediaContributorDto> result = [];
HashSet<string> seen = new(StringComparer.OrdinalIgnoreCase);
void Add(string? displayName, string role, string category)
{
if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}"))
return;
result.Add(new MediaContributorDto(
Name: new MediaContributorNameDto(DisplayName: displayName.Trim(), LegalName: null),
Role: new MediaContributorRoleDto(Name: role, Category: category))
);
}
foreach (OpfCreatorDto creator in creators)
Add(creator.Name, "Author", "Writing");
foreach (OpfContributorDto contributor in contributors)
Add(contributor.Name, MapContributorRole(contributor.Role), MapContributorCategory(contributor.Role));
return result;
}
/// <summary>
/// Maps a language code into a language info DTO by matching it against known cultures.
/// </summary>
/// <param name="rawCode">The raw language code to map.</param>
/// <returns>The mapped language info, or <see langword="null"/> when the code is empty.</returns>
private static LanguageInfoDto? MapLanguage(string? rawCode)
{
if (string.IsNullOrWhiteSpace(rawCode))
return null;
string code = rawCode.Trim().ToLowerInvariant();
IEnumerable<CultureInfo> cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
.Concat(CultureInfo.GetCultures(CultureTypes.NeutralCultures));
CultureInfo? culture = cultures.FirstOrDefault(candidate =>
string.Equals(candidate.TwoLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase) ||
string.Equals(candidate.ThreeLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase));
return culture is null
? new LanguageInfoDto(LanguageCode: code, LanguageName: code, NativeName: null)
: new LanguageInfoDto(LanguageCode: culture.TwoLetterISOLanguageName, LanguageName: culture.EnglishName, NativeName: culture.NativeName);
}
/// <summary>
/// Strips the HTML markup of a description, leaving the text content.
/// </summary>
/// <param name="value">The HTML value to strip.</param>
/// <returns>The text content, or <see langword="null"/> when the value is empty.</returns>
private static string? StripHtml(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
string decoded = WebUtility.HtmlDecode(value);
string withoutTags = Regex.Replace(decoded, "<[^>]+>", " ");
string collapsed = Regex.Replace(withoutTags, @"\s+", " ").Trim();
return collapsed.Length == 0 ? null : collapsed;
}
/// <summary>
/// Normalizes an ISBN into its canonical form without separators or whitespace.
/// </summary>
/// <param name="isbn">The ISBN to normalize.</param>
/// <returns>The normalized ISBN, or <see langword="null"/> when the value is not a valid ISBN.</returns>
private static string? NormalizeIsbn(string isbn)
{
string normalized = new string([.. isbn.Where(character => character is not '-' && !char.IsWhiteSpace(character))]).ToUpperInvariant();
// valid ISBNs must be 10 or 13 characters in length, all characters except the last one must be digits, and the last one must be a digit for ISBN-13 and X for ISBN-10
if ((normalized.Length != 10 && normalized.Length != 13) ||
normalized[..^1].Any(character => !char.IsDigit(character)) ||
(!char.IsDigit(normalized[^1]) && !(normalized.Length == 10 && normalized[^1] == 'X')))
return null;
return normalized;
}
/// <summary>
/// Gets the value of the first identifier whose scheme matches one of the <paramref name="schemes"/>.
/// </summary>
/// <param name="identifiers">The identifiers read from the OPF file.</param>
/// <param name="schemes">The identifier schemes to try, in order.</param>
/// <returns>The identifier value, or <see langword="null"/> when no identifier matches.</returns>
private static string? GetIdentifier(List<OpfIdentifierDto> identifiers, params string[] schemes)
{
foreach (OpfIdentifierDto identifier in identifiers)
if (schemes.Any(scheme => string.Equals(identifier.Scheme, scheme, StringComparison.OrdinalIgnoreCase)))
return identifier.Value;
return null;
}
/// <summary>
/// Maps a creator or contributor role code into a role name.
/// </summary>
/// <param name="role">The role code to map.</param>
/// <returns>The mapped role name.</returns>
private static string MapContributorRole(string? role)
{
return string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) ? "Author" : string.IsNullOrWhiteSpace(role) ? "Contributor" : role;
}
/// <summary>
/// Maps a creator or contributor role code into a contributor category.
/// </summary>
/// <param name="role">The role code to map.</param>
/// <returns>The mapped contributor category.</returns>
private static string MapContributorCategory(string? role)
{
if (string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) || role?.Contains("author", StringComparison.OrdinalIgnoreCase) == true)
return "Writing";
if (string.Equals(role, "ill", StringComparison.OrdinalIgnoreCase))
return "Art";
if (string.Equals(role, "trl", StringComparison.OrdinalIgnoreCase))
return "Translation";
if (string.Equals(role, "bkp", StringComparison.OrdinalIgnoreCase))
return "Production";
return "Other";
}
}
@@ -0,0 +1,158 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
#endregion
namespace Lumina.Plugins.Calibre.Core.Opf;
/// <summary>
/// Reads the metadata of a book from a Calibre OPF file.
/// </summary>
internal static class OpfReader
{
private const long MAX_OPF_FILE_SIZE_BYTES = 5 * 1024 * 1024;
private static readonly XNamespace s_opfNamespace = "http://www.idpf.org/2007/opf";
private static readonly XNamespace s_dcNamespace = "http://purl.org/dc/elements/1.1/";
/// <summary>
/// Reads the metadata of the book from the OPF file at <paramref name="opfFilePath"/>.
/// </summary>
/// <param name="opfFilePath">The file system path of the OPF file to read.</param>
/// <returns>The metadata read from the OPF file, with the fields that could not be read left empty.</returns>
public static OpfDocumentDto Read(string opfFilePath)
{
OpfDocumentDto document = new();
FileInfo fileInfo = new(opfFilePath);
if (!fileInfo.Exists || fileInfo.Length > MAX_OPF_FILE_SIZE_BYTES)
return document;
try
{
using FileStream fileStream = File.OpenRead(opfFilePath);
// the OPF file is untrusted XML, so DTD processing and external entity resolution are disabled, and the document size is bounded
XmlReaderSettings xmlReaderSettings = new()
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
MaxCharactersInDocument = MAX_OPF_FILE_SIZE_BYTES,
MaxCharactersFromEntities = 0
};
using XmlReader xmlReader = XmlReader.Create(fileStream, xmlReaderSettings);
XDocument xDocument = XDocument.Load(xmlReader, LoadOptions.None);
Parse(xDocument, document);
}
catch (XmlException)
{
// a malformed OPF file must not prevent the enrichment of the book from proceeding
}
return document;
}
/// <summary>
/// Parses the metadata elements of the <paramref name="xDocument"/> into the <paramref name="document"/>.
/// </summary>
/// <param name="xDocument">The parsed OPF document.</param>
/// <param name="document">The model onto which the parsed metadata is written.</param>
private static void Parse(XDocument xDocument, OpfDocumentDto document)
{
XElement? metadata = xDocument.Root?.Element(s_opfNamespace + "metadata");
if (metadata is null)
return;
document.Title = GetElementText(metadata, s_dcNamespace + "title");
document.Description = GetElementText(metadata, s_dcNamespace + "description");
document.Publisher = GetElementText(metadata, s_dcNamespace + "publisher");
document.LanguageCode = GetElementText(metadata, s_dcNamespace + "language");
document.PublishDate = ParseDate(GetElementText(metadata, s_dcNamespace + "date"));
foreach (XElement identifier in metadata.Elements(s_dcNamespace + "identifier"))
{
string? scheme = identifier.Attribute(s_opfNamespace + "scheme")?.Value;
if (!string.IsNullOrWhiteSpace(scheme) && !string.IsNullOrWhiteSpace(identifier.Value))
document.Identifiers.Add(new OpfIdentifierDto(Scheme: scheme.Trim(), Value: identifier.Value.Trim()));
}
foreach (XElement subject in metadata.Elements(s_dcNamespace + "subject"))
if (!string.IsNullOrWhiteSpace(subject.Value))
document.Subjects.Add(subject.Value.Trim());
foreach (XElement creator in metadata.Elements(s_dcNamespace + "creator"))
if (!string.IsNullOrWhiteSpace(creator.Value))
document.Creators.Add(new OpfCreatorDto(Name: creator.Value.Trim(), Role: creator.Attribute(s_opfNamespace + "role")?.Value?.Trim()));
foreach (XElement contributor in metadata.Elements(s_dcNamespace + "contributor"))
if (!string.IsNullOrWhiteSpace(contributor.Value))
document.Contributors.Add(new OpfContributorDto(Name: contributor.Value.Trim(), Role: contributor.Attribute(s_opfNamespace + "role")?.Value?.Trim()));
foreach (XElement meta in metadata.Elements(s_opfNamespace + "meta"))
{
string? name = meta.Attribute("name")?.Value;
string? content = meta.Attribute("content")?.Value;
if (name is null || content is null)
continue;
if (string.Equals(name, "calibre:series", StringComparison.OrdinalIgnoreCase))
document.Series = content.Trim();
else if (string.Equals(name, "calibre:series_index", StringComparison.OrdinalIgnoreCase))
document.SeriesIndex = ParseDouble(content);
else if (string.Equals(name, "calibre:rating", StringComparison.OrdinalIgnoreCase))
document.Rating = ParseInt(content);
}
XElement? coverReference = xDocument.Root
?.Element(s_opfNamespace + "guide")
?.Elements(s_opfNamespace + "reference")
.FirstOrDefault(reference => string.Equals(reference.Attribute("type")?.Value, "cover", StringComparison.OrdinalIgnoreCase));
document.CoverHref = coverReference?.Attribute("href")?.Value;
}
/// <summary>
/// Gets the trimmed text of the child element with the specified <paramref name="name"/> of the <paramref name="parent"/> element.
/// </summary>
/// <param name="parent">The parent element.</param>
/// <param name="name">The name of the child element.</param>
/// <returns>The trimmed text, or <see langword="null"/> when the element is missing or empty.</returns>
private static string? GetElementText(XElement parent, XName name)
{
string? value = parent.Element(name)?.Value;
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
/// <summary>
/// Parses a date string into a <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="value">The date string to parse.</param>
/// <returns>The parsed date, or <see langword="null"/> when the string is empty or cannot be parsed.</returns>
private static DateTimeOffset? ParseDate(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
return DateTimeOffset.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTimeOffset result) ? result : null;
}
/// <summary>
/// Parses a double string.
/// </summary>
/// <param name="value">The string to parse.</param>
/// <returns>The parsed value, or <see langword="null"/> when the string is empty or cannot be parsed.</returns>
private static double? ParseDouble(string value)
{
return double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result) ? result : null;
}
/// <summary>
/// Parses an integer string.
/// </summary>
/// <param name="value">The string to parse.</param>
/// <returns>The parsed value, or <see langword="null"/> when the string is empty or cannot be parsed.</returns>
private static int? ParseInt(string value)
{
return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int result) ? result : null;
}
}
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
</Target>
<ItemGroup>
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
<Private>false</Private>
<ExcludeAssets>runtime</ExcludeAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
@@ -0,0 +1,4 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.Fixtures")]