#region ========================================================================= USING ===================================================================================== using Nemera.Contracts.DTO.Common; using Nemera.Contracts.DTO.MediaContributors; using Nemera.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Nemera.Domain.SharedKernel.Common.Enums.BookLibrary; using Nemera.Domain.SharedKernel.Common.Enums.MediaContributors; using Nemera.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 Nemera.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, MediaContributorRole role) { if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}")) return; result.Add(new MediaContributorDto( Name: new MediaContributorNameDto(DisplayName: displayName.Trim(), LegalName: null), Role: role) ); } foreach (OpfCreatorDto creator in creators) Add(creator.Name, MediaContributorRole.Author); foreach (OpfContributorDto contributor in contributors) Add(contributor.Name, MapContributorRole(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 the canonical role. /// /// The role code to map. /// The canonical role. private static MediaContributorRole MapContributorRole(string? role) { if (string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) || role?.Contains("author", StringComparison.OrdinalIgnoreCase) == true) return MediaContributorRole.Author; if (string.Equals(role, "ill", StringComparison.OrdinalIgnoreCase)) return MediaContributorRole.Illustrator; if (string.Equals(role, "trl", StringComparison.OrdinalIgnoreCase)) return MediaContributorRole.Translator; if (string.Equals(role, "bkp", StringComparison.OrdinalIgnoreCase)) return MediaContributorRole.Publisher; return MediaContributorRole.Other; } }