diff --git a/backend/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java b/backend/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java index 97a34b280..af205104e 100644 --- a/backend/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java +++ b/backend/src/main/java/org/booklore/service/metadata/writer/EpubMetadataWriter.java @@ -550,6 +550,18 @@ public class EpubMetadataWriter implements MetadataWriter { throw new IOException("Failed to parse container.xml to locate OPF path", e); } + if (existingCoverItem != null) { + String existingMediaType = existingCoverItem.getAttribute("media-type"); + if (!existingMediaType.equals(mediaType)) { + // If the existing cover item exists but has a different media type we can't + // use it. However, because it's _possible_ that the cover MAY be used elsewhere + // in the epub (such as referenced in HTML) we cannot delete the manifest item + // or the file. All we can do is discard it as the existing cover manifest item, + // and treat the epub as if it has no cover, and place a new cover manifest item. + existingCoverItem = null; + } + } + Path opfDir = opfPath.getParent(); if (existingCoverItem != null) { diff --git a/backend/src/test/java/org/booklore/service/metadata/writer/EpubMetadataWriterTest.java b/backend/src/test/java/org/booklore/service/metadata/writer/EpubMetadataWriterTest.java index e08b36ae6..c9657a673 100644 --- a/backend/src/test/java/org/booklore/service/metadata/writer/EpubMetadataWriterTest.java +++ b/backend/src/test/java/org/booklore/service/metadata/writer/EpubMetadataWriterTest.java @@ -387,7 +387,7 @@ class EpubMetadataWriterTest { - + """; @@ -786,8 +786,8 @@ class EpubMetadataWriterTest { Test Book - - + + """, @@ -806,6 +806,38 @@ class EpubMetadataWriterTest { } assertThat(count).isEqualTo(1); } + + @Test + void shouldMitigateMediaTypeMismatch() throws Exception { + Path thumbnailPath = tempDir.resolve("thumbnail-" + System.nanoTime()).toAbsolutePath(); + Files.write(thumbnailPath, new byte[]{0x01, 0x02, 0x03}); + + File epubFile = createEpubWithOpf( + """ + + + + + + + + + """, + "no-cover-" + System.nanoTime() + ".epub" + ); + + writer.saveMetadataToFile(epubFile, metadata, thumbnailPath.toString(), new MetadataClearFlags()); + + + String content = readOpfContent(epubFile); + + // Removes properties from existing + assertThat(content).contains(""); + + // And creates a new item with the prop + assertThat(content).containsPattern(".*"); + } + } private Document parseOpf(File epubFile) throws Exception {