Refactors the book, artist, and album slices across the stack

This commit is contained in:
BinaryAlley committed 2026-09-17 13:30:48 -07:00
1 parent 8aaf9fe64e
commit ea6eb9f796
439 files changed
+28235 -3156

No files matched your search

@@ -1,7 +1,6 @@
#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.Domain.SharedKernel.Common.Enums.MediaContributors;
@@ -68,7 +67,7 @@ internal static class CalibreMapper
/// <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
// 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(
@@ -124,20 +123,20 @@ internal static class CalibreMapper
List<MediaContributorDto> result = [];
HashSet<string> seen = new(StringComparer.OrdinalIgnoreCase);
void Add(string? displayName, string role, MediaContributorRoleCategory category)
void Add(string? displayName, MediaContributorRole role)
{
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))
Role: role)
);
}
foreach (OpfCreatorDto creator in creators)
Add(creator.Name, "Author", MediaContributorRoleCategory.Author);
Add(creator.Name, MediaContributorRole.Author);
foreach (OpfContributorDto contributor in contributors)
Add(contributor.Name, MapContributorRole(contributor.Role), MapContributorCategory(contributor.Role));
Add(contributor.Name, MapContributorRole(contributor.Role));
return result;
}
@@ -189,7 +188,7 @@ internal static class CalibreMapper
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
// 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')))
@@ -214,30 +213,20 @@ internal static class CalibreMapper
}
/// <summary>
/// Maps a creator or contributor role code into a role name.
/// Maps a creator or contributor role code into the canonical role.
/// </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 the canonical category of the role.
/// </summary>
/// <param name="role">The role code to map.</param>
/// <returns>The canonical category of the role.</returns>
private static MediaContributorRoleCategory MapContributorCategory(string? role)
/// <returns>The canonical role.</returns>
private static MediaContributorRole MapContributorRole(string? role)
{
if (string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) || role?.Contains("author", StringComparison.OrdinalIgnoreCase) == true)
return MediaContributorRoleCategory.Author;
return MediaContributorRole.Author;
if (string.Equals(role, "ill", StringComparison.OrdinalIgnoreCase))
return MediaContributorRoleCategory.Illustrator;
return MediaContributorRole.Illustrator;
if (string.Equals(role, "trl", StringComparison.OrdinalIgnoreCase))
return MediaContributorRoleCategory.Translator;
return MediaContributorRole.Translator;
if (string.Equals(role, "bkp", StringComparison.OrdinalIgnoreCase))
return MediaContributorRoleCategory.Publisher;
return MediaContributorRoleCategory.Other;
return MediaContributorRole.Publisher;
return MediaContributorRole.Other;
}
}
@@ -59,8 +59,8 @@ internal static partial class OpenLibraryMapper
/// <param name="authors">The authors of the book.</param>
/// <param name="ratings">The ratings of the book, or <see langword="null"/> when no ratings were found.</param>
/// <param name="fallback">The search document used as a fallback source of data, or <see langword="null"/>.</param>
/// <returns>The mapped book request.</returns>
public static AddBookRequest MapDetailed(
/// <returns>The mapped book metadata.</returns>
public static BookMetadataDto MapDetailed(
BookMetadataLookupDto lookup,
OpenLibraryEditionResponse? edition,
OpenLibraryWorkResponse? work,
@@ -99,26 +99,23 @@ internal static partial class OpenLibraryMapper
string? releaseCountry = edition?.PublishPlaces.FirstOrDefault() ?? fallback?.PublishPlaces.FirstOrDefault();
string? releaseVersion = edition?.EditionName;
return new AddBookRequest(
lookup.LibraryId,
lookup.Path,
new WrittenContentMetadataDto(
title,
work?.OriginalTitle,
description,
new ReleaseInfoDto(
originalRelease.Date,
originalYear,
editionRelease.Date,
editionRelease.Date?.Year ?? editionRelease.Year,
MapReleaseCountry(releaseCountry),
NullIfWhiteSpace(releaseVersion)),
[.. genreNames.Select(name => new GenreDto(name))],
[.. subjects.Select(name => new TagDto(name))],
MapLanguage(currentLanguageCode),
MapLanguage(originalLanguageCode),
edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(),
edition?.NumberOfPages ?? fallback?.NumberOfPagesMedian),
return new BookMetadataDto(
title,
work?.OriginalTitle,
description,
new ReleaseInfoDto(
originalRelease.Date,
originalYear,
editionRelease.Date,
editionRelease.Date?.Year ?? editionRelease.Year,
MapReleaseCountry(releaseCountry),
NullIfWhiteSpace(releaseVersion)),
[.. genreNames.Select(name => new GenreDto(name))],
[.. subjects.Select(name => new TagDto(name))],
MapLanguage(currentLanguageCode),
MapLanguage(originalLanguageCode),
edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(),
edition?.NumberOfPages ?? fallback?.NumberOfPagesMedian,
MapFormat(edition?.PhysicalFormat),
NullIfWhiteSpace(edition?.EditionName),
ParseVolumeNumber(edition?.Volume, edition?.Series.FirstOrDefault()),
@@ -134,7 +131,8 @@ internal static partial class OpenLibraryMapper
NullIfWhiteSpace(appleBooksId),
isbns,
contributors,
mappedRatings);
mappedRatings,
CoverImagePath: null);
}
/// <summary>
@@ -142,8 +140,8 @@ internal static partial class OpenLibraryMapper
/// </summary>
/// <param name="lookup">The lookup describing the book to map.</param>
/// <param name="document">The search document to map.</param>
/// <returns>The mapped book request candidate.</returns>
public static AddBookRequest MapSearchCandidate(BookMetadataLookupDto lookup, OpenLibrarySearchDocumentResponse document)
/// <returns>The mapped book metadata candidate.</returns>
public static BookMetadataDto MapSearchCandidate(BookMetadataLookupDto lookup, OpenLibrarySearchDocumentResponse document)
{
return MapDetailed(lookup, null, null, [], null, document);
}
@@ -274,24 +272,24 @@ internal static partial class OpenLibraryMapper
List<MediaContributorDto> result = [];
HashSet<string> seen = new(StringComparer.OrdinalIgnoreCase);
void Add(string? displayName, string? legalName, string role, MediaContributorRoleCategory category)
void Add(string? displayName, string? legalName, MediaContributorRole role)
{
if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}"))
return;
result.Add(new MediaContributorDto(new MediaContributorNameDto(displayName.Trim(), NullIfWhiteSpace(legalName)), new MediaContributorRoleDto(role, category)));
result.Add(new MediaContributorDto(new MediaContributorNameDto(displayName.Trim(), NullIfWhiteSpace(legalName)), role));
}
foreach (OpenLibraryAuthorResponse author in authors)
Add(author.Name, author.PersonalName, "Author", MediaContributorRoleCategory.Author);
Add(author.Name, author.PersonalName, MediaContributorRole.Author);
foreach (string authorName in fallbackAuthors ?? [])
Add(authorName, null, "Author", MediaContributorRoleCategory.Author);
Add(authorName, null, MediaContributorRole.Author);
foreach (string contribution in contributions ?? [])
{
Match match = ContributorPattern().Match(contribution);
string name = match.Success ? match.Groups["name"].Value.Trim() : contribution.Trim();
string role = match.Success ? match.Groups["role"].Value.Trim() : "Contributor";
Add(name, null, role, ContributorCategory(role));
string role = match.Success ? match.Groups["role"].Value.Trim() : string.Empty;
Add(name, null, ContributorRole(role));
}
return result;
}
@@ -505,24 +503,24 @@ internal static partial class OpenLibraryMapper
}
/// <summary>
/// Maps a contribution role into the canonical category of the role.
/// Maps a contribution role into the canonical role.
/// </summary>
/// <param name="role">The role to categorize.</param>
/// <returns>The canonical category of the role.</returns>
private static MediaContributorRoleCategory ContributorCategory(string role)
/// <param name="role">The role to map.</param>
/// <returns>The canonical role.</returns>
private static MediaContributorRole ContributorRole(string role)
{
if (role.Contains("illustr", StringComparison.OrdinalIgnoreCase) ||
role.Contains("artist", StringComparison.OrdinalIgnoreCase))
return MediaContributorRoleCategory.Illustrator;
return MediaContributorRole.Illustrator;
if (role.Contains("translat", StringComparison.OrdinalIgnoreCase))
return MediaContributorRoleCategory.Translator;
return MediaContributorRole.Translator;
if (role.Contains("narrat", StringComparison.OrdinalIgnoreCase))
return MediaContributorRoleCategory.Narrator;
return MediaContributorRole.Narrator;
if (role.Contains("edit", StringComparison.OrdinalIgnoreCase) ||
role.Contains("author", StringComparison.OrdinalIgnoreCase) ||
role.Contains("writer", StringComparison.OrdinalIgnoreCase))
return MediaContributorRoleCategory.Author;
return MediaContributorRoleCategory.Other;
return MediaContributorRole.Author;
return MediaContributorRole.Other;
}
/// <summary>
@@ -65,75 +65,15 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMe
if (!string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) || !string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId))
{
AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
return exactBookRequestMatch is null ? [] : [new BookMetadataDto(
exactBookRequestMatch.Metadata?.Title,
exactBookRequestMatch.Metadata?.OriginalTitle,
exactBookRequestMatch.Metadata?.Description,
exactBookRequestMatch.Metadata?.ReleaseInfo,
exactBookRequestMatch.Metadata?.Genres,
exactBookRequestMatch.Metadata?.Tags,
exactBookRequestMatch.Metadata?.Language,
exactBookRequestMatch.Metadata?.OriginalLanguage,
exactBookRequestMatch.Metadata?.Publisher,
exactBookRequestMatch.Metadata?.PageCount,
exactBookRequestMatch.Format,
exactBookRequestMatch.Edition,
exactBookRequestMatch.VolumeNumber,
exactBookRequestMatch.Series,
exactBookRequestMatch.ASIN,
exactBookRequestMatch.GoodreadsId,
exactBookRequestMatch.LCCN,
exactBookRequestMatch.OCLCNumber,
exactBookRequestMatch.OpenLibraryId,
exactBookRequestMatch.LibraryThingId,
exactBookRequestMatch.GoogleBooksId,
exactBookRequestMatch.BarnesAndNobleId,
exactBookRequestMatch.AppleBooksId,
exactBookRequestMatch.ISBNs,
exactBookRequestMatch.Contributors,
exactBookRequestMatch.Ratings,
CoverImagePath: null
)];
BookMetadataDto? exactBookMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
return exactBookMatch is null ? [] : [exactBookMatch];
}
IReadOnlyList<OpenLibrarySearchDocumentResponse> openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
return [.. openLibrarySearchDocuments
.Where(openLibrarySearchDocument => !string.IsNullOrWhiteSpace(openLibrarySearchDocument.Title))
.Select(openLibrarySearchDocument =>
{
AddBookRequest addBookRequest = OpenLibraryMapper.MapSearchCandidate(bookMetadataLookup, openLibrarySearchDocument);
return new BookMetadataDto(
addBookRequest.Metadata?.Title,
addBookRequest.Metadata?.OriginalTitle,
addBookRequest.Metadata?.Description,
addBookRequest.Metadata?.ReleaseInfo,
addBookRequest.Metadata?.Genres,
addBookRequest.Metadata?.Tags,
addBookRequest.Metadata?.Language,
addBookRequest.Metadata?.OriginalLanguage,
addBookRequest.Metadata?.Publisher,
addBookRequest.Metadata?.PageCount,
addBookRequest.Format,
addBookRequest.Edition,
addBookRequest.VolumeNumber,
addBookRequest.Series,
addBookRequest.ASIN,
addBookRequest.GoodreadsId,
addBookRequest.LCCN,
addBookRequest.OCLCNumber,
addBookRequest.OpenLibraryId,
addBookRequest.LibraryThingId,
addBookRequest.GoogleBooksId,
addBookRequest.BarnesAndNobleId,
addBookRequest.AppleBooksId,
addBookRequest.ISBNs,
addBookRequest.Contributors,
addBookRequest.Ratings,
CoverImagePath: null
);
})];
.Select(openLibrarySearchDocument => OpenLibraryMapper.MapSearchCandidate(bookMetadataLookup, openLibrarySearchDocument))];
}
/// <summary>
@@ -144,45 +84,16 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMe
/// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found.</returns>
public async Task<BookMetadataDto?> GetMetadataAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
{
AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
return exactBookRequestMatch is null ? null : new BookMetadataDto(
exactBookRequestMatch.Metadata?.Title,
exactBookRequestMatch.Metadata?.OriginalTitle,
exactBookRequestMatch.Metadata?.Description,
exactBookRequestMatch.Metadata?.ReleaseInfo,
exactBookRequestMatch.Metadata?.Genres,
exactBookRequestMatch.Metadata?.Tags,
exactBookRequestMatch.Metadata?.Language,
exactBookRequestMatch.Metadata?.OriginalLanguage,
exactBookRequestMatch.Metadata?.Publisher,
exactBookRequestMatch.Metadata?.PageCount,
exactBookRequestMatch.Format,
exactBookRequestMatch.Edition,
exactBookRequestMatch.VolumeNumber,
exactBookRequestMatch.Series,
exactBookRequestMatch.ASIN,
exactBookRequestMatch.GoodreadsId,
exactBookRequestMatch.LCCN,
exactBookRequestMatch.OCLCNumber,
exactBookRequestMatch.OpenLibraryId,
exactBookRequestMatch.LibraryThingId,
exactBookRequestMatch.GoogleBooksId,
exactBookRequestMatch.BarnesAndNobleId,
exactBookRequestMatch.AppleBooksId,
exactBookRequestMatch.ISBNs,
exactBookRequestMatch.Contributors,
exactBookRequestMatch.Ratings,
CoverImagePath: null
);
return await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Resolves the lookup into a full book request by combining edition, work, author, and rating data from Open Library.
/// Resolves the lookup into full book metadata by combining edition, work, author, and rating data from Open Library.
/// </summary>
/// <param name="bookMetadataLookup">The lookup describing the book to resolve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The resolved book request, or <see langword="null"/> when no matching book was found.</returns>
public async Task<AddBookRequest?> GetBookAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken = default)
/// <returns>The resolved book metadata, or <see langword="null"/> when no matching book was found.</returns>
public async Task<BookMetadataDto?> GetBookAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken = default)
{
ValidateLookup(bookMetadataLookup);