From e26ac45ae9f780943ddad86773ca45f265d53e3d Mon Sep 17 00:00:00 2001 From: Jadehawk <333657+jadehawk@users.noreply.github.com> Date: Sat, 28 Feb 2026 18:15:55 -0500 Subject: [PATCH] fix(epub): restore Calibre extraction, add age/content rating, fix BookDrop metadata loss (#3114) Restores and extends the EPUB metadata extraction work from PR #1879 with additional fixes for field mapping gaps found in the processor, BookDrop finalization, and JSON sidecar. EPUB Metadata Extractor (EpubMetadataExtractor.java) - Restore Calibre user_metadata iteration that was regressed: now iterates elements and maps custom columns via CALIBRE_FIELD_MAPPINGS - Add #age_rating and #content_rating to CALIBRE_FIELD_MAPPINGS so Calibre-managed rating/rating string fields are imported - Add CALIBRE_IDENTIFIER_PREFIXES map for calibre: identifier fallback (hardcover_book, lubimyczytac, ranobedb, etc.) - Support both read paths: booklore: namespace (round-trip) and Calibre user_metadata (first import from Calibre library) - Validate age_rating values against VALID_AGE_RATINGS whitelist EPUB Metadata Writer (EpubMetadataWriter.java) - Write booklore:age_rating and booklore:content_rating to the OPF so values survive a round-trip rescan Metadata Change Detector (MetadataChangeDetector.java) - Mark ageRating and contentRating as includedInFileWrite=true so saving either field triggers a write-back to the EPUB file EPUB Processor (EpubProcessor.java) - Map extracted ageRating and contentRating from BookMetadata DTO into BookMetadataEntity in setBookMetadata(); these two lines were the silent reason values never reached the DB on library scan BookDrop Service (BookDropService.java) - Change processMovedFile() from REPLACE_ALL to REPLACE_WHEN_PROVIDED when applying bookdrop review metadata after file extraction. REPLACE_ALL unconditionally calls the setter even with null, wiping ageRating/contentRating that EpubProcessor just extracted from the file. REPLACE_WHEN_PROVIDED skips null fields and preserves the file-extracted values when the bookdrop review form does not submit those fields. JSON Sidecar (SidecarIdentifiers.java, SidecarMetadataMapper.java) - Add missing hardcoverBookId field to SidecarIdentifiers DTO - Write hardcoverBookId in buildIdentifiers() (toSidecarMetadata path) - Read hardcoverBookId in toBookMetadata() (sidecar import path) All other identifiers were already present; hardcoverBookId was the only one absent from all three locations simultaneously. Tests (EpubMetadataExtractorTest.java) - Add comprehensive test coverage for both extraction paths: booklore: namespace (round-trip) and Calibre user_metadata/ identifier extraction including age_rating and content_rating --- .../model/dto/sidecar/SidecarIdentifiers.java | 1 + .../service/bookdrop/BookDropService.java | 2 +- .../service/fileprocessor/EpubProcessor.java | 2 + .../extractor/EpubMetadataExtractor.java | 122 +++- .../sidecar/SidecarMetadataMapper.java | 2 + .../metadata/writer/EpubMetadataWriter.java | 8 + .../booklore/util/MetadataChangeDetector.java | 4 +- .../extractor/EpubMetadataExtractorTest.java | 649 +++++++++++++++++- 8 files changed, 747 insertions(+), 43 deletions(-) diff --git a/booklore-api/src/main/java/org/booklore/model/dto/sidecar/SidecarIdentifiers.java b/booklore-api/src/main/java/org/booklore/model/dto/sidecar/SidecarIdentifiers.java index 12f788caf..cbf912e5c 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/sidecar/SidecarIdentifiers.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/sidecar/SidecarIdentifiers.java @@ -16,6 +16,7 @@ public class SidecarIdentifiers { private String goodreadsId; private String googleId; private String hardcoverId; + private String hardcoverBookId; private String comicvineId; private String lubimyczytacId; private String ranobedbId; diff --git a/booklore-api/src/main/java/org/booklore/service/bookdrop/BookDropService.java b/booklore-api/src/main/java/org/booklore/service/bookdrop/BookDropService.java index 4df882686..015f757db 100644 --- a/booklore-api/src/main/java/org/booklore/service/bookdrop/BookDropService.java +++ b/booklore-api/src/main/java/org/booklore/service/bookdrop/BookDropService.java @@ -476,7 +476,7 @@ public class BookDropService { .build()) .updateThumbnail(metadata.getThumbnailUrl() != null) .mergeCategories(false) - .replaceMode(MetadataReplaceMode.REPLACE_ALL) + .replaceMode(MetadataReplaceMode.REPLACE_WHEN_PROVIDED) .mergeMoods(true) .mergeTags(true) .build(); diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/EpubProcessor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/EpubProcessor.java index 633ff89d5..52b8dc629 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/EpubProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/EpubProcessor.java @@ -136,6 +136,8 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc metadata.setLubimyczytacRating(epubMetadata.getLubimyczytacRating()); metadata.setRanobedbId(truncate(epubMetadata.getRanobedbId(), 100)); metadata.setRanobedbRating(epubMetadata.getRanobedbRating()); + metadata.setAgeRating(epubMetadata.getAgeRating()); + metadata.setContentRating(truncate(epubMetadata.getContentRating(), 20)); bookCreatorService.addAuthorsToBook(epubMetadata.getAuthors(), bookEntity); diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/EpubMetadataExtractor.java b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/EpubMetadataExtractor.java index e88c1b9f3..b528c294c 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/EpubMetadataExtractor.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/EpubMetadataExtractor.java @@ -31,6 +31,7 @@ import java.time.LocalDate; import java.time.OffsetDateTime; import java.util.*; import java.util.regex.Pattern; +import java.util.function.BiConsumer; import java.util.stream.Collectors; @Slf4j @@ -45,11 +46,47 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { private static final List MEDIA_TYPES = new ArrayList<>(); private static final Pattern ISBN_SEPARATOR_PATTERN = Pattern.compile("[- ]"); + private static final Set VALID_AGE_RATINGS = Set.of(0, 6, 10, 13, 16, 18, 21); + static { MEDIA_TYPES.addAll(Arrays.asList(MediaTypes.mediaTypes)); MEDIA_TYPES.add(null); } + private static final Map> CALIBRE_IDENTIFIER_PREFIXES = Map.of( + "amazon", BookMetadata.BookMetadataBuilder::asin, + "asin", BookMetadata.BookMetadataBuilder::asin, + "mobi-asin", BookMetadata.BookMetadataBuilder::asin, + "goodreads", BookMetadata.BookMetadataBuilder::goodreadsId, + "google", BookMetadata.BookMetadataBuilder::googleId, + "hardcover", BookMetadata.BookMetadataBuilder::hardcoverId, + "hardcover_book", BookMetadata.BookMetadataBuilder::hardcoverBookId, + "comicvine", BookMetadata.BookMetadataBuilder::comicvineId, + "lubimyczytac", BookMetadata.BookMetadataBuilder::lubimyczytacId, + "ranobedb", BookMetadata.BookMetadataBuilder::ranobedbId); + + private static final Map> CALIBRE_FIELD_MAPPINGS = Map.ofEntries( + Map.entry("#subtitle", BookMetadata.BookMetadataBuilder::subtitle), + Map.entry("#pagecount", (builder, value) -> safeParseInt(value, builder::pageCount)), + Map.entry("#series_total", (builder, value) -> safeParseInt(value, builder::seriesTotal)), + Map.entry("#amazon_rating", (builder, value) -> safeParseDouble(value, builder::amazonRating)), + Map.entry("#amazon_review_count", (builder, value) -> safeParseInt(value, builder::amazonReviewCount)), + Map.entry("#goodreads_rating", (builder, value) -> safeParseDouble(value, builder::goodreadsRating)), + Map.entry("#goodreads_review_count", (builder, value) -> safeParseInt(value, builder::goodreadsReviewCount)), + Map.entry("#hardcover_rating", (builder, value) -> safeParseDouble(value, builder::hardcoverRating)), + Map.entry("#hardcover_review_count", (builder, value) -> safeParseInt(value, builder::hardcoverReviewCount)), + Map.entry("#lubimyczytac_rating", (builder, value) -> safeParseDouble(value, builder::lubimyczytacRating)), + Map.entry("#ranobedb_rating", (builder, value) -> safeParseDouble(value, builder::ranobedbRating)), + Map.entry("#age_rating", (builder, value) -> safeParseInt(value, v -> { + if (VALID_AGE_RATINGS.contains(v)) builder.ageRating(v); + })), + Map.entry("#content_rating", (builder, value) -> { + String normalized = value.trim().toUpperCase(); + if (Set.of("EVERYONE", "TEEN", "MATURE", "ADULT", "EXPLICIT").contains(normalized)) { + builder.contentRating(normalized); + } + })); + @Override public byte[] extractCover(File epubFile) { Book epub = null; @@ -196,6 +233,8 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { BookMetadata.BookMetadataBuilder builderMeta = BookMetadata.builder(); Set categories = new HashSet<>(); + Set moods = new HashSet<>(); + Set tags = new HashSet<>(); boolean seriesFound = false; boolean seriesIndexFound = false; @@ -262,11 +301,9 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { } } else if ("calibre:user_metadata".equals(prop)) { try { - JSONObject jsonroot = new JSONObject(content); - JSONObject pages = jsonroot.getJSONObject("#pagecount"); - Object value = pages.opt("#value#"); - safeParseInt(String.valueOf(value), builderMeta::pageCount); - } catch (JSONException ignored) { + extractCalibreUserMetadata(new JSONObject(content), builderMeta, moods, tags); + } catch (JSONException e) { + log.warn("Failed to parse Calibre user_metadata JSON: {}", e.getMessage()); } } @@ -286,18 +323,23 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { else if (key.equals(BookLoreMetadata.NS_PREFIX + ":series_total")) safeParseInt(content, builderMeta::seriesTotal); else if (key.equals(BookLoreMetadata.NS_PREFIX + ":rating")) { /* Generic rating not supported */ } else if (key.equals(BookLoreMetadata.NS_PREFIX + ":amazon_rating")) safeParseDouble(content, builderMeta::amazonRating); + else if (key.equals(BookLoreMetadata.NS_PREFIX + ":amazon_review_count")) safeParseInt(content, builderMeta::amazonReviewCount); else if (key.equals(BookLoreMetadata.NS_PREFIX + ":goodreads_rating")) safeParseDouble(content, builderMeta::goodreadsRating); + else if (key.equals(BookLoreMetadata.NS_PREFIX + ":goodreads_review_count")) safeParseInt(content, builderMeta::goodreadsReviewCount); else if (key.equals(BookLoreMetadata.NS_PREFIX + ":hardcover_rating")) safeParseDouble(content, builderMeta::hardcoverRating); + else if (key.equals(BookLoreMetadata.NS_PREFIX + ":hardcover_review_count")) safeParseInt(content, builderMeta::hardcoverReviewCount); else if (key.equals(BookLoreMetadata.NS_PREFIX + ":lubimyczytac_rating")) safeParseDouble(content, builderMeta::lubimyczytacRating); else if (key.equals(BookLoreMetadata.NS_PREFIX + ":ranobedb_rating")) safeParseDouble(content, builderMeta::ranobedbRating); + else if (key.equals(BookLoreMetadata.NS_PREFIX + ":age_rating")) safeParseInt(content, v -> { if (VALID_AGE_RATINGS.contains(v)) builderMeta.ageRating(v); }); + else if (key.equals(BookLoreMetadata.NS_PREFIX + ":content_rating")) builderMeta.contentRating(content); else if (key.equals(BookLoreMetadata.NS_PREFIX + ":moods")) { if (StringUtils.isNotBlank(content)) { - builderMeta.moods(parseJsonArrayOrCsv(content)); + extractSetField(content, moods); } } else if (key.equals(BookLoreMetadata.NS_PREFIX + ":tags")) { if (StringUtils.isNotBlank(content)) { - builderMeta.tags(parseJsonArrayOrCsv(content)); + extractSetField(content, tags); } } } @@ -357,6 +399,19 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { case "HARDCOVERBOOK", "HARDCOVER_BOOK_ID" -> builderMeta.hardcoverBookId(value); case "LUBIMYCZYTAC" -> builderMeta.lubimyczytacId(value); } + } else { + // Handle Calibre's prefix:value format (e.g., amazon:B09XXX, goodreads:123) + int colonIdx = text.indexOf(':'); + if (colonIdx > 0) { + String prefix = text.substring(0, colonIdx).toLowerCase(); + String val = text.substring(colonIdx + 1).trim(); + if (!"calibre".equals(prefix) && !"uuid".equals(prefix)) { + BiConsumer setter = CALIBRE_IDENTIFIER_PREFIXES.get(prefix); + if (setter != null) { + setter.accept(builderMeta, val); + } + } + } } } case "date" -> { @@ -399,12 +454,12 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { builderMeta.authors(creatorsByRole.get("aut")); - // Remove tags and moods from categories to ensure strict separation - BookMetadata intermediate = builderMeta.build(); - Set knownNonCategories = new HashSet<>(); - if (intermediate.getMoods() != null) knownNonCategories.addAll(intermediate.getMoods()); - if (intermediate.getTags() != null) knownNonCategories.addAll(intermediate.getTags()); - categories.removeAll(knownNonCategories); + if (!moods.isEmpty()) builderMeta.moods(moods); + if (!tags.isEmpty()) builderMeta.tags(tags); + + // Remove moods and tags from categories to ensure strict separation + categories.removeAll(moods); + categories.removeAll(tags); builderMeta.categories(categories); @@ -425,20 +480,57 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { } } - private void safeParseInt(String value, java.util.function.IntConsumer setter) { + private static void safeParseInt(String value, java.util.function.IntConsumer setter) { try { setter.accept(Integer.parseInt(value)); } catch (NumberFormatException ignored) { } } - private void safeParseDouble(String value, java.util.function.DoubleConsumer setter) { + private static void safeParseDouble(String value, java.util.function.DoubleConsumer setter) { try { setter.accept(Double.parseDouble(value)); } catch (NumberFormatException ignored) { } } + private void extractSetField(String value, Set targetSet) { + if (StringUtils.isNotBlank(value)) { + targetSet.addAll(parseJsonArrayOrCsv(value)); + } + } + + private void extractCalibreUserMetadata(JSONObject userMetadata, BookMetadata.BookMetadataBuilder builder, + Set moodsSet, Set tagsSet) { + Iterator keys = userMetadata.keys(); + while (keys.hasNext()) { + String fieldName = keys.next(); + try { + JSONObject fieldObj = userMetadata.optJSONObject(fieldName); + if (fieldObj == null) continue; + + Object rawValue = fieldObj.opt("#value#"); + if (rawValue == null) continue; + + String value = String.valueOf(rawValue).trim(); + if (value.isEmpty() || "null".equals(value)) continue; + + if ("#moods".equals(fieldName)) { + extractSetField(value, moodsSet); + } else if ("#extra_tags".equals(fieldName)) { + extractSetField(value, tagsSet); + } else { + BiConsumer mapper = CALIBRE_FIELD_MAPPINGS.get(fieldName); + if (mapper != null) { + mapper.accept(builder, value); + } + } + } catch (Exception e) { + log.debug("Failed to extract Calibre field '{}': {}", fieldName, e.getMessage()); + } + } + } + /** * Parses a string that may be either a JSON array (e.g., ["item1", "item2"]) or a CSV (item1, item2). * Returns a Set of parsed values. diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/sidecar/SidecarMetadataMapper.java b/booklore-api/src/main/java/org/booklore/service/metadata/sidecar/SidecarMetadataMapper.java index b133506fc..e3f1d0f30 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/sidecar/SidecarMetadataMapper.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/sidecar/SidecarMetadataMapper.java @@ -102,6 +102,7 @@ public class SidecarMetadataMapper { .goodreadsId(ids.getGoodreadsId()) .googleId(ids.getGoogleId()) .hardcoverId(ids.getHardcoverId()) + .hardcoverBookId(ids.getHardcoverBookId()) .comicvineId(ids.getComicvineId()) .lubimyczytacId(ids.getLubimyczytacId()) .ranobedbId(ids.getRanobedbId()) @@ -189,6 +190,7 @@ public class SidecarMetadataMapper { .goodreadsId(entity.getGoodreadsId()) .googleId(entity.getGoogleId()) .hardcoverId(entity.getHardcoverId()) + .hardcoverBookId(entity.getHardcoverBookId()) .comicvineId(entity.getComicvineId()) .lubimyczytacId(entity.getLubimyczytacId()) .ranobedbId(entity.getRanobedbId()) diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java b/booklore-api/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java index a532a0825..3369f8e50 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java @@ -871,6 +871,14 @@ public class EpubMetadataWriter implements MetadataWriter { .toList()) + "]"; metadataElement.appendChild(createBookloreMetaElement(doc, "tags", tagsJson)); } + + if (metadata.getAgeRating() != null) { + metadataElement.appendChild(createBookloreMetaElement(doc, "age_rating", String.valueOf(metadata.getAgeRating()))); + } + + if (StringUtils.isNotBlank(metadata.getContentRating())) { + metadataElement.appendChild(createBookloreMetaElement(doc, "content_rating", metadata.getContentRating())); + } } private Element createBookloreMetaElement(Document doc, String property, String value) { diff --git a/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java b/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java index 528c4e9d3..3afa35841 100644 --- a/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java +++ b/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java @@ -220,11 +220,11 @@ public class MetadataChangeDetector { new FieldDescriptor<>("ageRating", BookMetadata::getAgeRating, BookMetadataEntity::getAgeRating, BookMetadata::getAgeRatingLocked, BookMetadataEntity::getAgeRatingLocked, - MetadataClearFlags::isAgeRating, false), + MetadataClearFlags::isAgeRating, true), new FieldDescriptor<>("contentRating", BookMetadata::getContentRating, BookMetadataEntity::getContentRating, BookMetadata::getContentRatingLocked, BookMetadataEntity::getContentRatingLocked, - MetadataClearFlags::isContentRating, false) + MetadataClearFlags::isContentRating, true) ); private static final List COLLECTION_FIELDS = List.of( diff --git a/booklore-api/src/test/java/org/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java b/booklore-api/src/test/java/org/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java index 35242c183..30264be05 100644 --- a/booklore-api/src/test/java/org/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java +++ b/booklore-api/src/test/java/org/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java @@ -285,6 +285,48 @@ class EpubMetadataExtractorTest { ); } + @Test + @DisplayName("Should extract description from EPUB metadata") + void extractMetadata_withDescription_returnsDescription() throws IOException { + String opfContent = """ + + + + Test Book + A great book about testing. + + + """; + File epubFile = createEpubWithOpf(opfContent, "test-desc-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epubFile); + assertNotNull(result); + assertEquals("A great book about testing.", result.getDescription()); + } + + @Test + @DisplayName("Should extract multiple dc:subject categories from EPUB metadata") + void extractMetadata_withCategories_returnsAllCategories() throws IOException { + String opfContent = """ + + + + Test Book + Science Fiction + Adventure + Fantasy + + + """; + File epubFile = createEpubWithOpf(opfContent, "test-cats-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epubFile); + assertNotNull(result); + assertNotNull(result.getCategories()); + assertTrue(result.getCategories().contains("Science Fiction")); + assertTrue(result.getCategories().contains("Adventure")); + assertTrue(result.getCategories().contains("Fantasy")); + assertEquals(3, result.getCategories().size()); + } + @Test @DisplayName("Should use filename as title when title is missing") void extractMetadata_withoutTitle_usesFilename() throws IOException { @@ -345,6 +387,30 @@ class EpubMetadataExtractorTest { () -> assertTrue(result.getSeriesNumber() == null || result.getSeriesNumber() == 0.0f) ); } + + @Test + @DisplayName("Should extract EPUB3 belongs-to-collection series metadata") + void extractMetadata_withEpub3Collection_returnsSeriesInfo() throws IOException { + String opfContent = """ + + + + Test Book + The Wheel of Time + 14 + + + """; + File epubFile = createEpubWithOpf(opfContent, "test-epub3-series-" + System.nanoTime() + ".epub"); + + BookMetadata result = extractor.extractMetadata(epubFile); + + assertAll( + () -> assertNotNull(result), + () -> assertEquals("The Wheel of Time", result.getSeriesName()), + () -> assertEquals(14.0f, result.getSeriesNumber(), 0.001) + ); + } } @Nested @@ -491,6 +557,442 @@ class EpubMetadataExtractorTest { } } + @Nested + @DisplayName("Calibre Identifier Tests") + class CalibreIdentifierTests { + + @Test + @DisplayName("Should extract ASIN from Calibre amazon: prefix identifier") + void extractMetadata_calibreAmazonPrefix_returnsAsin() throws IOException { + String opfContent = """ + + + + Test + amazon:B09QZY6N2K + + + """; + File epub = createEpubWithOpf(opfContent, "test-asin-amazon-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("B09QZY6N2K", result.getAsin()); + } + + @Test + @DisplayName("Should extract ASIN from Calibre asin: prefix identifier") + void extractMetadata_calibreAsinPrefix_returnsAsin() throws IOException { + String opfContent = """ + + + + Test + asin:B09QZY6N2K + + + """; + File epub = createEpubWithOpf(opfContent, "test-asin-prefix-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("B09QZY6N2K", result.getAsin()); + } + + @Test + @DisplayName("Should extract ASIN from mobi-asin: prefix identifier") + void extractMetadata_calibreMobiAsinPrefix_returnsAsin() throws IOException { + String opfContent = """ + + + + Test + mobi-asin:B09QZY6N2K + + + """; + File epub = createEpubWithOpf(opfContent, "test-mobiasin-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("B09QZY6N2K", result.getAsin()); + } + + @Test + @DisplayName("Should extract Goodreads ID from Calibre goodreads: prefix identifier") + void extractMetadata_calibreGoodreadsPrefix_returnsGoodreadsId() throws IOException { + String opfContent = """ + + + + Test + goodreads:60229814 + + + """; + File epub = createEpubWithOpf(opfContent, "test-gr-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("60229814", result.getGoodreadsId()); + } + + @Test + @DisplayName("Should extract Google ID from Calibre google: prefix identifier") + void extractMetadata_calibreGooglePrefix_returnsGoogleId() throws IOException { + String opfContent = """ + + + + Test + google:abc123 + + + """; + File epub = createEpubWithOpf(opfContent, "test-google-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("abc123", result.getGoogleId()); + } + + @Test + @DisplayName("Should extract Hardcover ID from Calibre hardcover: prefix identifier") + void extractMetadata_calibreHardcoverPrefix_returnsHardcoverId() throws IOException { + String opfContent = """ + + + + Test + hardcover:8888 + + + """; + File epub = createEpubWithOpf(opfContent, "test-hc-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("8888", result.getHardcoverId()); + } + + @Test + @DisplayName("Should extract Hardcover Book ID from Calibre hardcover_book: prefix identifier") + void extractMetadata_calibreHardcoverBookPrefix_returnsHardcoverBookId() throws IOException { + String opfContent = """ + + + + Test + hardcover_book:7777 + + + """; + File epub = createEpubWithOpf(opfContent, "test-hcbook-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("7777", result.getHardcoverBookId()); + } + + @Test + @DisplayName("Should extract Comicvine ID from Calibre comicvine: prefix identifier") + void extractMetadata_calibreComicvinePrefix_returnsComicvineId() throws IOException { + String opfContent = """ + + + + Test + comicvine:555 + + + """; + File epub = createEpubWithOpf(opfContent, "test-cv-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("555", result.getComicvineId()); + } + + @Test + @DisplayName("Should extract Lubimyczytac ID from Calibre lubimyczytac: prefix identifier") + void extractMetadata_calibreLubimyczytacPrefix_returnsLubimyczytacId() throws IOException { + String opfContent = """ + + + + Test + lubimyczytac:444 + + + """; + File epub = createEpubWithOpf(opfContent, "test-lubi-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("444", result.getLubimyczytacId()); + } + + @Test + @DisplayName("Should extract Ranobedb ID from Calibre ranobedb: prefix identifier") + void extractMetadata_calibreRanobedbPrefix_returnsRanobedbId() throws IOException { + String opfContent = """ + + + + Test + ranobedb:333 + + + """; + File epub = createEpubWithOpf(opfContent, "test-ranobedb-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("333", result.getRanobedbId()); + } + + @Test + @DisplayName("Should extract ISBN-13 from urn:isbn: URN format") + void extractMetadata_urnIsbn13_returnsIsbn13() throws IOException { + String opfContent = """ + + + + Test + urn:isbn:9781234567890 + + + """; + File epub = createEpubWithOpf(opfContent, "test-urn-isbn-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("9781234567890", result.getIsbn13()); + } + + @Test + @DisplayName("Should ignore calibre:UUID identifier") + void extractMetadata_calibreUuid_isIgnored() throws IOException { + String opfContent = """ + + + + Test + calibre:12345678-abcd-1234-abcd-123456789abc + + + """; + File epub = createEpubWithOpf(opfContent, "test-calibre-uuid-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertNull(result.getAsin()); + assertNull(result.getGoodreadsId()); + } + } + + @Nested + @DisplayName("Calibre User Metadata Tests") + class CalibreUserMetadataTests { + + private File createEpubWithCalibreUserMetadata(String userMetadataJson) throws IOException { + String escapedJson = userMetadataJson.replace("\"", """); + String opfContent = String.format(""" + + + + Calibre Book + %s + + + """, escapedJson); + return createEpubWithOpf(opfContent, "test-calibre-um-" + System.nanoTime() + ".epub"); + } + + @Test + @DisplayName("Should extract subtitle from Calibre #subtitle custom column") + void extractMetadata_calibreSubtitle_returnsSubtitle() throws IOException { + String json = "{\"#subtitle\":{\"#value#\":\"The Hidden Path\"}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("The Hidden Path", result.getSubtitle()); + } + + @Test + @DisplayName("Should extract page count from Calibre #pagecount custom column") + void extractMetadata_calibrePagecount_returnsPageCount() throws IOException { + String json = "{\"#pagecount\":{\"#value#\":412}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals(412, result.getPageCount()); + } + + @Test + @DisplayName("Should extract series total from Calibre #series_total custom column") + void extractMetadata_calibreSeriesTotal_returnsSeriesTotal() throws IOException { + String json = "{\"#series_total\":{\"#value#\":7}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals(7, result.getSeriesTotal()); + } + + @Test + @DisplayName("Should extract all ratings from Calibre custom columns") + void extractMetadata_calibreRatings_returnsAllRatings() throws IOException { + String json = "{" + + "\"#amazon_rating\":{\"#value#\":4.5}," + + "\"#amazon_review_count\":{\"#value#\":1234}," + + "\"#goodreads_rating\":{\"#value#\":4.1}," + + "\"#goodreads_review_count\":{\"#value#\":5678}," + + "\"#hardcover_rating\":{\"#value#\":4.8}," + + "\"#hardcover_review_count\":{\"#value#\":999}," + + "\"#lubimyczytac_rating\":{\"#value#\":3.9}," + + "\"#ranobedb_rating\":{\"#value#\":4.2}" + + "}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertAll( + () -> assertEquals(4.5, result.getAmazonRating(), 0.001), + () -> assertEquals(1234, result.getAmazonReviewCount()), + () -> assertEquals(4.1, result.getGoodreadsRating(), 0.001), + () -> assertEquals(5678, result.getGoodreadsReviewCount()), + () -> assertEquals(4.8, result.getHardcoverRating(), 0.001), + () -> assertEquals(999, result.getHardcoverReviewCount()), + () -> assertEquals(3.9, result.getLubimyczytacRating(), 0.001), + () -> assertEquals(4.2, result.getRanobedbRating(), 0.001) + ); + } + + @Test + @DisplayName("Should extract age rating from Calibre #age_rating custom column") + void extractMetadata_calibreAgeRating_returnsAgeRating() throws IOException { + String json = "{\"#age_rating\":{\"#value#\":16}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals(16, result.getAgeRating()); + } + + @Test + @DisplayName("Should extract valid content rating from Calibre #content_rating custom column") + void extractMetadata_calibreContentRating_valid_returnsContentRating() throws IOException { + String json = "{\"#content_rating\":{\"#value#\":\"Teen\"}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals("TEEN", result.getContentRating()); + } + + @Test + @DisplayName("Should ignore invalid content rating from Calibre #content_rating custom column") + void extractMetadata_calibreContentRating_invalid_isIgnored() throws IOException { + String json = "{\"#content_rating\":{\"#value#\":\"Unknown Rating\"}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertNull(result.getContentRating()); + } + + @Test + @DisplayName("Should extract moods from Calibre #moods custom column") + void extractMetadata_calibreMoods_returnsMoods() throws IOException { + String json = "{\"#moods\":{\"#value#\":\"Dark, Suspenseful, Atmospheric\"}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertNotNull(result.getMoods()); + assertTrue(result.getMoods().contains("Dark")); + assertTrue(result.getMoods().contains("Suspenseful")); + assertTrue(result.getMoods().contains("Atmospheric")); + } + + @Test + @DisplayName("Should extract tags from Calibre #extra_tags custom column") + void extractMetadata_calibreExtraTags_returnsTags() throws IOException { + String json = "{\"#extra_tags\":{\"#value#\":\"Fiction, Thriller, Mystery\"}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertNotNull(result.getTags()); + assertTrue(result.getTags().contains("Fiction")); + assertTrue(result.getTags().contains("Thriller")); + assertTrue(result.getTags().contains("Mystery")); + } + + @Test + @DisplayName("Should handle null #value# in Calibre user_metadata gracefully") + void extractMetadata_calibreNullValue_isIgnored() throws IOException { + String json = "{\"#subtitle\":{\"#value#\":null},\"#pagecount\":{\"#value#\":null}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertNull(result.getSubtitle()); + assertNull(result.getPageCount()); + } + + @Test + @DisplayName("Should ignore age rating value not in valid set {0,6,10,13,16,18,21}") + void extractMetadata_calibreAgeRating_invalidValue_isIgnored() throws IOException { + String json = "{\"#age_rating\":{\"#value#\":15}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertNull(result.getAgeRating()); + } + + @Test + @DisplayName("Should extract age rating 0 (All Ages) from Calibre #age_rating") + void extractMetadata_calibreAgeRating_zero_returnsZero() throws IOException { + String json = "{\"#age_rating\":{\"#value#\":0}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals(0, result.getAgeRating()); + } + + @Test + @DisplayName("Should extract age rating 21 from Calibre #age_rating") + void extractMetadata_calibreAgeRating_21_returns21() throws IOException { + String json = "{\"#age_rating\":{\"#value#\":21}}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertEquals(21, result.getAgeRating()); + } + + @Test + @DisplayName("Should extract age_rating and content_rating from a full real-world Calibre user_metadata JSON blob with 17 custom columns") + void extractMetadata_calibreFullRealWorldJson_extractsAgeAndContentRating() throws IOException { + String json = "{" + + "\"#age_rating\":{\"#extra#\":null,\"#value#\":18,\"category_sort\":\"value\",\"colnum\":82,\"column\":\"value\",\"datatype\":\"int\",\"display\":{\"description\":\"Age Rating\",\"number_format\":null,\"web_search_template\":\"\"},\"is_category\":false,\"is_csp\":false,\"is_custom\":true,\"is_editable\":true,\"is_multiple\":null,\"is_multiple2\":{},\"kind\":\"field\",\"label\":\"age_rating\",\"link_column\":\"value\",\"name\":\"Age Rating\",\"rec_index\":23}," + + "\"#content_rating\":{\"#extra#\":null,\"#value#\":\"Everyone\",\"category_sort\":\"value\",\"colnum\":83,\"column\":\"value\",\"datatype\":\"text\",\"display\":{\"description\":\"Content Rating\",\"use_decorations\":false,\"web_search_template\":\"\"},\"is_category\":true,\"is_csp\":false,\"is_custom\":true,\"is_editable\":true,\"is_multiple\":null,\"is_multiple2\":{},\"kind\":\"field\",\"label\":\"content_rating\",\"link_column\":\"value\",\"name\":\"Content Rating\",\"rec_index\":26}," + + "\"#amazon_rating\":{\"#extra#\":null,\"#value#\":5.0,\"datatype\":\"float\",\"colnum\":67,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#amazon_review_count\":{\"#extra#\":null,\"#value#\":5,\"datatype\":\"int\",\"colnum\":68,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#goodreads_rating\":{\"#extra#\":null,\"#value#\":5.0,\"datatype\":\"float\",\"colnum\":70,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#goodreads_review_count\":{\"#extra#\":null,\"#value#\":5,\"datatype\":\"int\",\"colnum\":71,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#hardcover_rating\":{\"#extra#\":null,\"#value#\":5.0,\"datatype\":\"float\",\"colnum\":72,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#hardcover_review_count\":{\"#extra#\":null,\"#value#\":5,\"datatype\":\"int\",\"colnum\":73,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#lubimyczytac_rating\":{\"#extra#\":null,\"#value#\":5.0,\"datatype\":\"float\",\"colnum\":84,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#ranobedb_rating\":{\"#extra#\":null,\"#value#\":5.0,\"datatype\":\"float\",\"colnum\":85,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#pagecount\":{\"#extra#\":null,\"#value#\":1000,\"datatype\":\"int\",\"colnum\":81,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#series_total\":{\"#extra#\":null,\"#value#\":10,\"datatype\":\"int\",\"colnum\":37,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#subtitle\":{\"#extra#\":null,\"#value#\":\"DEMO-SUBTITLE\",\"datatype\":\"comments\",\"colnum\":77,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#moods\":{\"#extra#\":null,\"#value#\":[\"DEMO-MOODS\"],\"datatype\":\"text\",\"colnum\":76,\"is_multiple\":\"|\",\"is_multiple2\":{\"cache_to_list\":\"|\",\"list_to_ui\":\", \",\"ui_to_list\":\",\"}}," + + "\"#extra_tags\":{\"#extra#\":null,\"#value#\":[\"DEMO-TAGS\"],\"datatype\":\"text\",\"colnum\":74,\"is_multiple\":\"|\",\"is_multiple2\":{\"cache_to_list\":\"|\",\"list_to_ui\":\", \",\"ui_to_list\":\",\"}}," + + "\"#word_count\":{\"#extra#\":null,\"#value#\":1000,\"datatype\":\"int\",\"colnum\":57,\"is_multiple\":null,\"is_multiple2\":{}}," + + "\"#goodreads_awards\":{\"#extra#\":null,\"#value#\":[\"DEMO-AWARDS\"],\"datatype\":\"text\",\"colnum\":69,\"is_multiple\":\"|\",\"is_multiple2\":{}}" + + "}"; + File epub = createEpubWithCalibreUserMetadata(json); + BookMetadata result = extractor.extractMetadata(epub); + assertNotNull(result); + assertAll( + () -> assertEquals(18, result.getAgeRating()), + () -> assertEquals("EVERYONE", result.getContentRating()), + () -> assertEquals(5.0, result.getAmazonRating(), 0.001), + () -> assertEquals(5, result.getAmazonReviewCount()), + () -> assertEquals(1000, result.getPageCount()), + () -> assertEquals(10, result.getSeriesTotal()), + () -> assertEquals("DEMO-SUBTITLE", result.getSubtitle()), + () -> assertNotNull(result.getMoods()), + () -> assertTrue(result.getMoods().contains("DEMO-MOODS")), + () -> assertNotNull(result.getTags()), + () -> assertTrue(result.getTags().contains("DEMO-TAGS")) + ); + } + } + @Nested @DisplayName("Edge Cases") class EdgeCaseTests { @@ -642,25 +1144,19 @@ class EpubMetadataExtractorTest { } @Nested - @DisplayName("BookLore Metadata Tests") - class BookLoreMetadataTests { + @DisplayName("BookLore Round-Trip Metadata Tests") + class BookloreRoundTripTests { @Test - @DisplayName("Should extract BookLore custom properties from EPUB metadata") - void extractMetadata_withBookloreProperties_returnsExtendedMetadata() throws IOException { - File epubFile = createEpubWithBookloreMetadata(); + @DisplayName("Should extract all 14 booklore: namespace fields from OPF") + void extractMetadata_allBookloreFields_roundTrip() throws IOException { + File epubFile = createEpubWithAllBookloreFields(); BookMetadata result = extractor.extractMetadata(epubFile); assertAll( () -> assertNotNull(result), - () -> assertEquals("A Subtitle", result.getSubtitle()), - () -> assertEquals(10, result.getSeriesTotal()), - () -> assertEquals(4.5, result.getAmazonRating()), - () -> assertEquals(4.0, result.getGoodreadsRating()), - () -> assertEquals(5.0, result.getHardcoverRating()), - () -> assertEquals(3.5, result.getLubimyczytacRating()), - () -> assertEquals(2.0, result.getRanobedbRating()), + // IDs (legacy booklore meta format) () -> assertEquals("B001", result.getAsin()), () -> assertEquals("1001", result.getGoodreadsId()), () -> assertEquals("2002", result.getComicvineId()), @@ -668,27 +1164,118 @@ class EpubMetadataExtractorTest { () -> assertEquals("4004", result.getRanobedbId()), () -> assertEquals("5005", result.getGoogleId()), () -> assertEquals("6006", result.getLubimyczytacId()), + // Numeric fields + () -> assertEquals(350, result.getPageCount()), + () -> assertEquals(10, result.getSeriesTotal()), + () -> assertEquals(16, result.getAgeRating()), + () -> assertEquals("TEEN", result.getContentRating()), + // Ratings + () -> assertEquals(4.5, result.getAmazonRating(), 0.001), + () -> assertEquals(4.0, result.getGoodreadsRating(), 0.001), + () -> assertEquals(5.0, result.getHardcoverRating(), 0.001), + () -> assertEquals(3.5, result.getLubimyczytacRating(), 0.001), + () -> assertEquals(2.0, result.getRanobedbRating(), 0.001), + // Review counts + () -> assertEquals(1234, result.getAmazonReviewCount()), + () -> assertEquals(5678, result.getGoodreadsReviewCount()), + () -> assertEquals(999, result.getHardcoverReviewCount()), + // Sets (JSON array format - as written by EpubMetadataWriter) + () -> assertNotNull(result.getMoods()), () -> assertTrue(result.getMoods().contains("Dark")), () -> assertTrue(result.getMoods().contains("Mystery")), + () -> assertNotNull(result.getTags()), () -> assertTrue(result.getTags().contains("Fiction")), () -> assertTrue(result.getTags().contains("Thriller")) ); } + + @Test + @DisplayName("Should extract booklore:subtitle from OPF") + void extractMetadata_bookloreSubtitle_returnsSubtitle() throws IOException { + String opfContent = """ + + + + Main Title + A Subtitle + + + """; + File epubFile = createEpubWithOpf(opfContent, "test-subtitle-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epubFile); + assertNotNull(result); + assertEquals("A Subtitle", result.getSubtitle()); + } + + @Test + @DisplayName("Should extract booklore:age_rating as integer") + void extractMetadata_bookloreAgeRating_returnsInteger() throws IOException { + String opfContent = """ + + + + Test + 18 + + + """; + File epubFile = createEpubWithOpf(opfContent, "test-agerate-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epubFile); + assertNotNull(result); + assertEquals(18, result.getAgeRating()); + } + + @Test + @DisplayName("Should extract booklore:content_rating as valid enum string") + void extractMetadata_bookloreContentRating_returnsString() throws IOException { + String opfContent = """ + + + + Test + MATURE + + + """; + File epubFile = createEpubWithOpf(opfContent, "test-contentrate-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epubFile); + assertNotNull(result); + assertEquals("MATURE", result.getContentRating()); + } + + @Test + @DisplayName("Should extract booklore moods and tags as JSON arrays") + void extractMetadata_bookloreMoodsTagsJsonArray_returnsSets() throws IOException { + String opfContent = """ + + + + Test + ["Dark", "Tense", "Atmospheric"] + ["Horror", "Suspense"] + + + """; + File epubFile = createEpubWithOpf(opfContent, "test-moodstags-" + System.nanoTime() + ".epub"); + BookMetadata result = extractor.extractMetadata(epubFile); + assertNotNull(result); + assertNotNull(result.getMoods()); + assertTrue(result.getMoods().contains("Dark")); + assertTrue(result.getMoods().contains("Tense")); + assertTrue(result.getMoods().contains("Atmospheric")); + assertNotNull(result.getTags()); + assertTrue(result.getTags().contains("Horror")); + assertTrue(result.getTags().contains("Suspense")); + } } - private File createEpubWithBookloreMetadata() throws IOException { + private File createEpubWithAllBookloreFields() throws IOException { String opfContent = """ - + - BookLore Test - A Subtitle - 10 - 4.5 - 4.0 - 5.0 - 3.5 - 2.0 + BookLore Round-Trip Test B001 1001 2002 @@ -696,12 +1283,24 @@ class EpubMetadataExtractorTest { 4004 5005 6006 - Dark, Mystery - Fiction, Thriller + 350 + 10 + 16 + TEEN + 4.5 + 1234 + 4.0 + 5678 + 5.0 + 999 + 3.5 + 2.0 + ["Dark", "Mystery"] + ["Fiction", "Thriller"] """; - return createEpubWithOpf(opfContent, "test-booklore-" + System.nanoTime() + ".epub"); + return createEpubWithOpf(opfContent, "test-booklore-all-" + System.nanoTime() + ".epub"); } private File createEpubWithIsbn(String isbn13, String isbn10) throws IOException {