Fix(metadata): Improve handling of non-author creator roles (#1987)
* Fix(metadata): Don't import creators with a non-author role as author Looks at either the meta tag for the creators or the opf role attribute to determine the role of a creator. If no role is specified its assumed to be an author. Also only prunes handled created roles when writing the epub data back out to prevent clobbering any extra data that might be present in the epub already. * Fix(metadata): Add testcases for non-author creator handling Just adds testcases for the previous changes to the extraction and writer logic.
This commit is contained in:
+32
-4
@@ -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<String> authors = new HashSet<>();
|
||||
Set<String> categories = new HashSet<>();
|
||||
|
||||
boolean seriesFound = false;
|
||||
@@ -108,6 +108,11 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
NodeList children = metadata.getChildNodes();
|
||||
|
||||
Map<String, String> creatorsById = new HashMap<>();
|
||||
Map<String, String> creatorRoleById = new HashMap<>();
|
||||
Map<String, Set<String>> creatorsByRole = new HashMap<>();
|
||||
creatorsByRole.put("aut", new HashSet<>());
|
||||
|
||||
Map<String, String> titlesById = new HashMap<>();
|
||||
Map<String, String> 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<String, String> 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();
|
||||
|
||||
+45
-4
@@ -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<Element> 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
|
||||
|
||||
+32
@@ -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("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
|
||||
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
|
||||
<dc:title>%s</dc:title>
|
||||
<dc:creator>%s</dc:creator>
|
||||
<dc:creator opf:role="aut">%s</dc:creator>
|
||||
<dc:creator opf:role="ill">%s</dc:creator>
|
||||
<dc:creator id="creator04">%s</dc:creator>
|
||||
<meta property="role" refines="#creator04" scheme="marc:relators">edt</meta>
|
||||
</metadata>
|
||||
</package>
|
||||
""", 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("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
+66
@@ -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("<metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">");
|
||||
existingMetadata.append("<dc:creator id=\"creator02\">Alice</dc:creator>");
|
||||
existingMetadata.append("<meta property=\"role\" refines=\"#creator02\">ill</meta>");
|
||||
existingMetadata.append("</metadata>");
|
||||
String opfContent = String.format("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
|
||||
%s
|
||||
</package>
|
||||
""", 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 = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
|
||||
<rootfiles>
|
||||
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
|
||||
</rootfiles>
|
||||
</container>
|
||||
""";
|
||||
|
||||
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 = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
Reference in New Issue
Block a user