diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java index 72f40fdf4..1c51ff3d2 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractor.java @@ -36,6 +36,7 @@ import java.util.regex.Pattern; public class EpubMetadataExtractor implements FileMetadataExtractor { private static final Pattern YEAR_ONLY_PATTERN = Pattern.compile("^\\d{4}$"); + private static final String OPF_NS = "http://www.idpf.org/2007/opf"; @Override public byte[] extractCover(File epubFile) { @@ -100,7 +101,6 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { if (metadata == null) return null; BookMetadata.BookMetadataBuilder builderMeta = BookMetadata.builder(); - Set authors = new HashSet<>(); Set categories = new HashSet<>(); boolean seriesFound = false; @@ -108,6 +108,11 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { NodeList children = metadata.getChildNodes(); + Map creatorsById = new HashMap<>(); + Map creatorRoleById = new HashMap<>(); + Map> creatorsByRole = new HashMap<>(); + creatorsByRole.put("aut", new HashSet<>()); + Map titlesById = new HashMap<>(); Map titleTypeById = new HashMap<>(); @@ -136,6 +141,10 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { titleTypeById.put(refines.substring(1), content.toLowerCase()); } + if ("role".equals(prop) && StringUtils.isNotBlank(refines)) { + creatorRoleById.put(refines.substring(1), content.toLowerCase()); + } + if (!seriesFound && ("booklore:series".equals(prop) || "calibre:series".equals(name) || "belongs-to-collection".equals(prop))) { builderMeta.seriesName(content); seriesFound = true; @@ -176,13 +185,25 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { case "booklore:page_count" -> safeParseInt(content, builderMeta::pageCount); } } - case "creator" -> authors.add(text); + case "creator" -> { + String role = el.getAttributeNS(OPF_NS, "role"); + if (StringUtils.isNotBlank(role)) { + creatorsByRole.computeIfAbsent(role, k -> new HashSet<>()).add(text); + } else { + String id = el.getAttribute("id"); + if (StringUtils.isNotBlank(id)) { + creatorsById.put(id, text); + } else { + creatorsByRole.get("aut").add(text); + } + } + } case "subject" -> categories.add(text); case "description" -> builderMeta.description(text); case "publisher" -> builderMeta.publisher(text); case "language" -> builderMeta.language(text); case "identifier" -> { - String scheme = el.getAttributeNS("http://www.idpf.org/2007/opf", "scheme").toUpperCase(); + String scheme = el.getAttributeNS(OPF_NS, "scheme").toUpperCase(); String value = text.toLowerCase().startsWith("isbn:") ? text.substring(5) : text; if (!scheme.isEmpty()) { @@ -235,7 +256,14 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { } } - builderMeta.authors(authors); + for (Map.Entry entry : creatorsById.entrySet()) { + String id = entry.getKey(); + String value = entry.getValue(); + String role = creatorRoleById.getOrDefault(id, "aut"); + creatorsByRole.computeIfAbsent(role, k -> new HashSet<>()).add(value); + } + + builderMeta.authors(creatorsByRole.get("aut")); builderMeta.categories(categories); BookMetadata extractedMetadata = builderMeta.build(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java index 30d439931..68b6feb2e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java @@ -86,7 +86,8 @@ public class EpubMetadataWriter implements MetadataWriter { helper.copyLanguage(clear != null && clear.isLanguage(), val -> replaceAndTrackChange(opfDoc, metadataElement, "language", DC_NS, val, hasChanges)); helper.copyAuthors(clear != null && clear.isAuthors(), names -> { - removeElementsByTagNameNS(metadataElement, DC_NS, "creator"); + removeCreatorsByRole(metadataElement, ""); + removeCreatorsByRole(metadataElement, "aut"); if (names != null) { for (String name : names) { String[] parts = name.split(" ", 2); @@ -491,6 +492,16 @@ public class EpubMetadataWriter implements MetadataWriter { } } + private void removeMetaByRefines(Element metadataElement, String refines) { + NodeList metas = metadataElement.getElementsByTagNameNS("*", "meta"); + for (int i = metas.getLength() - 1; i >= 0; i--) { + Element meta = (Element) metas.item(i); + if (refines.equals(meta.getAttribute("refines"))) { + metadataElement.removeChild(meta); + } + } + } + private Element createMetaElement(Document doc, String name, String content) { Element meta = doc.createElementNS(doc.getDocumentElement().getNamespaceURI(), "meta"); meta.setAttribute("name", name); @@ -523,6 +534,28 @@ public class EpubMetadataWriter implements MetadataWriter { } } + private void removeCreatorsByRole(Element metadataElement, String role) { + NodeList creators = metadataElement.getElementsByTagNameNS("*", "creator"); + for (int i = creators.getLength() - 1; i >= 0; i--) { + Element creatorElement = (Element) creators.item(i); + String id = creatorElement.getAttribute("id"); + String creatorRole = creatorElement.getAttributeNS(OPF_NS, "role"); + if (StringUtils.isNotBlank(id) && StringUtils.isBlank(creatorRole)) { + // Finds any matching role meta tags for this creator ID + Element meta = getMetaElementByFilter(metadataElement, el -> ("role".equals(el.getAttribute("property")) && "#".concat(id).equals(el.getAttribute("refines")))); + if ( meta != null ) { + creatorRole = meta.hasAttribute("content") ? meta.getAttribute("content").trim() : meta.getTextContent().trim(); + } + } + if (role.equalsIgnoreCase(creatorRole)) { + metadataElement.removeChild(creatorElement); + if (StringUtils.isNotBlank(id)){ + removeMetaByRefines(metadataElement, "#".concat(id)); + } + } + } + } + private Element createCreatorElement(Document doc, String fullName, String fileAs, String role) { Element creator = doc.createElementNS("http://purl.org/dc/elements/1.1/", "creator"); creator.setPrefix("dc"); @@ -543,17 +576,25 @@ public class EpubMetadataWriter implements MetadataWriter { return subj; } - private String getMetaContentByName(Element metadataElement, String name) { + private Element getMetaElementByFilter(Element metadataElement, java.util.function.Predicate filter) { NodeList metas = metadataElement.getElementsByTagNameNS("*", "meta"); for (int i = 0; i < metas.getLength(); i++) { Element meta = (Element) metas.item(i); - if (name.equals(meta.getAttribute("name"))) { - return meta.getAttribute("content"); + if (filter.test(meta)) { + return meta; } } return null; } + private String getMetaContentByName(Element metadataElement, String name) { + Element meta = getMetaElementByFilter( metadataElement, el -> name.equals(el.getAttribute("name")) ); + if (meta != null) { + return meta.getAttribute("content"); + } + return null; + } + private void deleteDirectoryRecursively(Path dir) { try (var pathStream = Files.walk(dir)) { pathStream diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java index 255de003a..8bb77f8d9 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java @@ -232,6 +232,21 @@ class EpubMetadataExtractorTest { assertEquals(2, result.getAuthors().size()); } + @Test + @DisplayName("Should not extract non-authors from EPUB metadata") + void extractMetadata_withExtraCreators_returnsOnlyAuthors() throws IOException { + File epubFile = createEpubWithExtraCreators(DEFAULT_TITLE, DEFAULT_AUTHOR, "Jane Smith", "Alice", "Bob"); + + BookMetadata result = extractor.extractMetadata(epubFile); + + assertNotNull(result); + assertTrue(result.getAuthors().contains(DEFAULT_AUTHOR)); + assertTrue(result.getAuthors().contains("Jane Smith")); + assertFalse(result.getAuthors().contains("Alice")); + assertFalse(result.getAuthors().contains("Bob")); + assertEquals(2, result.getAuthors().size()); + } + @Test @DisplayName("Should extract publisher from EPUB metadata") void extractMetadata_withPublisher_returnsPublisher() throws IOException { @@ -533,6 +548,23 @@ class EpubMetadataExtractorTest { return createEpubWithOpf(opfContent, "test-multiauthor-" + System.nanoTime() + ".epub"); } + private File createEpubWithExtraCreators(String title, String author1, String author2, String illustrator, String editor) throws IOException { + String opfContent = String.format(""" + + + + %s + %s + %s + %s + %s + edt + + + """, title, author1, author2, illustrator, editor); + return createEpubWithOpf(opfContent, "test-extracreator-" + System.nanoTime() + ".epub"); + } + private File createEpubWithCalibreSeries(String title, String seriesName, String seriesIndex) throws IOException { String opfContent = String.format(""" diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java index 9a04018e2..df9b71493 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java @@ -15,11 +15,14 @@ import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; +import java.util.zip.ZipFile; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -51,6 +54,40 @@ class EpubMetadataWriterTest { bookEntity.setFileName("test.epub"); } + @Nested + @DisplayName("Metadata writing Tests") + class MetadataWritingTests { + @Test + @DisplayName("Should only overwrite authors of EPUB metadata") + void writeMetadata_withAuthor_onlyAuthor() throws IOException { + StringBuilder existingMetadata = new StringBuilder(); + existingMetadata.append(""); + existingMetadata.append("Alice"); + existingMetadata.append("ill"); + existingMetadata.append(""); + String opfContent = String.format(""" + + + %s + + """, existingMetadata); + File epubFile = createEpubWithOpf(opfContent, "test-metadata-" + System.nanoTime() + ".epub"); + + assertDoesNotThrow(() -> writer.writeMetadataToFile(epubFile, metadata, null, new MetadataClearFlags())); + + assertTrue(epubFile.exists()); + assertTrue(epubFile.length() > 0); + try (ZipFile zf = new ZipFile(epubFile)) { + ZipEntry ze = zf.getEntry("OEBPS/content.opf"); + try (InputStream is = zf.getInputStream(ze)) { + byte[] fileBytes = is.readAllBytes(); + String fileString = new String(fileBytes); + assertTrue(fileString.contains("id=\"creator02\"")); + } + } + } + } + @Nested @DisplayName("URL Decoding Tests") class UrlDecodingTests { @@ -89,6 +126,35 @@ class EpubMetadataWriterTest { } } + private File createEpubWithOpf(String opfContent, String filename) throws IOException { + File epubFile = tempDir.resolve(filename).toFile(); + + String containerXml = """ + + + + + + + """; + + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epubFile))) { + zos.putNextEntry(new ZipEntry("mimetype")); + zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + zos.putNextEntry(new ZipEntry("META-INF/container.xml")); + zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + zos.putNextEntry(new ZipEntry("OEBPS/content.opf")); + zos.write(opfContent.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + } + + return epubFile; + } + private byte[] createEpubWithUnicodeCoverHref() throws IOException { String opfContent = """