diff --git a/backend/src/main/java/org/booklore/service/metadata/extractor/EpubMetadataExtractor.java b/backend/src/main/java/org/booklore/service/metadata/extractor/EpubMetadataExtractor.java index 51917c849..ecc610e23 100644 --- a/backend/src/main/java/org/booklore/service/metadata/extractor/EpubMetadataExtractor.java +++ b/backend/src/main/java/org/booklore/service/metadata/extractor/EpubMetadataExtractor.java @@ -1,17 +1,12 @@ package org.booklore.service.metadata.extractor; +import lombok.RequiredArgsConstructor; +import org.booklore.util.epub.CoverDetectorService; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.node.ObjectNode; import org.grimmory.epub4j.archive.EpubContainer; import org.grimmory.epub4j.archive.EpubContainers; -import org.grimmory.epub4j.domain.Book; -import org.grimmory.epub4j.domain.MediaType; -import org.grimmory.epub4j.domain.MediaTypes; -import org.grimmory.epub4j.domain.Resource; -import org.grimmory.epub4j.epub.CoverDetector; -import org.grimmory.epub4j.epub.CoverDetector.CoverDetectionResult; -import org.grimmory.epub4j.epub.EpubReader; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; @@ -42,28 +37,18 @@ import java.util.function.IntConsumer; @Slf4j @Component +@RequiredArgsConstructor 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"; - // List of all media types that epub4j has so we can lazy load them. - // Note that we have to add in null to handle files without extentions like mimetype. - 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); private final ObjectMapper objectMapper; - - static { - MEDIA_TYPES.addAll(Arrays.asList(MediaTypes.mediaTypes)); - MEDIA_TYPES.add(null); - } - - public EpubMetadataExtractor(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } + private final CoverDetectorService coverDetectorService; private static final Map> CALIBRE_IDENTIFIER_PREFIXES = Map.of( "amazon", BookMetadata.BookMetadataBuilder::asin, @@ -101,80 +86,13 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { @Override public byte[] extractCover(File epubFile) { - // Primary: use epub4j's CoverDetector with native lazy loading try { - Book book = new EpubReader().readEpubLazy(epubFile.toPath(), "UTF-8"); - Optional detection = CoverDetector.detectCoverImageWithMethod(book); - if (detection.isPresent()) { - CoverDetectionResult result = detection.get(); - log.debug("Cover detected for {} via {}: {}", - epubFile.getName(), result.method(), result.resource().getHref()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - result.resource().writeTo(baos); - byte[] data = baos.toByteArray(); - if (data.length > 0) { - return data; - } + var coverImage = coverDetectorService.detectCoverImage(epubFile.toPath()); + if (coverImage != null && coverImage.length > 0) { + return coverImage; } } catch (Exception e) { - log.debug("epub4j cover detection failed for {}: {}", epubFile.getName(), e.getMessage()); - } - - // Last resort: scan container for cover-like images - try (EpubContainer container = EpubContainers.open(epubFile.toPath())) { - // NOTE: this will moved to org.grimmory.epub4j in the near future - // most of the parsing done here, can be safely replaced with methods already existing in epub4j - String opfName = findOpfPath(container); - Document opf = parseXmlFromContainer(container, opfName); - - // Try OPF manifest for cover-image property - NodeList items = opf.getElementsByTagName("item"); - for (int i = 0; i < items.getLength(); i++) { - Element item = (Element) items.item(i); - String properties = item.getAttribute("properties"); - if (properties != null && properties.contains("cover-image")) { - String href = URLDecoder.decode(item.getAttribute("href"), StandardCharsets.UTF_8); - String fullPath = resolvePath(opfName, href); - if (container.exists(fullPath)) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - container.streamTo(fullPath, baos); - return baos.toByteArray(); - } - } - } - - // Search manifest for cover-looking items by id/href - for (int i = 0; i < items.getLength(); i++) { - Element item = (Element) items.item(i); - String id = item.getAttribute("id"); - String href = item.getAttribute("href"); - String mediaType = item.getAttribute("media-type"); - if (mediaType != null && mediaType.startsWith("image/")) { - if ((id != null && id.toLowerCase().contains("cover")) || - (href != null && href.toLowerCase().contains("cover"))) { - String decodedHref = URLDecoder.decode(href, StandardCharsets.UTF_8); - String fullPath = resolvePath(opfName, decodedHref); - if (container.exists(fullPath)) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - container.streamTo(fullPath, baos); - return baos.toByteArray(); - } - } - } - } - - // Scan all files for cover-named images - for (String name : container.listAllFiles()) { - String lower = name.toLowerCase(); - if (lower.contains("cover") && (lower.endsWith(".jpg") || lower.endsWith(".jpeg") || - lower.endsWith(".png") || lower.endsWith(".webp"))) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - container.streamTo(name, baos); - return baos.toByteArray(); - } - } - } catch (Exception e) { - log.debug("Container cover search failed for {}: {}", epubFile.getName(), e.getMessage()); + log.debug("Cover detection failed for {}: {}", epubFile.getName(), e.getMessage()); } return null; @@ -600,26 +518,6 @@ public class EpubMetadataExtractor implements FileMetadataExtractor { return null; } - private byte[] getImageFromEpubResource(Resource res) { - if (res == null) { - return null; - } - - MediaType mt = res.getMediaType(); - if (mt == null || mt.name() == null || !mt.name().startsWith("image")) { - return null; - } - - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - res.writeTo(baos); - return baos.toByteArray(); - } catch (IOException e) { - log.warn("Failed to read data for resource", e); - return null; - } - } - private String findOpfPath(EpubContainer container) throws IOException, ParserConfigurationException, SAXException { String containerXmlPath = "META-INF/container.xml"; if (!container.exists(containerXmlPath)) { diff --git a/backend/src/main/java/org/booklore/service/reader/EpubReaderService.java b/backend/src/main/java/org/booklore/service/reader/EpubReaderService.java index 1dd053e87..0ecd208f4 100644 --- a/backend/src/main/java/org/booklore/service/reader/EpubReaderService.java +++ b/backend/src/main/java/org/booklore/service/reader/EpubReaderService.java @@ -13,8 +13,8 @@ import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookRepository; import org.booklore.service.ArchiveService; import org.booklore.util.FileUtils; +import org.booklore.util.epub.CoverDetectorService; import org.grimmory.epub4j.domain.*; -import org.grimmory.epub4j.epub.CoverDetector; import org.grimmory.epub4j.epub.EpubReader; import org.springframework.stereotype.Service; @@ -69,6 +69,7 @@ public class EpubReaderService { ); private final BookRepository bookRepository; + private final CoverDetectorService coverDetectorService; private final Cache metadataCache = Caffeine.newBuilder() .maximumSize(MAX_CACHE_ENTRIES) .expireAfterAccess(Duration.ofMinutes(30)) @@ -207,39 +208,35 @@ public class EpubReaderService { private CachedEpubMetadata parseEpubMetadata(Path epubPath, long lastModified) throws IOException { try { + String coverPath = coverDetectorService.detectCoverImagePath(epubPath); + Book book = new EpubReader().readEpubLazy(epubPath, "UTF-8"); - EpubBookInfo bookInfo = mapBookToInfo(book); + + Resource opfResource = book.getOpfResource(); + String opfPath = opfResource != null ? opfResource.getHref() : ""; + String rootPath = opfPath.contains("/") ? opfPath.substring(0, opfPath.lastIndexOf('/') + 1) : ""; + + List manifest = mapManifest(book, rootPath); + List spine = mapSpine(book, rootPath); + Map metadata = mapMetadata(book); + EpubTocItem toc = mapToc(book.getTableOfContents(), rootPath); + + EpubBookInfo bookInfo = EpubBookInfo.builder() + .containerPath(opfPath) + .rootPath(rootPath) + .spine(spine) + .manifest(manifest) + .toc(toc) + .metadata(metadata) + .coverPath(coverPath) + .build(); + return new CachedEpubMetadata(bookInfo, lastModified); } catch (Exception e) { throw new IOException("Unable to parse EPUB", e); } } - private EpubBookInfo mapBookToInfo(Book book) { - Resource opfResource = book.getOpfResource(); - String opfPath = opfResource != null ? opfResource.getHref() : ""; - String rootPath = opfPath.contains("/") ? opfPath.substring(0, opfPath.lastIndexOf('/') + 1) : ""; - - Resource coverResource = CoverDetector.detectCoverImage(book); - String coverHref = coverResource != null ? rootPath + coverResource.getHref() : null; - - List manifest = mapManifest(book, rootPath); - List spine = mapSpine(book, rootPath); - Map metadata = mapMetadata(book); - EpubTocItem toc = mapToc(book.getTableOfContents(), rootPath); - String coverPath = coverHref; - - return EpubBookInfo.builder() - .containerPath(opfPath) - .rootPath(rootPath) - .spine(spine) - .manifest(manifest) - .toc(toc) - .metadata(metadata) - .coverPath(coverPath) - .build(); - } - private List mapManifest(Book book, String rootPath) { List manifest = new ArrayList<>(); for (Resource resource : book.getResources().getAll()) { diff --git a/backend/src/main/java/org/booklore/util/epub/CoverDetectorService.java b/backend/src/main/java/org/booklore/util/epub/CoverDetectorService.java new file mode 100644 index 000000000..aa1ca703b --- /dev/null +++ b/backend/src/main/java/org/booklore/util/epub/CoverDetectorService.java @@ -0,0 +1,320 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2025-2026 Grimmory contributors + * Copyright (C) 2025-2026 Booklore contributors + */ +package org.booklore.util.epub; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.booklore.service.ArchiveService; +import org.grimmory.epub4j.domain.Book; +import org.grimmory.epub4j.domain.MediaType; +import org.grimmory.epub4j.domain.MediaTypes; +import org.grimmory.epub4j.domain.Resource; +import org.grimmory.epub4j.domain.Resources; +import org.grimmory.epub4j.domain.Spine; +import org.grimmory.epub4j.epub.EpubReader; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +@RequiredArgsConstructor +public class CoverDetectorService { + /** Minimum image size in bytes to consider as a potential cover (10KB). */ + private static final int MIN_COVER_SIZE = 10 * 1024; + + private static final Pattern IMG_SRC_PATTERN = + Pattern.compile("]+src\\s*=\\s*[\"']([^\"']+)[\"']", Pattern.CASE_INSENSITIVE); + private static final Pattern SVG_IMAGE_PATTERN = + Pattern.compile( + "]+(?:href|xlink:href)\\s*=\\s*[\"']([^\"']+)[\"']", Pattern.CASE_INSENSITIVE); + + private final ArchiveService archiveService; + + private Resource detectCoverImageFallback(Path path) { + // Last resort: scan container for cover-like images + try { + for (var entryName : archiveService.getEntryNames(path)) { + String lower = entryName.toLowerCase(); + if (lower.contains("cover") && (lower.endsWith(".jpg") || lower.endsWith(".jpeg") || + lower.endsWith(".png") || lower.endsWith(".webp"))) { + return new Resource( + archiveService.getEntryBytes(path, entryName), + collapsePath(entryName) + ); + } + } + } catch (Exception e) { + log.debug("Container cover search failed for {}: {}", path.getFileName().toString(), e.getMessage()); + } + + return null; + } + + private Resource detectCoverImageResource(Book book) { + if (book.getCoverImage() != null) { + return book.getCoverImage(); + } + + var resources = book.getResources().getAll(); + + Resource byId = findCoverById(resources); + if (byId != null) { + log.debug("Cover detected by resource id: {}", byId.getHref()); + return byId; + } + + Resource byName = findCoverByName(resources); + if (byName != null) { + log.debug("Cover detected by filename: {}", byName.getHref()); + return byName; + } + + Resource fromSpine = findCoverFromFirstSpineItem(book); + if (fromSpine != null) { + log.debug("Cover detected from first spine item: {}", fromSpine.getHref()); + return fromSpine; + } + + Resource largest = findLargestImage(resources); + if (largest != null) { + log.debug("Cover detected as largest image: {}", largest.getHref()); + return largest; + } + + Resource firstImage = findFirstManifestImage(resources); + if (firstImage != null) { + log.debug("Cover detected as first manifest image: {}", firstImage.getHref()); + return firstImage; + } + + return null; + } + + public String detectCoverImagePath(Path path) { + try { + Book book = new EpubReader().readEpubLazy(path, "UTF-8"); + + Resource opfResource = book.getOpfResource(); + String opfPath = opfResource != null ? opfResource.getHref() : ""; + String rootPath = opfPath.contains("/") ? opfPath.substring(0, opfPath.lastIndexOf('/') + 1) : ""; + + var resource = detectCoverImageResource(book); + + if (resource == null) { + // fallback is absolute + rootPath = ""; + resource = detectCoverImageFallback(path); + } + + return resource == null ? null : rootPath + resource.getHref(); + } catch (IOException e) { + log.debug("Failed to read epub for cover detection: {}", e.getMessage()); + } + + return null; + } + + public byte[] detectCoverImage(Path path) { + try { + Book book = new EpubReader().readEpubLazy(path, "UTF-8"); + + var resource = detectCoverImageResource(book); + + if (resource == null) { + resource = detectCoverImageFallback(path); + } + + return resource == null ? null : resource.getData(); + } catch (IOException e) { + log.debug("Failed to read epub for cover detection: {}", e.getMessage()); + } + + return null; + } + + /** + * Find an image resource whose id contains "cover" (case-insensitive). Matches id patterns like + * "cover-image", "cover", "coverimg" that OPF generators commonly use. + */ + private Resource findCoverById(Collection resources) { + for (Resource resource : resources) { + if (!isImageResource(resource)) continue; + String id = resource.getId(); + if (id != null && id.toLowerCase().contains("cover")) { + return resource; + } + } + return null; + } + + /** + * Returns the first image resource found in the manifest. Last-resort fallback when all other + * strategies fail. + */ + private Resource findFirstManifestImage(Collection resources) { + for (Resource resource : resources) { + if (isImageResource(resource) && resource.getSize() >= MIN_COVER_SIZE) { + return resource; + } + } + return null; + } + + /** + * Find an image resource whose filename contains "cover" (case-insensitive). Prioritizes exact + * matches like "cover.jpg" over partial matches like "discover.png". + */ + private Resource findCoverByName(Collection resources) { + Resource exactMatch = null; + Resource partialMatch = null; + + for (Resource resource : resources) { + if (!isImageResource(resource)) continue; + + String href = resource.getHref(); + if (href == null) continue; + + String filename = href; + int lastSlash = filename.lastIndexOf('/'); + if (lastSlash >= 0) filename = filename.substring(lastSlash + 1); + String filenameLower = filename.toLowerCase(); + + int dotPos = filenameLower.lastIndexOf('.'); + String nameWithoutExt = dotPos > 0 ? filenameLower.substring(0, dotPos) : filenameLower; + if ("cover".equals(nameWithoutExt)) { + exactMatch = resource; + break; // Can't do better than an exact match + } + + if (partialMatch == null && filenameLower.contains("cover")) { + partialMatch = resource; + } + } + + return exactMatch != null ? exactMatch : partialMatch; + } + + /** + * Look at the first spine item's XHTML content and find the first referenced image. This works + * for EPUBs where the first page is a cover page containing an img tag. + */ + private Resource findCoverFromFirstSpineItem(Book book) { + Spine spine = book.getSpine(); + if (spine.isEmpty()) return null; + + Resource firstResource = spine.getResource(0); + if (firstResource == null || firstResource.getMediaType() != MediaTypes.XHTML) { + return null; + } + + try { + byte[] data = firstResource.getData(); + if (data == null || data.length == 0) return null; + + String content = new String(data, StandardCharsets.UTF_8); + String firstHref = firstResource.getHref(); + String basePath = ""; + if (firstHref != null) { + int lastSlash = firstHref.lastIndexOf('/'); + if (lastSlash >= 0) { + basePath = firstHref.substring(0, lastSlash + 1); + } + } + + Matcher imgMatcher = IMG_SRC_PATTERN.matcher(content); + if (imgMatcher.find()) { + Resource resolved = resolveImageRef(book.getResources(), basePath, imgMatcher.group(1)); + if (resolved != null) return resolved; + } + + Matcher svgMatcher = SVG_IMAGE_PATTERN.matcher(content); + if (svgMatcher.find()) { + Resource resolved = resolveImageRef(book.getResources(), basePath, svgMatcher.group(1)); + if (resolved != null) return resolved; + } + } catch (IOException e) { + log.debug("Failed to read first spine item for cover detection: {}", e.getMessage()); + } + + return null; + } + + /** Resolve an image reference relative to a base path and look it up in resources. */ + private Resource resolveImageRef(Resources resources, String basePath, String imgSrc) { + if (imgSrc == null || imgSrc.isBlank()) return null; + + int hashPos = imgSrc.indexOf('#'); + if (hashPos >= 0) imgSrc = imgSrc.substring(0, hashPos); + + int queryPos = imgSrc.indexOf('?'); + if (queryPos >= 0) imgSrc = imgSrc.substring(0, queryPos); + + Resource resource = resources.getByHref(imgSrc); + if (resource != null) return resource; + + String resolved = basePath + imgSrc; + resource = resources.getByHref(resolved); + if (resource != null) return resource; + + if (resolved.contains("..") || resolved.contains("./") || resolved.startsWith("/")) { + resolved = collapsePath(resolved); + resource = resources.getByHref(resolved); + return resource; + } + + return null; + } + + /** + * Find the largest image resource by data size. Only considers images above the minimum size + * threshold. + */ + private Resource findLargestImage(Collection resources) { + Resource largest = null; + long largestSize = MIN_COVER_SIZE; // reject images below this as unlikely covers + + for (Resource resource : resources) { + if (!isImageResource(resource)) continue; + + long size = resource.getSize(); + if (size > largestSize) { + largestSize = size; + largest = resource; + } + } + + return largest; + } + + private boolean isImageResource(Resource resource) { + MediaType mt = resource.getMediaType(); + return mt == MediaTypes.JPG + || mt == MediaTypes.PNG + || mt == MediaTypes.GIF + || mt == MediaTypes.SVG + || mt == MediaTypes.WEBP; + } + + /** Collapse ".." and "." segments in a path. */ + private String collapsePath(String path) { + String[] parts = path.split("/"); + Deque stack = new ArrayDeque<>(); + for (String part : parts) { + if ("..".equals(part)) { + if (!stack.isEmpty()) stack.removeLast(); + } else if (!".".equals(part) && !part.isEmpty()) { + stack.addLast(part); + } + } + return String.join("/", stack); + } +} diff --git a/backend/src/test/java/org/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java b/backend/src/test/java/org/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java index 7d4992797..9b4c08ca9 100644 --- a/backend/src/test/java/org/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java +++ b/backend/src/test/java/org/booklore/service/metadata/extractor/EpubMetadataExtractorTest.java @@ -1,15 +1,20 @@ package org.booklore.service.metadata.extractor; import org.booklore.model.dto.BookMetadata; -import org.junit.jupiter.api.BeforeEach; +import org.booklore.util.epub.CoverDetectorService; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; import java.io.File; import java.io.FileOutputStream; @@ -23,18 +28,21 @@ import java.util.zip.ZipOutputStream; import static org.assertj.core.api.Assertions.assertThat; -class EpubMetadataExtractorTest { +@ExtendWith(MockitoExtension.class) +class EpubMetadataExtractorTest { + @Mock + CoverDetectorService coverDetectorService; + + @Spy + private ObjectMapper objectMapper = JsonMapper.shared(); + + @InjectMocks private EpubMetadataExtractor extractor; @TempDir Path tempDir; - @BeforeEach - void setUp() { - extractor = new EpubMetadataExtractor(new ObjectMapper()); - } - private File createEpub(String opfContent) throws IOException { return createEpub(opfContent, "OEBPS/content.opf", null); } @@ -1017,246 +1025,6 @@ class EpubMetadataExtractorTest { } } - @Nested - class CoverExtraction { - - @Test - void extractsCoverViaCoverImageProperty() throws IOException { - byte[] coverBytes = new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, 0x01, 0x02, 0x03}; - String opf = wrapOpf("", """ - - """); - File epub = createEpub(opf, "OEBPS/content.opf", coverBytes); - byte[] result = extractor.extractCover(epub); - - assertThat(result).isEqualTo(coverBytes); - } - - @Test - void extractsCoverByHeuristicManifestSearch() throws IOException { - byte[] coverBytes = new byte[]{0x01, 0x02, 0x03, 0x04}; - String opf = wrapOpf("", """ - - """); - File epub = createEpub(opf, "OEBPS/content.opf", coverBytes); - byte[] result = extractor.extractCover(epub); - - assertThat(result).isEqualTo(coverBytes); - } - - @Test - void extractsCoverByZipHeuristic() throws IOException { - byte[] coverBytes = new byte[]{0x10, 0x20, 0x30}; - File epub = tempDir.resolve("cover_zip.epub").toFile(); - try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub))) { - zos.putNextEntry(new ZipEntry("mimetype")); - zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - String containerXml = """ - - - - - - """; - zos.putNextEntry(new ZipEntry("META-INF/container.xml")); - zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - String opf = """ - - - - - - - """; - zos.putNextEntry(new ZipEntry("content.opf")); - zos.write(opf.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - zos.putNextEntry(new ZipEntry("images/cover.jpg")); - zos.write(coverBytes); - zos.closeEntry(); - } - - byte[] result = extractor.extractCover(epub); - assertThat(result).isEqualTo(coverBytes); - } - - @Test - void returnsNullForEpubWithNoCover() throws IOException { - File epub = tempDir.resolve("nocover.epub").toFile(); - try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub))) { - zos.putNextEntry(new ZipEntry("mimetype")); - zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - String containerXml = """ - - - - - - """; - zos.putNextEntry(new ZipEntry("META-INF/container.xml")); - zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - String opf = """ - - - - No Cover Book - - - - - """; - zos.putNextEntry(new ZipEntry("content.opf")); - zos.write(opf.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - } - - byte[] result = extractor.extractCover(epub); - assertThat(result).isNull(); - } - } - - @Nested - class PathResolution { - - @Test - void resolvesCoverWithParentDirectorySegments() throws IOException { - byte[] coverBytes = new byte[]{0x01, 0x02}; - File epub = tempDir.resolve("pathtest.epub").toFile(); - try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub))) { - zos.putNextEntry(new ZipEntry("mimetype")); - zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - String containerXml = """ - - - - - - """; - zos.putNextEntry(new ZipEntry("META-INF/container.xml")); - zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - String opf = """ - - - - Path Test - - - - - """; - zos.putNextEntry(new ZipEntry("OEBPS/subdir/content.opf")); - zos.write(opf.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - zos.putNextEntry(new ZipEntry("OEBPS/images/cover.jpg")); - zos.write(coverBytes); - zos.closeEntry(); - } - - byte[] result = extractor.extractCover(epub); - assertThat(result).isEqualTo(coverBytes); - } - - @Test - void resolvesAbsoluteHrefInZip() throws IOException { - byte[] coverBytes = new byte[]{0x0A, 0x0B}; - File epub = tempDir.resolve("abstest.epub").toFile(); - try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub))) { - zos.putNextEntry(new ZipEntry("mimetype")); - zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - String containerXml = """ - - - - - - """; - zos.putNextEntry(new ZipEntry("META-INF/container.xml")); - zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - String opf = """ - - - - Abs Test - - - - - """; - zos.putNextEntry(new ZipEntry("OEBPS/content.opf")); - zos.write(opf.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - zos.putNextEntry(new ZipEntry("images/cover.jpg")); - zos.write(coverBytes); - zos.closeEntry(); - } - - byte[] result = extractor.extractCover(epub); - assertThat(result).isEqualTo(coverBytes); - } - - @Test - void resolvesDotSegmentsInHref() throws IOException { - byte[] coverBytes = new byte[]{0x0C}; - File epub = tempDir.resolve("dottest.epub").toFile(); - try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub))) { - zos.putNextEntry(new ZipEntry("mimetype")); - zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - String containerXml = """ - - - - - - """; - zos.putNextEntry(new ZipEntry("META-INF/container.xml")); - zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - String opf = """ - - - - Dot Test - - - - - """; - zos.putNextEntry(new ZipEntry("OEBPS/content.opf")); - zos.write(opf.getBytes(StandardCharsets.UTF_8)); - zos.closeEntry(); - - zos.putNextEntry(new ZipEntry("OEBPS/images/cover.jpg")); - zos.write(coverBytes); - zos.closeEntry(); - } - - byte[] result = extractor.extractCover(epub); - assertThat(result).isEqualTo(coverBytes); - } - } - @Nested class OpfAtRootLevel { @@ -1385,7 +1153,6 @@ class EpubMetadataExtractorTest { void nonExistentFileReturnsNull() { File nonExistent = new File(tempDir.toFile(), "nonexistent.epub"); assertThat(extractor.extractMetadata(nonExistent)).isNull(); - assertThat(extractor.extractCover(nonExistent)).isNull(); } @Test @@ -1395,7 +1162,6 @@ class EpubMetadataExtractorTest { fos.write(new byte[]{0x00, 0x01, 0x02, 0x03}); } assertThat(extractor.extractMetadata(corrupt)).isNull(); - assertThat(extractor.extractCover(corrupt)).isNull(); } @Test diff --git a/backend/src/test/java/org/booklore/service/reader/EpubReaderServiceTest.java b/backend/src/test/java/org/booklore/service/reader/EpubReaderServiceTest.java index 83b5713fe..232812589 100644 --- a/backend/src/test/java/org/booklore/service/reader/EpubReaderServiceTest.java +++ b/backend/src/test/java/org/booklore/service/reader/EpubReaderServiceTest.java @@ -9,6 +9,7 @@ import org.booklore.model.entity.BookEntity; import org.booklore.repository.BookRepository; import org.booklore.service.ArchiveService; import org.booklore.util.FileUtils; +import org.booklore.util.epub.CoverDetectorService; import org.grimmory.epub4j.domain.*; import org.grimmory.epub4j.epub.EpubWriter; import org.junit.jupiter.api.BeforeEach; @@ -45,6 +46,9 @@ class EpubReaderServiceTest { @Spy ArchiveService archiveService = new ArchiveService(); + @Mock + CoverDetectorService coverDetectorService; + @InjectMocks EpubReaderService epubReaderService; @@ -113,7 +117,6 @@ class EpubReaderServiceTest { assertEquals("en", bookInfo.getMetadata().get("language")); assertFalse(bookInfo.getManifest().isEmpty()); assertEquals(2, bookInfo.getSpine().size()); - assertNotNull(bookInfo.getCoverPath()); } } diff --git a/backend/src/test/java/org/booklore/util/epub/CoverDetectorServiceTest.java b/backend/src/test/java/org/booklore/util/epub/CoverDetectorServiceTest.java new file mode 100644 index 000000000..e3118f872 --- /dev/null +++ b/backend/src/test/java/org/booklore/util/epub/CoverDetectorServiceTest.java @@ -0,0 +1,324 @@ +package org.booklore.util.epub; + +import org.booklore.service.ArchiveService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static org.assertj.core.api.Assertions.assertThat; + + +@ExtendWith(MockitoExtension.class) +public class CoverDetectorServiceTest { + @Spy + ArchiveService archiveService = new ArchiveService(); + + @InjectMocks + CoverDetectorService coverDetectorService; + + @TempDir + Path tempDir; + + private Path createEpub(String opfContent, String opfPath, byte[] coverImage) throws IOException { + Path epub = tempDir.resolve("test.epub"); + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub.toFile()))) { + zos.putNextEntry(new ZipEntry("mimetype")); + zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String containerXml = """ + + + + + + """.formatted(opfPath); + zos.putNextEntry(new ZipEntry("META-INF/container.xml")); + zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + zos.putNextEntry(new ZipEntry(opfPath)); + zos.write(opfContent.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + if (coverImage != null) { + zos.putNextEntry(new ZipEntry("OEBPS/images/cover.jpg")); + zos.write(coverImage); + zos.closeEntry(); + } + } + return epub; + } + + private String wrapOpf(String metadataContent, String manifestContent) { + return """ + + + + %s + + + %s + + """.formatted(metadataContent, manifestContent); + } + + @Test + void extractsCoverViaCoverImageProperty() throws IOException { + byte[] coverBytes = new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, 0x01, 0x02, 0x03}; + String opf = wrapOpf("", """ + + """); + Path epub = createEpub(opf, "OEBPS/content.opf", coverBytes); + byte[] result = coverDetectorService.detectCoverImage(epub); + + assertThat(result).isEqualTo(coverBytes); + } + + @Test + void extractsCoverByHeuristicManifestSearch() throws IOException { + byte[] coverBytes = new byte[]{0x01, 0x02, 0x03, 0x04}; + String opf = wrapOpf("", """ + + """); + Path epub = createEpub(opf, "OEBPS/content.opf", coverBytes); + byte[] result = coverDetectorService.detectCoverImage(epub); + + assertThat(result).isEqualTo(coverBytes); + } + + @Test + void extractsCoverByZipHeuristic() throws IOException { + byte[] coverBytes = new byte[]{0x10, 0x20, 0x30}; + Path epub = tempDir.resolve("cover_zip.epub"); + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub.toFile()))) { + zos.putNextEntry(new ZipEntry("mimetype")); + zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String containerXml = """ + + + + + + """; + zos.putNextEntry(new ZipEntry("META-INF/container.xml")); + zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String opf = """ + + + + + + + """; + zos.putNextEntry(new ZipEntry("content.opf")); + zos.write(opf.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + zos.putNextEntry(new ZipEntry("images/cover.jpg")); + zos.write(coverBytes); + zos.closeEntry(); + } + + byte[] result = coverDetectorService.detectCoverImage(epub); + assertThat(result).isEqualTo(coverBytes); + } + + @Test + void returnsNullForEpubWithNoCover() throws IOException { + Path epub = tempDir.resolve("nocover.epub"); + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub.toFile()))) { + zos.putNextEntry(new ZipEntry("mimetype")); + zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String containerXml = """ + + + + + + """; + zos.putNextEntry(new ZipEntry("META-INF/container.xml")); + zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String opf = """ + + + + No Cover Book + + + + + """; + zos.putNextEntry(new ZipEntry("content.opf")); + zos.write(opf.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + } + + byte[] result = coverDetectorService.detectCoverImage(epub); + assertThat(result).isNull(); + } + + @Test + void resolvesCoverWithParentDirectorySegments() throws IOException { + byte[] coverBytes = new byte[]{0x01, 0x02}; + Path epub = tempDir.resolve("pathtest.epub"); + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub.toFile()))) { + zos.putNextEntry(new ZipEntry("mimetype")); + zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String containerXml = """ + + + + + + """; + zos.putNextEntry(new ZipEntry("META-INF/container.xml")); + zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String opf = """ + + + + Path Test + + + + + """; + zos.putNextEntry(new ZipEntry("OEBPS/subdir/content.opf")); + zos.write(opf.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + zos.putNextEntry(new ZipEntry("OEBPS/images/cover.jpg")); + zos.write(coverBytes); + zos.closeEntry(); + } + + byte[] result = coverDetectorService.detectCoverImage(epub); + assertThat(result).isEqualTo(coverBytes); + } + + @Test + void resolvesAbsoluteHrefInZip() throws IOException { + byte[] coverBytes = new byte[]{0x0A, 0x0B}; + Path epub = tempDir.resolve("abstest.epub"); + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub.toFile()))) { + zos.putNextEntry(new ZipEntry("mimetype")); + zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String containerXml = """ + + + + + + """; + zos.putNextEntry(new ZipEntry("META-INF/container.xml")); + zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String opf = """ + + + + Abs Test + + + + + """; + zos.putNextEntry(new ZipEntry("OEBPS/content.opf")); + zos.write(opf.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + zos.putNextEntry(new ZipEntry("images/cover.jpg")); + zos.write(coverBytes); + zos.closeEntry(); + } + + byte[] result = coverDetectorService.detectCoverImage(epub); + assertThat(result).isEqualTo(coverBytes); + } + + @Test + void resolvesDotSegmentsInHref() throws IOException { + byte[] coverBytes = new byte[]{0x0C}; + Path epub = tempDir.resolve("dottest.epub"); + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epub.toFile()))) { + zos.putNextEntry(new ZipEntry("mimetype")); + zos.write("application/epub+zip".getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String containerXml = """ + + + + + + """; + zos.putNextEntry(new ZipEntry("META-INF/container.xml")); + zos.write(containerXml.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + String opf = """ + + + + Dot Test + + + + + """; + zos.putNextEntry(new ZipEntry("OEBPS/content.opf")); + zos.write(opf.getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + + zos.putNextEntry(new ZipEntry("OEBPS/images/cover.jpg")); + zos.write(coverBytes); + zos.closeEntry(); + } + + byte[] result = coverDetectorService.detectCoverImage(epub); + assertThat(result).isEqualTo(coverBytes); + } + + @Test + void nonExistentFileReturnsNull() { + Path nonExistent = tempDir.resolve("nonexistent.epub"); + assertThat(coverDetectorService.detectCoverImage(nonExistent)).isNull(); + } + + @Test + void corruptZipReturnsNull() throws IOException { + Path corrupt = tempDir.resolve("corrupt.epub"); + try (FileOutputStream fos = new FileOutputStream(corrupt.toFile())) { + fos.write(new byte[]{0x00, 0x01, 0x02, 0x03}); + } + assertThat(coverDetectorService.detectCoverImage(corrupt)).isNull(); + } + +}