refactor(epub): migrate from documentnode to grimmory epub4j library and update related code (#334)
* refactor(epub): migrate from documentnode to grimmory epub4j library and update related code * chore(deps): restore proper imports * refactor(epub): update to epub4j version 1.0.0 and improve cover image detection * fix(epub): validate spine indices in convertXPointerRangeToCfi method * chore(deps): update epub4j dependencies to version 1.0.1 * chore(deps): update epub4j dependency to version 1.0.1 * feat(build): enable preview features and update epub4j dependencies in build configuration * feat(epub): update epub4j dependencies to version 1.1.0 and refactor resource handling for improved streaming
This commit is contained in:
@@ -26,6 +26,10 @@ java {
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.compilerArgs.add("--enable-preview")
|
||||
}
|
||||
|
||||
val useLocalLibs = providers.gradleProperty("useLocalLibs").isPresent
|
||||
|
||||
repositories {
|
||||
@@ -127,9 +131,13 @@ dependencies {
|
||||
implementation("com.twelvemonkeys.imageio:imageio-bmp:3.13.1")
|
||||
|
||||
// epub4j-grimmory fork publishes as org.grimmory:epub4j-core
|
||||
val epub4jCoords = if (useLocalLibs) "org.grimmory:epub4j-core:+" else "io.documentnode:epub4j-core:4.2.3"
|
||||
val epub4jCoords = if (useLocalLibs) "org.grimmory:epub4j-core:+" else "org.grimmory:epub4j-core:1.1.0"
|
||||
implementation(epub4jCoords)
|
||||
|
||||
// epub4j-native for native archive parsing
|
||||
val epub4jNativeCoords = if (useLocalLibs) "org.grimmory:epub4j-native:+" else "org.grimmory:epub4j-native:1.1.0"
|
||||
implementation(epub4jNativeCoords)
|
||||
|
||||
// --- Audio Metadata (Audiobook Support) ---
|
||||
implementation("com.github.RouHim:jaudiotagger:2.0.19")
|
||||
|
||||
@@ -194,7 +202,7 @@ hibernate {
|
||||
tasks.named<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
maxHeapSize = "2560m"
|
||||
jvmArgs("-XX:+EnableDynamicAgentLoading", "--enable-native-access=ALL-UNNAMED")
|
||||
jvmArgs("-XX:+EnableDynamicAgentLoading", "--enable-native-access=ALL-UNNAMED", "--enable-preview")
|
||||
finalizedBy(tasks.named("jacocoTestReport"))
|
||||
}
|
||||
|
||||
@@ -222,7 +230,7 @@ tasks.named<Copy>("processResources") {
|
||||
}
|
||||
|
||||
tasks.named<BootRun>("bootRun") {
|
||||
jvmArgs("--enable-native-access=ALL-UNNAMED")
|
||||
jvmArgs("--enable-native-access=ALL-UNNAMED", "--enable-preview")
|
||||
if (System.getenv("REMOTE_DEBUG_ENABLED") == "true") {
|
||||
jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005")
|
||||
}
|
||||
|
||||
+73
-129
@@ -1,19 +1,19 @@
|
||||
package org.booklore.service.metadata.extractor;
|
||||
|
||||
import io.documentnode.epub4j.domain.Book;
|
||||
import io.documentnode.epub4j.domain.MediaType;
|
||||
import io.documentnode.epub4j.domain.MediaTypes;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
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 net.lingala.zip4j.ZipFile;
|
||||
import net.lingala.zip4j.model.FileHeader;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.booklore.model.dto.BookMetadata;
|
||||
import org.booklore.service.metadata.BookLoreMetadata;
|
||||
import org.booklore.service.reader.EpubReaderService;
|
||||
import org.booklore.util.SecureXmlUtils;
|
||||
import org.springframework.boot.configurationprocessor.json.JSONException;
|
||||
import org.springframework.boot.configurationprocessor.json.JSONObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -21,11 +21,9 @@ import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDate;
|
||||
@@ -90,111 +88,87 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
@Override
|
||||
public byte[] extractCover(File epubFile) {
|
||||
Book epub = null;
|
||||
io.documentnode.epub4j.domain.Resource coverImage = null;
|
||||
|
||||
try (FileInputStream fis = new FileInputStream(epubFile)) {
|
||||
try {
|
||||
epub = new EpubReader().readEpub(fis);
|
||||
coverImage = epub.getCoverImage();
|
||||
} catch (NullPointerException e) {
|
||||
log.debug("epub4j threw NullPointerException (likely malformed NCX) in {}: {}", epubFile.getName(), e.getMessage());
|
||||
} catch (Exception e) {
|
||||
log.debug("epub4j failed to parse EPUB for cover extraction (will try fallbacks) in {}: {}", epubFile.getName(), e.getMessage());
|
||||
// Primary: use epub4j's CoverDetector with native lazy loading
|
||||
try {
|
||||
Book book = new EpubReader().readEpubLazy(epubFile.toPath(), "UTF-8");
|
||||
Optional<CoverDetectionResult> 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;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("epub4j cover detection failed for {}: {}", epubFile.getName(), e.getMessage());
|
||||
}
|
||||
|
||||
// We fall back to reading the image based on the cover-image property.
|
||||
String coverHref = findCoverImageHrefInOpf(epubFile);
|
||||
if (coverHref != null) {
|
||||
byte[] image = extractFileFromZip(epubFile, coverHref);
|
||||
if (image != null) {
|
||||
return image;
|
||||
// Last resort: scan container for cover-like images
|
||||
try (EpubContainer container = EpubContainers.open(epubFile.toPath())) {
|
||||
Document opf = container.parseOpf();
|
||||
String opfName = container.getOpfName();
|
||||
|
||||
// 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();
|
||||
container.streamTo(fullPath, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: search manifest for anything that looks like a cover
|
||||
if (coverImage == null) {
|
||||
String href = findManifestCoverByHeuristic(epubFile);
|
||||
if (href != null) {
|
||||
byte[] data = extractFileFromZip(epubFile, href);
|
||||
if (data != null) return data;
|
||||
}
|
||||
}
|
||||
|
||||
if (coverImage == null && epub != null) {
|
||||
for (io.documentnode.epub4j.domain.Resource res : epub.getResources().getAll()) {
|
||||
String id = res.getId();
|
||||
String href = res.getHref();
|
||||
// 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"))) {
|
||||
if (res.getMediaType() != null && res.getMediaType().getName().startsWith("image")) {
|
||||
coverImage = res;
|
||||
break;
|
||||
String decodedHref = URLDecoder.decode(href, StandardCharsets.UTF_8);
|
||||
String fullPath = resolvePath(opfName, decodedHref);
|
||||
if (container.exists(fullPath)) {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
container.streamTo(fullPath, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Absolute last resort: Scan ZIP entries directly
|
||||
if (coverImage == null) {
|
||||
byte[] data = findCoverInZipByHeuristic(epubFile);
|
||||
if (data != null) return data;
|
||||
}
|
||||
|
||||
return (coverImage != null) ? coverImage.getData() : null;
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract cover from EPUB: {}", epubFile.getName(), e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private String findManifestCoverByHeuristic(File epubFile) {
|
||||
try {
|
||||
Document doc = EpubReaderService.getOPFDocument(epubFile);
|
||||
|
||||
NodeList manifestItems = doc.getElementsByTagName("item");
|
||||
|
||||
for (int i = 0; i < manifestItems.getLength(); i++) {
|
||||
Element item = (Element) manifestItems.item(i);
|
||||
String id = item.getAttribute("id");
|
||||
String href = item.getAttribute("href");
|
||||
String mediaType = item.getAttribute("media-type");
|
||||
|
||||
if ((id != null && id.toLowerCase().contains("cover")) || (href != null && href.toLowerCase().contains("cover"))) {
|
||||
if (mediaType != null && mediaType.startsWith("image/")) {
|
||||
String decodedHref = URLDecoder.decode(href, StandardCharsets.UTF_8);
|
||||
return resolvePath(EpubReaderService.getOPFPath(epubFile), decodedHref);
|
||||
}
|
||||
// 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();
|
||||
container.streamTo(name, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Heuristic manifest search failed: {}", e.getMessage());
|
||||
log.debug("Container cover search failed for {}: {}", epubFile.getName(), e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private byte[] findCoverInZipByHeuristic(File epubFile) {
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
List<FileHeader> fileHeaders = zip.getFileHeaders();
|
||||
for (FileHeader header : fileHeaders) {
|
||||
String name = header.getFileName().toLowerCase();
|
||||
if (name.contains("cover") && (name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png") || name.endsWith(".webp"))) {
|
||||
try (InputStream is = zip.getInputStream(header)) {
|
||||
return is.readAllBytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Direct ZIP scan for cover failed: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookMetadata extractMetadata(File epubFile) {
|
||||
try {
|
||||
Document doc = EpubReaderService.getOPFDocument(epubFile);
|
||||
try (EpubContainer container = EpubContainers.open(epubFile.toPath())) {
|
||||
Document doc = container.parseOpf();
|
||||
|
||||
Element metadata = (Element) doc.getElementsByTagNameNS("*", "metadata").item(0);
|
||||
if (metadata == null) return null;
|
||||
@@ -581,38 +555,20 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
|
||||
MediaType mt = res.getMediaType();
|
||||
if (mt == null || mt.getName() == null || !mt.getName().startsWith("image")) {
|
||||
if (mt == null || mt.name() == null || !mt.name().startsWith("image")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return res.getData();
|
||||
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 findCoverImageHrefInOpf(File epubFile) {
|
||||
try {
|
||||
Document doc = EpubReaderService.getOPFDocument(epubFile);
|
||||
NodeList manifestItems = doc.getElementsByTagName("item");
|
||||
|
||||
for (int i = 0; i < manifestItems.getLength(); i++) {
|
||||
Element item = (Element) manifestItems.item(i);
|
||||
String properties = item.getAttribute("properties");
|
||||
if (properties != null && properties.contains("cover-image")) {
|
||||
String href = item.getAttribute("href");
|
||||
String decodedHref = URLDecoder.decode(href, StandardCharsets.UTF_8);
|
||||
return resolvePath(EpubReaderService.getOPFPath(epubFile), decodedHref);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to find cover image in OPF: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String resolvePath(String opfPath, String href) {
|
||||
if (href == null || href.isEmpty()) return null;
|
||||
|
||||
@@ -637,16 +593,4 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
|
||||
return String.join("/", parts);
|
||||
}
|
||||
|
||||
private byte[] extractFileFromZip(File epubFile, String path) {
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
FileHeader header = zip.getFileHeader(path);
|
||||
if (header == null) return null;
|
||||
try (InputStream is = zip.getInputStream(header)) {
|
||||
return is.readAllBytes();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract file {} from zip", path);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+62
-38
@@ -2,9 +2,6 @@ package org.booklore.service.metadata.writer;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
import net.lingala.zip4j.model.ZipParameters;
|
||||
import net.lingala.zip4j.model.enums.CompressionMethod;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.booklore.model.MetadataClearFlags;
|
||||
import org.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
@@ -35,6 +32,7 @@ import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -43,6 +41,12 @@ import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import org.grimmory.epub4j.archive.EpubContainer;
|
||||
import org.grimmory.epub4j.archive.EpubContainers;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -68,9 +72,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
Path tempDir = null;
|
||||
try {
|
||||
tempDir = Files.createTempDirectory("epub_edit_" + UUID.randomUUID());
|
||||
try (ZipFile zipFile = new ZipFile(epubFile)) {
|
||||
zipFile.extractAll(tempDir.toString());
|
||||
}
|
||||
extractZipToDirectory(epubFile, tempDir);
|
||||
|
||||
File opfFile = findOpfFile(tempDir.toFile());
|
||||
if (opfFile == null) {
|
||||
@@ -225,9 +227,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
transformer.transform(new DOMSource(opfDoc), new StreamResult(opfFile));
|
||||
|
||||
File tempEpub = new File(epubFile.getParentFile(), epubFile.getName() + ".tmp");
|
||||
try (ZipFile tempZipFile = new ZipFile(tempEpub)) {
|
||||
addFolderContentsToZip(tempZipFile, tempDir.toFile(), tempDir.toFile());
|
||||
}
|
||||
createEpubZipFromDirectory(tempDir, tempEpub.toPath());
|
||||
|
||||
if (!epubFile.delete()) throw new IOException("Could not delete original EPUB");
|
||||
if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB");
|
||||
@@ -361,9 +361,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
File epubFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
tempDir = Files.createTempDirectory("epub_cover_" + UUID.randomUUID());
|
||||
|
||||
try (ZipFile zipFile = new ZipFile(epubFile)) {
|
||||
zipFile.extractAll(tempDir.toString());
|
||||
}
|
||||
extractZipToDirectory(epubFile, tempDir);
|
||||
|
||||
File opfFile = findOpfFile(tempDir.toFile());
|
||||
if (opfFile == null) {
|
||||
@@ -383,9 +381,7 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
transformer.transform(new DOMSource(opfDoc), new StreamResult(opfFile));
|
||||
|
||||
File tempEpub = new File(epubFile.getParentFile(), epubFile.getName() + ".tmp");
|
||||
try (ZipFile tempZipFile = new ZipFile(tempEpub)) {
|
||||
addFolderContentsToZip(tempZipFile, tempDir.toFile(), tempDir.toFile());
|
||||
}
|
||||
createEpubZipFromDirectory(tempDir, tempEpub.toPath());
|
||||
|
||||
if (!epubFile.delete()) throw new IOException("Could not delete original EPUB");
|
||||
if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB");
|
||||
@@ -526,33 +522,61 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
}
|
||||
}
|
||||
|
||||
private void addFolderContentsToZip(ZipFile zipFile, File baseDir, File currentDir) throws IOException {
|
||||
// EPUB spec requires mimetype to be the first entry in the ZIP, uncompressed (STORED)
|
||||
if (baseDir.equals(currentDir)) {
|
||||
File mimetypeFile = new File(baseDir, "mimetype");
|
||||
if (mimetypeFile.exists()) {
|
||||
ZipParameters mimetypeParams = new ZipParameters();
|
||||
mimetypeParams.setFileNameInZip("mimetype");
|
||||
mimetypeParams.setCompressionMethod(CompressionMethod.STORE);
|
||||
zipFile.addFile(mimetypeFile, mimetypeParams);
|
||||
private void extractZipToDirectory(File zipSource, Path targetDir) throws IOException {
|
||||
try (EpubContainer container = EpubContainers.open(zipSource.toPath())) {
|
||||
for (String name : container.listAllFiles()) {
|
||||
Path entryPath = targetDir.resolve(name).normalize();
|
||||
if (!entryPath.startsWith(targetDir)) {
|
||||
throw new IOException("ZIP entry outside target directory: " + name);
|
||||
}
|
||||
Files.createDirectories(entryPath.getParent());
|
||||
try (OutputStream out = Files.newOutputStream(entryPath)) {
|
||||
container.streamTo(name, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void createEpubZipFromDirectory(Path sourceDir, Path targetZip) throws IOException {
|
||||
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(targetZip))) {
|
||||
// EPUB spec requires mimetype to be the first entry in the ZIP, uncompressed (STORED)
|
||||
Path mimetypeFile = sourceDir.resolve("mimetype");
|
||||
if (Files.exists(mimetypeFile)) {
|
||||
byte[] mimetypeData = Files.readAllBytes(mimetypeFile);
|
||||
ZipEntry mimetypeEntry = new ZipEntry("mimetype");
|
||||
mimetypeEntry.setMethod(ZipEntry.STORED);
|
||||
mimetypeEntry.setSize(mimetypeData.length);
|
||||
mimetypeEntry.setCompressedSize(mimetypeData.length);
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(mimetypeData);
|
||||
mimetypeEntry.setCrc(crc.getValue());
|
||||
zos.putNextEntry(mimetypeEntry);
|
||||
zos.write(mimetypeData);
|
||||
zos.closeEntry();
|
||||
} else {
|
||||
log.warn("EPUB mimetype file not found in extracted directory — output may be spec-invalid");
|
||||
}
|
||||
}
|
||||
|
||||
File[] files = Objects.requireNonNull(currentDir.listFiles());
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
addFolderContentsToZip(zipFile, baseDir, file);
|
||||
} else {
|
||||
// Skip mimetype — already added as the first entry
|
||||
String relativePath = baseDir.toPath().relativize(file.toPath()).toString().replace(File.separatorChar, '/');
|
||||
if ("mimetype".equals(relativePath)) {
|
||||
continue;
|
||||
}
|
||||
ZipParameters params = new ZipParameters();
|
||||
params.setFileNameInZip(relativePath);
|
||||
zipFile.addFile(file, params);
|
||||
try (var pathStream = Files.walk(sourceDir)) {
|
||||
pathStream
|
||||
.filter(path -> !path.equals(sourceDir))
|
||||
.filter(path -> !path.equals(mimetypeFile))
|
||||
.sorted()
|
||||
.forEach(path -> {
|
||||
try {
|
||||
String relativePath = sourceDir.relativize(path).toString().replace(File.separatorChar, '/');
|
||||
if (Files.isDirectory(path)) {
|
||||
zos.putNextEntry(new ZipEntry(relativePath + "/"));
|
||||
zos.closeEntry();
|
||||
} else {
|
||||
zos.putNextEntry(new ZipEntry(relativePath));
|
||||
Files.copy(path, zos);
|
||||
zos.closeEntry();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new java.io.UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@ package org.booklore.service.reader;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.response.EpubBookInfo;
|
||||
import org.booklore.model.dto.response.EpubManifestItem;
|
||||
@@ -14,24 +12,17 @@ import org.booklore.model.entity.BookFileEntity;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.util.FileUtils;
|
||||
import org.booklore.util.SecureXmlUtils;
|
||||
import org.grimmory.epub4j.domain.*;
|
||||
import org.grimmory.epub4j.epub.CoverDetector;
|
||||
import org.grimmory.epub4j.epub.EpubReader;
|
||||
import org.grimmory.epub4j.native_parsing.NativeArchive;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import java.io.*;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -39,32 +30,11 @@ import java.util.regex.Pattern;
|
||||
public class EpubReaderService {
|
||||
|
||||
private static final String CONTAINER_PATH = "META-INF/container.xml";
|
||||
private static final String CONTAINER_NS = "urn:oasis:names:tc:opendocument:xmlns:container";
|
||||
private static final String OPF_NS = "http://www.idpf.org/2007/opf";
|
||||
private static final String DC_NS = "http://purl.org/dc/elements/1.1/";
|
||||
private static final String NCX_NS = "http://www.daisy.org/z3986/2005/ncx/";
|
||||
private static final String XHTML_NS = "http://www.w3.org/1999/xhtml";
|
||||
private static final String EPUB_NS = "http://www.idpf.org/2007/ops";
|
||||
|
||||
private static final int MAX_CACHE_ENTRIES = 50;
|
||||
private static final int BUFFER_SIZE = 65536; // 64KB buffer for I/O
|
||||
private static final Charset[] ENCODINGS_TO_TRY = {
|
||||
StandardCharsets.UTF_8,
|
||||
StandardCharsets.ISO_8859_1,
|
||||
Charset.forName("CP437")
|
||||
};
|
||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
||||
|
||||
private static final Map<String, String> CONTENT_TYPE_MAP = createContentTypeMap();
|
||||
|
||||
private static DocumentBuilder createDocumentBuilder() {
|
||||
try {
|
||||
return SecureXmlUtils.createSecureDocumentBuilder(true);
|
||||
} catch (ParserConfigurationException e) {
|
||||
throw new RuntimeException("Failed to create DocumentBuilder", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> createContentTypeMap() {
|
||||
Map<String, String> map = new HashMap<>(32);
|
||||
map.put(".xhtml", "application/xhtml+xml");
|
||||
@@ -88,7 +58,14 @@ public class EpubReaderService {
|
||||
map.put(".smil", "application/smil+xml");
|
||||
map.put(".mp3", "audio/mpeg");
|
||||
map.put(".mp4", "video/mp4");
|
||||
map.put(".m4a", "audio/mp4");
|
||||
map.put(".m4b", "audio/mp4");
|
||||
map.put(".aac", "audio/aac");
|
||||
map.put(".wav", "audio/wav");
|
||||
map.put(".flac", "audio/flac");
|
||||
map.put(".ogg", "audio/ogg");
|
||||
map.put(".webm", "video/webm");
|
||||
map.put(".avif", "image/avif");
|
||||
map.put(".opf", "application/oebps-package+xml");
|
||||
return Collections.unmodifiableMap(map);
|
||||
}
|
||||
@@ -99,15 +76,13 @@ public class EpubReaderService {
|
||||
private static class CachedEpubMetadata {
|
||||
final EpubBookInfo bookInfo;
|
||||
final long lastModified;
|
||||
final Charset successfulEncoding;
|
||||
final Set<String> validPaths; // Pre-computed valid paths for O(1) lookup
|
||||
final Map<String, EpubManifestItem> manifestByHref; // O(1) lookup by href
|
||||
final Set<String> validPaths;
|
||||
final Map<String, EpubManifestItem> manifestByHref;
|
||||
volatile long lastAccessed;
|
||||
|
||||
CachedEpubMetadata(EpubBookInfo bookInfo, long lastModified, Charset encoding) {
|
||||
CachedEpubMetadata(EpubBookInfo bookInfo, long lastModified) {
|
||||
this.bookInfo = bookInfo;
|
||||
this.lastModified = lastModified;
|
||||
this.successfulEncoding = encoding;
|
||||
this.lastAccessed = System.currentTimeMillis();
|
||||
|
||||
Set<String> paths = new HashSet<>(bookInfo.getManifest().size() + 2);
|
||||
@@ -166,7 +141,7 @@ public class EpubReaderService {
|
||||
throw new FileNotFoundException("File not found in EPUB: " + filePath);
|
||||
}
|
||||
|
||||
streamEntryFromZip(epubPath, actualPath, outputStream, metadata.successfulEncoding);
|
||||
streamEntryFromZip(epubPath, actualPath, outputStream);
|
||||
}
|
||||
|
||||
public String getContentType(Long bookId, String filePath) {
|
||||
@@ -253,448 +228,157 @@ public class EpubReaderService {
|
||||
}
|
||||
|
||||
private CachedEpubMetadata parseEpubMetadata(Path epubPath, long lastModified) throws IOException {
|
||||
for (Charset encoding : ENCODINGS_TO_TRY) {
|
||||
try {
|
||||
EpubBookInfo bookInfo = parseEpubWithEncoding(epubPath, encoding);
|
||||
return new CachedEpubMetadata(bookInfo, lastModified, encoding);
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to parse EPUB with encoding {}: {}", encoding, e.getMessage());
|
||||
}
|
||||
}
|
||||
throw new IOException("Unable to parse EPUB with any supported encoding");
|
||||
}
|
||||
|
||||
private EpubBookInfo parseEpubWithEncoding(Path epubPath, Charset charset) throws Exception {
|
||||
try (ZipFile zipFile = ZipFile.builder()
|
||||
.setPath(epubPath)
|
||||
.setCharset(charset)
|
||||
.setUseUnicodeExtraFields(true)
|
||||
.get()) {
|
||||
|
||||
String opfPath = parseContainerXml(zipFile);
|
||||
String rootPath = opfPath.contains("/") ? opfPath.substring(0, opfPath.lastIndexOf('/') + 1) : "";
|
||||
|
||||
Document opfDoc = parseXmlEntry(zipFile, opfPath);
|
||||
Element packageEl = opfDoc.getDocumentElement();
|
||||
|
||||
List<EpubManifestItem> manifest = parseManifest(opfDoc, rootPath, zipFile);
|
||||
Map<String, EpubManifestItem> manifestById = new HashMap<>();
|
||||
for (EpubManifestItem item : manifest) {
|
||||
manifestById.put(item.getId(), item);
|
||||
}
|
||||
|
||||
List<EpubSpineItem> spine = parseSpine(opfDoc, manifestById);
|
||||
|
||||
Map<String, Object> metadata = parseMetadata(opfDoc);
|
||||
|
||||
String navPath = null;
|
||||
String ncxPath = null;
|
||||
for (EpubManifestItem item : manifest) {
|
||||
if (item.getProperties() != null && item.getProperties().contains("nav")) {
|
||||
navPath = item.getHref();
|
||||
}
|
||||
if ("application/x-dtbncx+xml".equals(item.getMediaType())) {
|
||||
ncxPath = item.getHref();
|
||||
}
|
||||
}
|
||||
|
||||
EpubTocItem toc = null;
|
||||
if (navPath != null) {
|
||||
try {
|
||||
toc = parseNavDocument(zipFile, navPath, rootPath);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to parse nav document, trying NCX: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
if (toc == null && ncxPath != null) {
|
||||
try {
|
||||
toc = parseNcx(zipFile, ncxPath, rootPath);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to parse NCX: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
String coverPath = findCoverPath(opfDoc, manifest, manifestById);
|
||||
|
||||
return EpubBookInfo.builder()
|
||||
.containerPath(opfPath)
|
||||
.rootPath(rootPath)
|
||||
.spine(spine)
|
||||
.manifest(manifest)
|
||||
.toc(toc)
|
||||
.metadata(metadata)
|
||||
.coverPath(coverPath)
|
||||
.build();
|
||||
try {
|
||||
Book book = new EpubReader().readEpubLazy(epubPath, "UTF-8");
|
||||
EpubBookInfo bookInfo = mapBookToInfo(book);
|
||||
return new CachedEpubMetadata(bookInfo, lastModified);
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Unable to parse EPUB", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String parseContainerXml(ZipFile zipFile) throws Exception {
|
||||
Document doc = parseXmlEntry(zipFile, CONTAINER_PATH);
|
||||
NodeList rootfiles = doc.getElementsByTagNameNS(CONTAINER_NS, "rootfile");
|
||||
if (rootfiles.getLength() == 0) {
|
||||
rootfiles = doc.getElementsByTagName("rootfile");
|
||||
}
|
||||
if (rootfiles.getLength() == 0) {
|
||||
throw new IOException("No rootfile found in container.xml");
|
||||
}
|
||||
Element rootfile = (Element) rootfiles.item(0);
|
||||
String fullPath = rootfile.getAttribute("full-path");
|
||||
if (fullPath == null || fullPath.isEmpty()) {
|
||||
throw new IOException("No full-path attribute in rootfile");
|
||||
}
|
||||
return fullPath;
|
||||
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<EpubManifestItem> manifest = mapManifest(book, rootPath);
|
||||
List<EpubSpineItem> spine = mapSpine(book, rootPath);
|
||||
Map<String, Object> 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();
|
||||
}
|
||||
|
||||
public static String getOPFPath(File epubFile) throws Exception {
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
return parseContainerXml(zip);
|
||||
}
|
||||
}
|
||||
|
||||
public static Document getOPFDocument(File epubFile) throws Exception {
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
String opfPath = parseContainerXml(zip);
|
||||
return parseXmlEntry(zip, opfPath);
|
||||
}
|
||||
}
|
||||
|
||||
private List<EpubManifestItem> parseManifest(Document opfDoc, String rootPath, ZipFile zipFile) {
|
||||
private List<EpubManifestItem> mapManifest(Book book, String rootPath) {
|
||||
List<EpubManifestItem> manifest = new ArrayList<>();
|
||||
NodeList items = opfDoc.getElementsByTagNameNS(OPF_NS, "item");
|
||||
if (items.getLength() == 0) {
|
||||
items = opfDoc.getElementsByTagName("item");
|
||||
}
|
||||
for (Resource resource : book.getResources().getAll()) {
|
||||
String fullHref = rootPath + resource.getHref();
|
||||
|
||||
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");
|
||||
String properties = item.getAttribute("properties");
|
||||
|
||||
String fullHref = rootPath + href;
|
||||
long size = getEntrySize(zipFile, fullHref);
|
||||
|
||||
List<String> propList = null;
|
||||
if (properties != null && !properties.isEmpty()) {
|
||||
propList = Arrays.asList(WHITESPACE_PATTERN.split(properties));
|
||||
// Use EPUB3 manifest item properties directly from the parsed resource
|
||||
List<String> properties = null;
|
||||
if (resource.getProperties() != null && !resource.getProperties().isEmpty()) {
|
||||
properties = resource.getProperties().stream()
|
||||
.map(ManifestItemProperties::getName)
|
||||
.toList();
|
||||
}
|
||||
|
||||
manifest.add(EpubManifestItem.builder()
|
||||
.id(id)
|
||||
.id(resource.getId())
|
||||
.href(fullHref)
|
||||
.mediaType(mediaType)
|
||||
.properties(propList)
|
||||
.size(size)
|
||||
.mediaType(resource.getMediaType().name())
|
||||
.properties(properties)
|
||||
.size(resource.getSize())
|
||||
.build());
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
|
||||
private List<EpubSpineItem> parseSpine(Document opfDoc, Map<String, EpubManifestItem> manifestById) {
|
||||
private List<EpubSpineItem> mapSpine(Book book, String rootPath) {
|
||||
List<EpubSpineItem> spine = new ArrayList<>();
|
||||
NodeList itemrefs = opfDoc.getElementsByTagNameNS(OPF_NS, "itemref");
|
||||
if (itemrefs.getLength() == 0) {
|
||||
itemrefs = opfDoc.getElementsByTagName("itemref");
|
||||
}
|
||||
|
||||
for (int i = 0; i < itemrefs.getLength(); i++) {
|
||||
Element itemref = (Element) itemrefs.item(i);
|
||||
String idref = itemref.getAttribute("idref");
|
||||
String linear = itemref.getAttribute("linear");
|
||||
|
||||
EpubManifestItem manifestItem = manifestById.get(idref);
|
||||
if (manifestItem != null) {
|
||||
spine.add(EpubSpineItem.builder()
|
||||
.idref(idref)
|
||||
.href(manifestItem.getHref())
|
||||
.mediaType(manifestItem.getMediaType())
|
||||
.linear(!"no".equals(linear))
|
||||
.build());
|
||||
}
|
||||
for (SpineReference ref : book.getSpine().getSpineReferences()) {
|
||||
Resource resource = ref.getResource();
|
||||
spine.add(EpubSpineItem.builder()
|
||||
.idref(resource.getId())
|
||||
.href(rootPath + resource.getHref())
|
||||
.mediaType(resource.getMediaType().name())
|
||||
.linear(ref.isLinear())
|
||||
.build());
|
||||
}
|
||||
return spine;
|
||||
}
|
||||
|
||||
private Map<String, Object> parseMetadata(Document opfDoc) {
|
||||
private Map<String, Object> mapMetadata(Book book) {
|
||||
Map<String, Object> metadata = new HashMap<>();
|
||||
Metadata md = book.getMetadata();
|
||||
|
||||
String title = getElementTextByNS(opfDoc, DC_NS, "title");
|
||||
if (title == null) title = getElementText(opfDoc, "dc:title");
|
||||
if (title != null) metadata.put("title", title);
|
||||
String title = md.getFirstTitle();
|
||||
if (title != null && !title.isEmpty()) metadata.put("title", title);
|
||||
|
||||
String creator = getElementTextByNS(opfDoc, DC_NS, "creator");
|
||||
if (creator == null) creator = getElementText(opfDoc, "dc:creator");
|
||||
if (creator != null) metadata.put("creator", creator);
|
||||
List<Author> authors = md.getAuthors();
|
||||
if (authors != null && !authors.isEmpty()) {
|
||||
Author first = authors.get(0);
|
||||
String name = first.getFirstname();
|
||||
if (first.getLastname() != null && !first.getLastname().isEmpty()) {
|
||||
name = (name != null && !name.isEmpty()) ? name + " " + first.getLastname() : first.getLastname();
|
||||
}
|
||||
if (name != null && !name.isEmpty()) metadata.put("creator", name);
|
||||
}
|
||||
|
||||
String language = getElementTextByNS(opfDoc, DC_NS, "language");
|
||||
if (language == null) language = getElementText(opfDoc, "dc:language");
|
||||
if (language != null) metadata.put("language", language);
|
||||
String language = md.getLanguage();
|
||||
if (language != null && !language.isEmpty()) metadata.put("language", language);
|
||||
|
||||
String publisher = getElementTextByNS(opfDoc, DC_NS, "publisher");
|
||||
if (publisher == null) publisher = getElementText(opfDoc, "dc:publisher");
|
||||
if (publisher != null) metadata.put("publisher", publisher);
|
||||
List<String> publishers = md.getPublishers();
|
||||
if (publishers != null && !publishers.isEmpty()) metadata.put("publisher", publishers.get(0));
|
||||
|
||||
String identifier = getElementTextByNS(opfDoc, DC_NS, "identifier");
|
||||
if (identifier == null) identifier = getElementText(opfDoc, "dc:identifier");
|
||||
if (identifier != null) metadata.put("identifier", identifier);
|
||||
List<Identifier> identifiers = md.getIdentifiers();
|
||||
if (identifiers != null && !identifiers.isEmpty()) metadata.put("identifier", identifiers.get(0).getValue());
|
||||
|
||||
String description = getElementTextByNS(opfDoc, DC_NS, "description");
|
||||
if (description == null) description = getElementText(opfDoc, "dc:description");
|
||||
if (description != null) metadata.put("description", description);
|
||||
List<String> descriptions = md.getDescriptions();
|
||||
if (descriptions != null && !descriptions.isEmpty()) metadata.put("description", descriptions.get(0));
|
||||
|
||||
// EPUB3 rendition properties
|
||||
if (md.getRenditionLayout() != null) metadata.put("rendition:layout", md.getRenditionLayout());
|
||||
if (md.getRenditionOrientation() != null) metadata.put("rendition:orientation", md.getRenditionOrientation());
|
||||
if (md.getRenditionSpread() != null) metadata.put("rendition:spread", md.getRenditionSpread());
|
||||
if (md.getMediaDuration() != null) metadata.put("media:duration", md.getMediaDuration());
|
||||
|
||||
// Page progression direction from spine
|
||||
String ppd = book.getSpine().getPageProgressionDirection();
|
||||
if (ppd != null && !ppd.isEmpty()) metadata.put("page-progression-direction", ppd);
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private EpubTocItem parseNavDocument(ZipFile zipFile, String navPath, String rootPath) throws Exception {
|
||||
Document doc = parseXmlEntry(zipFile, navPath);
|
||||
|
||||
NodeList navs = doc.getElementsByTagNameNS(XHTML_NS, "nav");
|
||||
if (navs.getLength() == 0) {
|
||||
navs = doc.getElementsByTagName("nav");
|
||||
}
|
||||
|
||||
Element tocNav = null;
|
||||
for (int i = 0; i < navs.getLength(); i++) {
|
||||
Element nav = (Element) navs.item(i);
|
||||
String type = nav.getAttributeNS(EPUB_NS, "type");
|
||||
if (type == null || type.isEmpty()) {
|
||||
type = nav.getAttribute("epub:type");
|
||||
}
|
||||
if ("toc".equals(type)) {
|
||||
tocNav = nav;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (tocNav == null && navs.getLength() > 0) {
|
||||
tocNav = (Element) navs.item(0);
|
||||
}
|
||||
|
||||
if (tocNav == null) {
|
||||
private EpubTocItem mapToc(TableOfContents toc, String rootPath) {
|
||||
if (toc == null || toc.getTocReferences() == null || toc.getTocReferences().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
NodeList ols = tocNav.getElementsByTagNameNS(XHTML_NS, "ol");
|
||||
if (ols.getLength() == 0) {
|
||||
ols = tocNav.getElementsByTagName("ol");
|
||||
}
|
||||
|
||||
if (ols.getLength() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String navDir = navPath.contains("/") ? navPath.substring(0, navPath.lastIndexOf('/') + 1) : rootPath;
|
||||
List<EpubTocItem> children = parseNavOl((Element) ols.item(0), navDir);
|
||||
List<EpubTocItem> children = toc.getTocReferences().stream()
|
||||
.map(ref -> mapTocReference(ref, rootPath))
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
|
||||
return EpubTocItem.builder()
|
||||
.label("Table of Contents")
|
||||
.children(children)
|
||||
.children(children.isEmpty() ? null : children)
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<EpubTocItem> parseNavOl(Element ol, String basePath) {
|
||||
List<EpubTocItem> items = new ArrayList<>();
|
||||
NodeList children = ol.getChildNodes();
|
||||
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
if (children.item(i) instanceof Element li && "li".equals(li.getLocalName())) {
|
||||
EpubTocItem item = parseNavLi(li, basePath);
|
||||
if (item != null) {
|
||||
items.add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private EpubTocItem parseNavLi(Element li, String basePath) {
|
||||
Element link = null;
|
||||
NodeList children = li.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
if (children.item(i) instanceof Element el) {
|
||||
if ("a".equals(el.getLocalName()) || "span".equals(el.getLocalName())) {
|
||||
link = el;
|
||||
break;
|
||||
}
|
||||
}
|
||||
private EpubTocItem mapTocReference(TOCReference tocRef, String rootPath) {
|
||||
String label = tocRef.getTitle();
|
||||
String href = tocRef.getResource() != null ? rootPath + tocRef.getResource().getHref() : null;
|
||||
if (href != null && tocRef.getFragmentId() != null && !tocRef.getFragmentId().isEmpty()) {
|
||||
href += "#" + tocRef.getFragmentId();
|
||||
}
|
||||
|
||||
if (link == null) return null;
|
||||
|
||||
String label = link.getTextContent().trim();
|
||||
String href = link.getAttribute("href");
|
||||
if (href != null && !href.isEmpty() && !href.startsWith("http")) {
|
||||
href = resolveHref(href, basePath);
|
||||
}
|
||||
|
||||
List<EpubTocItem> subItems = null;
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
if (children.item(i) instanceof Element el && "ol".equals(el.getLocalName())) {
|
||||
subItems = parseNavOl(el, basePath);
|
||||
break;
|
||||
}
|
||||
List<EpubTocItem> children = null;
|
||||
if (tocRef.getChildren() != null && !tocRef.getChildren().isEmpty()) {
|
||||
children = tocRef.getChildren().stream()
|
||||
.map(ref -> mapTocReference(ref, rootPath))
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
}
|
||||
|
||||
return EpubTocItem.builder()
|
||||
.label(label)
|
||||
.href(href)
|
||||
.children(subItems)
|
||||
.build();
|
||||
}
|
||||
|
||||
private EpubTocItem parseNcx(ZipFile zipFile, String ncxPath, String rootPath) throws Exception {
|
||||
Document doc = parseXmlEntry(zipFile, ncxPath);
|
||||
|
||||
NodeList navMaps = doc.getElementsByTagNameNS(NCX_NS, "navMap");
|
||||
if (navMaps.getLength() == 0) {
|
||||
navMaps = doc.getElementsByTagName("navMap");
|
||||
}
|
||||
|
||||
if (navMaps.getLength() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Element navMap = (Element) navMaps.item(0);
|
||||
String ncxDir = ncxPath.contains("/") ? ncxPath.substring(0, ncxPath.lastIndexOf('/') + 1) : rootPath;
|
||||
List<EpubTocItem> children = parseNcxNavPoints(navMap, ncxDir);
|
||||
|
||||
return EpubTocItem.builder()
|
||||
.label("Table of Contents")
|
||||
.children(children)
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<EpubTocItem> parseNcxNavPoints(Element parent, String basePath) {
|
||||
List<EpubTocItem> items = new ArrayList<>();
|
||||
NodeList navPoints = parent.getChildNodes();
|
||||
|
||||
for (int i = 0; i < navPoints.getLength(); i++) {
|
||||
if (navPoints.item(i) instanceof Element el && "navPoint".equals(el.getLocalName())) {
|
||||
EpubTocItem item = parseNcxNavPoint(el, basePath);
|
||||
if (item != null) {
|
||||
items.add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private EpubTocItem parseNcxNavPoint(Element navPoint, String basePath) {
|
||||
String label = null;
|
||||
NodeList labels = navPoint.getElementsByTagNameNS(NCX_NS, "navLabel");
|
||||
if (labels.getLength() == 0) {
|
||||
labels = navPoint.getElementsByTagName("navLabel");
|
||||
}
|
||||
if (labels.getLength() > 0) {
|
||||
Element labelEl = (Element) labels.item(0);
|
||||
NodeList texts = labelEl.getElementsByTagNameNS(NCX_NS, "text");
|
||||
if (texts.getLength() == 0) {
|
||||
texts = labelEl.getElementsByTagName("text");
|
||||
}
|
||||
if (texts.getLength() > 0) {
|
||||
label = texts.item(0).getTextContent().trim();
|
||||
}
|
||||
}
|
||||
|
||||
String href = null;
|
||||
NodeList contents = navPoint.getElementsByTagNameNS(NCX_NS, "content");
|
||||
if (contents.getLength() == 0) {
|
||||
contents = navPoint.getElementsByTagName("content");
|
||||
}
|
||||
if (contents.getLength() > 0) {
|
||||
Element content = (Element) contents.item(0);
|
||||
href = content.getAttribute("src");
|
||||
if (href != null && !href.isEmpty()) {
|
||||
href = resolveHref(href, basePath);
|
||||
}
|
||||
}
|
||||
|
||||
List<EpubTocItem> subItems = parseNcxNavPoints(navPoint, basePath);
|
||||
|
||||
return EpubTocItem.builder()
|
||||
.label(label)
|
||||
.href(href)
|
||||
.children(subItems.isEmpty() ? null : subItems)
|
||||
.build();
|
||||
}
|
||||
|
||||
private String findCoverPath(Document opfDoc, List<EpubManifestItem> manifest, Map<String, EpubManifestItem> manifestById) {
|
||||
for (EpubManifestItem item : manifest) {
|
||||
if (item.getProperties() != null && item.getProperties().contains("cover-image")) {
|
||||
return item.getHref();
|
||||
}
|
||||
}
|
||||
|
||||
NodeList metas = opfDoc.getElementsByTagNameNS(OPF_NS, "meta");
|
||||
if (metas.getLength() == 0) {
|
||||
metas = opfDoc.getElementsByTagName("meta");
|
||||
}
|
||||
for (int i = 0; i < metas.getLength(); i++) {
|
||||
Element meta = (Element) metas.item(i);
|
||||
if ("cover".equals(meta.getAttribute("name"))) {
|
||||
String coverId = meta.getAttribute("content");
|
||||
EpubManifestItem coverItem = manifestById.get(coverId);
|
||||
if (coverItem != null) {
|
||||
return coverItem.getHref();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Document parseXmlEntry(ZipFile zipFile, String entryPath) throws Exception {
|
||||
ZipArchiveEntry entry = zipFile.getEntry(entryPath);
|
||||
if (entry == null) {
|
||||
throw new FileNotFoundException("Entry not found: " + entryPath);
|
||||
}
|
||||
|
||||
DocumentBuilder builder = createDocumentBuilder();
|
||||
try (InputStream is = zipFile.getInputStream(entry)) {
|
||||
return builder.parse(is);
|
||||
}
|
||||
}
|
||||
|
||||
private long getEntrySize(ZipFile zipFile, String entryPath) {
|
||||
ZipArchiveEntry entry = zipFile.getEntry(entryPath);
|
||||
return entry != null ? entry.getSize() : 0;
|
||||
}
|
||||
|
||||
private String getElementTextByNS(Document doc, String ns, String tagName) {
|
||||
NodeList nodes = doc.getElementsByTagNameNS(ns, tagName);
|
||||
if (nodes.getLength() > 0) {
|
||||
return nodes.item(0).getTextContent().trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String getElementText(Document doc, String tagName) {
|
||||
NodeList nodes = doc.getElementsByTagName(tagName);
|
||||
if (nodes.getLength() > 0) {
|
||||
return nodes.item(0).getTextContent().trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String resolveHref(String href, String basePath) {
|
||||
if (href == null || href.isEmpty()) return href;
|
||||
if (href.startsWith("/")) return href.substring(1);
|
||||
if (href.startsWith("http://") || href.startsWith("https://")) return href;
|
||||
|
||||
String result = basePath + href;
|
||||
while (result.contains("/../")) {
|
||||
int idx = result.indexOf("/../");
|
||||
int prevSlash = result.lastIndexOf('/', idx - 1);
|
||||
if (prevSlash >= 0) {
|
||||
result = result.substring(0, prevSlash) + result.substring(idx + 3);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String normalizePath(String path, String rootPath) {
|
||||
if (path == null) return null;
|
||||
|
||||
@@ -718,38 +402,10 @@ public class EpubReaderService {
|
||||
return metadata.validPaths.contains(path);
|
||||
}
|
||||
|
||||
private void streamEntryFromZip(Path epubPath, String entryName, OutputStream outputStream, Charset cachedEncoding) throws IOException {
|
||||
if (cachedEncoding != null) {
|
||||
if (tryStreamEntryFromZip(epubPath, entryName, outputStream, cachedEncoding)) {
|
||||
return;
|
||||
}
|
||||
private void streamEntryFromZip(Path epubPath, String entryName, OutputStream outputStream) throws IOException {
|
||||
try (NativeArchive archive = NativeArchive.open(epubPath)) {
|
||||
archive.streamEntry(entryName, outputStream);
|
||||
}
|
||||
|
||||
for (Charset encoding : ENCODINGS_TO_TRY) {
|
||||
if (encoding.equals(cachedEncoding)) continue;
|
||||
if (tryStreamEntryFromZip(epubPath, entryName, outputStream, encoding)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new IOException("Unable to stream entry from EPUB: " + entryName);
|
||||
}
|
||||
|
||||
private boolean tryStreamEntryFromZip(Path epubPath, String entryName, OutputStream outputStream, Charset charset) throws IOException {
|
||||
try (ZipFile zipFile = ZipFile.builder()
|
||||
.setPath(epubPath)
|
||||
.setCharset(charset)
|
||||
.setUseUnicodeExtraFields(true)
|
||||
.get()) {
|
||||
ZipArchiveEntry entry = zipFile.getEntry(entryName);
|
||||
if (entry != null) {
|
||||
try (InputStream in = new BufferedInputStream(zipFile.getInputStream(entry), BUFFER_SIZE)) {
|
||||
in.transferTo(outputStream);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String guessContentType(String path) {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
package org.booklore.util.epub;
|
||||
|
||||
import io.documentnode.epub4j.domain.Book;
|
||||
import io.documentnode.epub4j.domain.MediaType;
|
||||
import io.documentnode.epub4j.domain.MediaTypes;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.domain.Spine;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
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.Spine;
|
||||
import org.grimmory.epub4j.epub.EpubReader;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -30,8 +30,8 @@ public class EpubContentReader {
|
||||
}
|
||||
|
||||
public static String getSpineItemContent(File epubFile, int spineIndex) {
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
Book epub = new EpubReader().readEpubLazy(zip, "UTF-8", MEDIA_TYPES);
|
||||
try {
|
||||
Book epub = new EpubReader().readEpubLazy(epubFile.toPath(), "UTF-8", MEDIA_TYPES);
|
||||
|
||||
Spine spine = epub.getSpine();
|
||||
if (spine == null || spine.size() == 0) {
|
||||
@@ -50,7 +50,9 @@ public class EpubContentReader {
|
||||
String.format("Spine item %d has no resource in: %s", spineIndex, epubFile.getName()));
|
||||
}
|
||||
|
||||
return new String(resource.getData(), StandardCharsets.UTF_8);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
resource.writeTo(baos);
|
||||
return baos.toString(StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new EpubReadException("Failed to read EPUB file: " + epubFile.getName(), e);
|
||||
}
|
||||
@@ -61,8 +63,8 @@ public class EpubContentReader {
|
||||
}
|
||||
|
||||
public static int getSpineSize(File epubFile) {
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
Book epub = new EpubReader().readEpubLazy(zip, "UTF-8", MEDIA_TYPES);
|
||||
try {
|
||||
Book epub = new EpubReader().readEpubLazy(epubFile.toPath(), "UTF-8", MEDIA_TYPES);
|
||||
Spine spine = epub.getSpine();
|
||||
return spine != null ? spine.size() : 0;
|
||||
} catch (IOException e) {
|
||||
@@ -71,8 +73,8 @@ public class EpubContentReader {
|
||||
}
|
||||
|
||||
public static String getSpineItemHref(File epubFile, int spineIndex) {
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
Book epub = new EpubReader().readEpubLazy(zip, "UTF-8", MEDIA_TYPES);
|
||||
try {
|
||||
Book epub = new EpubReader().readEpubLazy(epubFile.toPath(), "UTF-8", MEDIA_TYPES);
|
||||
|
||||
Spine spine = epub.getSpine();
|
||||
if (spine == null || spineIndex < 0 || spineIndex >= spine.size()) {
|
||||
@@ -89,8 +91,8 @@ public class EpubContentReader {
|
||||
|
||||
public static List<String> getAllSpineItemHrefs(File epubFile) {
|
||||
List<String> hrefs = new ArrayList<>();
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
Book epub = new EpubReader().readEpubLazy(zip, "UTF-8", MEDIA_TYPES);
|
||||
try {
|
||||
Book epub = new EpubReader().readEpubLazy(epubFile.toPath(), "UTF-8", MEDIA_TYPES);
|
||||
|
||||
Spine spine = epub.getSpine();
|
||||
if (spine != null) {
|
||||
|
||||
@@ -1,521 +0,0 @@
|
||||
package org.booklore.util.koreader;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.jsoup.nodes.Element;
|
||||
import org.jsoup.nodes.Node;
|
||||
import org.jsoup.nodes.TextNode;
|
||||
import org.jsoup.select.Elements;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Slf4j
|
||||
public class CfiConvertor {
|
||||
|
||||
private static final Pattern CFI_PATTERN = Pattern.compile("^epubcfi\\((.+)\\)$");
|
||||
private static final Pattern CFI_SPINE_PATTERN = Pattern.compile("^/6/(\\d+)!(.*)$");
|
||||
private static final Pattern CFI_PATH_STEP_PATTERN = Pattern.compile("/(\\d+)(?:\\[(.*?)\\])?(?::(\\d+))?");
|
||||
private static final Pattern XPOINTER_DOC_FRAGMENT_PATTERN = Pattern.compile("^/body/DocFragment\\[(\\d+)\\]/body(.*)$");
|
||||
private static final Pattern XPOINTER_TEXT_OFFSET_PATTERN = Pattern.compile("/text\\(\\)\\.(\\d+)$");
|
||||
private static final Pattern XPOINTER_SEGMENT_WITH_INDEX_PATTERN = Pattern.compile("^(\\w+)\\[(\\d+)\\]$");
|
||||
private static final Pattern XPOINTER_SEGMENT_WITHOUT_INDEX_PATTERN = Pattern.compile("^(\\w+)$");
|
||||
private static final Pattern TRAILING_TEXT_OFFSET_PATTERN = Pattern.compile("/text\\(\\).*$");
|
||||
private static final Pattern SUFFIX_NODE_OFFSET_PATTERN = Pattern.compile("\\.\\d+$");
|
||||
|
||||
private static final Set<String> INLINE_ELEMENTS = Set.of(
|
||||
"span", "em", "strong", "i", "b", "u", "small", "mark", "sup", "sub"
|
||||
);
|
||||
|
||||
private final Document document;
|
||||
private final int spineItemIndex;
|
||||
|
||||
public CfiConvertor(Document htmlDocument, int spineIndex) {
|
||||
this.document = htmlDocument;
|
||||
this.spineItemIndex = spineIndex;
|
||||
}
|
||||
|
||||
public CfiConvertor(Document htmlDocument) {
|
||||
this(htmlDocument, 0);
|
||||
}
|
||||
|
||||
public static int extractSpineIndex(String cfiOrXPath) {
|
||||
if (cfiOrXPath == null || cfiOrXPath.isBlank()) {
|
||||
throw new IllegalArgumentException("CFI/XPointer string cannot be null or empty");
|
||||
}
|
||||
|
||||
if (cfiOrXPath.startsWith("epubcfi(")) {
|
||||
return extractSpineIndexFromCfi(cfiOrXPath);
|
||||
} else if (cfiOrXPath.startsWith("/body/DocFragment[")) {
|
||||
return extractSpineIndexFromXPointer(cfiOrXPath);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unsupported format for spine index extraction: " + cfiOrXPath);
|
||||
}
|
||||
}
|
||||
|
||||
private static int extractSpineIndexFromCfi(String cfi) {
|
||||
Matcher cfiMatcher = CFI_PATTERN.matcher(cfi);
|
||||
if (!cfiMatcher.matches()) {
|
||||
throw new IllegalArgumentException("Invalid CFI format: " + cfi);
|
||||
}
|
||||
|
||||
String innerCfi = cfiMatcher.group(1);
|
||||
Matcher spineMatcher = CFI_SPINE_PATTERN.matcher(innerCfi);
|
||||
if (!spineMatcher.matches()) {
|
||||
throw new IllegalArgumentException("Cannot extract spine index from CFI: " + cfi);
|
||||
}
|
||||
|
||||
int spineStep = Integer.parseInt(spineMatcher.group(1));
|
||||
return (spineStep - 2) / 2;
|
||||
}
|
||||
|
||||
private static int extractSpineIndexFromXPointer(String xpointer) {
|
||||
Pattern pattern = Pattern.compile("DocFragment\\[(\\d+)\\]");
|
||||
Matcher matcher = pattern.matcher(xpointer);
|
||||
if (matcher.find()) {
|
||||
return Integer.parseInt(matcher.group(1)) - 1;
|
||||
}
|
||||
throw new IllegalArgumentException("Cannot extract spine index from XPointer: " + xpointer);
|
||||
}
|
||||
|
||||
public String xPointerToCfi(String startXPointer, String endXPointer) {
|
||||
if (endXPointer != null && !endXPointer.isBlank()) {
|
||||
return convertRangeXPointerToCfi(startXPointer, endXPointer);
|
||||
}
|
||||
return convertPointXPointerToCfi(startXPointer);
|
||||
}
|
||||
|
||||
public String xPointerToCfi(String xpointer) {
|
||||
return xPointerToCfi(xpointer, null);
|
||||
}
|
||||
|
||||
public XPointerResult cfiToXPointer(String cfi) {
|
||||
Matcher cfiMatcher = CFI_PATTERN.matcher(cfi);
|
||||
if (!cfiMatcher.matches()) {
|
||||
throw new IllegalArgumentException("Invalid CFI format: " + cfi);
|
||||
}
|
||||
|
||||
String innerCfi = cfiMatcher.group(1);
|
||||
Matcher spineMatcher = CFI_SPINE_PATTERN.matcher(innerCfi);
|
||||
if (!spineMatcher.matches()) {
|
||||
throw new IllegalArgumentException("Cannot parse CFI spine step: " + cfi);
|
||||
}
|
||||
|
||||
int spineStep = Integer.parseInt(spineMatcher.group(1));
|
||||
int cfiSpineIndex = (spineStep - 2) / 2;
|
||||
|
||||
if (cfiSpineIndex != spineItemIndex) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("CFI spine index %d does not match converter spine index %d",
|
||||
cfiSpineIndex, spineItemIndex));
|
||||
}
|
||||
|
||||
String contentPath = spineMatcher.group(2);
|
||||
CfiPathResult pathResult = parseCfiPath(contentPath);
|
||||
|
||||
Element element = resolveElementFromCfiSteps(pathResult.steps());
|
||||
if (element == null) {
|
||||
throw new IllegalArgumentException("Element not found for CFI: " + cfi);
|
||||
}
|
||||
|
||||
String xpointer;
|
||||
if (pathResult.textOffset() != null) {
|
||||
xpointer = handleTextOffset(element, pathResult.textOffset());
|
||||
} else {
|
||||
xpointer = buildXPointerPath(element);
|
||||
}
|
||||
|
||||
return new XPointerResult(xpointer, xpointer, xpointer);
|
||||
}
|
||||
|
||||
public boolean validateCfi(String cfi) {
|
||||
try {
|
||||
cfiToXPointer(cfi);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.debug("CFI validation failed: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean validateXPointer(String xpointer, String pos1) {
|
||||
try {
|
||||
xPointerToCfi(xpointer, pos1);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.debug("XPointer validation failed: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean validateXPointer(String xpointer) {
|
||||
return validateXPointer(xpointer, null);
|
||||
}
|
||||
|
||||
public static String normalizeProgressXPointer(String xpointer) {
|
||||
if (xpointer == null) {
|
||||
return null;
|
||||
}
|
||||
String result = TRAILING_TEXT_OFFSET_PATTERN.matcher(xpointer).replaceAll("");
|
||||
result = SUFFIX_NODE_OFFSET_PATTERN.matcher(result).replaceAll("");
|
||||
return result;
|
||||
}
|
||||
|
||||
private String convertPointXPointerToCfi(String xpointer) {
|
||||
XPointerParseResult parseResult = parseXPointer(xpointer);
|
||||
String cfiPath = buildCfiPathFromElement(parseResult.element());
|
||||
|
||||
if (parseResult.textOffset() != null) {
|
||||
// CFI requires /1 to indicate first text node child before the character offset
|
||||
cfiPath += "/1:" + parseResult.textOffset();
|
||||
}
|
||||
|
||||
return buildFullCfi(cfiPath);
|
||||
}
|
||||
|
||||
private String convertRangeXPointerToCfi(String startXPointer, String endXPointer) {
|
||||
XPointerParseResult startResult = parseXPointer(startXPointer);
|
||||
XPointerParseResult endResult = parseXPointer(endXPointer);
|
||||
|
||||
String startPath = buildCfiPathFromElement(startResult.element());
|
||||
String endPath = buildCfiPathFromElement(endResult.element());
|
||||
|
||||
if (startResult.textOffset() != null) {
|
||||
// CFI requires /1 to indicate first text node child before the character offset
|
||||
startPath += "/1:" + startResult.textOffset();
|
||||
}
|
||||
if (endResult.textOffset() != null) {
|
||||
// CFI requires /1 to indicate first text node child before the character offset
|
||||
endPath += "/1:" + endResult.textOffset();
|
||||
}
|
||||
|
||||
if (!startPath.equals(endPath)) {
|
||||
return buildFullCfi(startPath + "," + endPath);
|
||||
}
|
||||
return buildFullCfi(startPath);
|
||||
}
|
||||
|
||||
private XPointerParseResult parseXPointer(String xpointer) {
|
||||
Matcher textOffsetMatcher = XPOINTER_TEXT_OFFSET_PATTERN.matcher(xpointer);
|
||||
Integer textOffset = null;
|
||||
String elementPath = xpointer;
|
||||
|
||||
if (textOffsetMatcher.find()) {
|
||||
textOffset = Integer.parseInt(textOffsetMatcher.group(1));
|
||||
elementPath = XPOINTER_TEXT_OFFSET_PATTERN.matcher(xpointer).replaceAll("");
|
||||
}
|
||||
|
||||
Element element = resolveXPointerPath(elementPath);
|
||||
if (element == null) {
|
||||
throw new IllegalArgumentException("Cannot resolve XPointer path: " + elementPath);
|
||||
}
|
||||
|
||||
return new XPointerParseResult(element, textOffset);
|
||||
}
|
||||
|
||||
private Element resolveXPointerPath(String path) {
|
||||
Matcher pathMatcher = XPOINTER_DOC_FRAGMENT_PATTERN.matcher(path);
|
||||
if (!pathMatcher.matches()) {
|
||||
throw new IllegalArgumentException("Invalid XPointer format: " + path);
|
||||
}
|
||||
|
||||
String elementPath = pathMatcher.group(2);
|
||||
Element body = document.body();
|
||||
|
||||
if (body == null) {
|
||||
throw new IllegalArgumentException("Document has no body element");
|
||||
}
|
||||
|
||||
if (elementPath == null || elementPath.isEmpty()) {
|
||||
return body;
|
||||
}
|
||||
|
||||
// Extract the final indexed segment (e.g., p[54] from /div/div/p[54])
|
||||
// KOReader counts elements globally in the document, not hierarchically
|
||||
String[] segments = elementPath.split("/");
|
||||
String lastSegment = null;
|
||||
for (int i = segments.length - 1; i >= 0; i--) {
|
||||
if (!segments[i].isEmpty()) {
|
||||
lastSegment = segments[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (lastSegment == null) {
|
||||
return body;
|
||||
}
|
||||
|
||||
Matcher withIndexMatcher = XPOINTER_SEGMENT_WITH_INDEX_PATTERN.matcher(lastSegment);
|
||||
if (withIndexMatcher.matches()) {
|
||||
String tagName = withIndexMatcher.group(1);
|
||||
int index = Integer.parseInt(withIndexMatcher.group(2)) - 1;
|
||||
|
||||
// Find the element globally in the document body
|
||||
Elements allElements = body.getElementsByTag(tagName);
|
||||
if (index < allElements.size()) {
|
||||
log.debug("XPointer resolved: found {}[{}] among {} total in document",
|
||||
tagName, index + 1, allElements.size());
|
||||
return allElements.get(index);
|
||||
} else {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Element index %d out of bounds for tag %s (found %d in document)",
|
||||
index, tagName, allElements.size()));
|
||||
}
|
||||
}
|
||||
|
||||
// For non-indexed segments, fall back to hierarchical traversal
|
||||
Element current = body;
|
||||
for (String segment : segments) {
|
||||
if (segment.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Matcher segWithIndex = XPOINTER_SEGMENT_WITH_INDEX_PATTERN.matcher(segment);
|
||||
Matcher segWithoutIndex = XPOINTER_SEGMENT_WITHOUT_INDEX_PATTERN.matcher(segment);
|
||||
|
||||
String tagName;
|
||||
int index;
|
||||
|
||||
if (segWithIndex.matches()) {
|
||||
tagName = segWithIndex.group(1);
|
||||
index = Integer.parseInt(segWithIndex.group(2)) - 1;
|
||||
} else if (segWithoutIndex.matches()) {
|
||||
tagName = segWithoutIndex.group(1);
|
||||
index = 0;
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid XPointer segment: " + segment);
|
||||
}
|
||||
|
||||
Elements children = current.children();
|
||||
List<Element> matchingChildren = new ArrayList<>();
|
||||
for (Element child : children) {
|
||||
if (child.tagName().equalsIgnoreCase(tagName)) {
|
||||
matchingChildren.add(child);
|
||||
}
|
||||
}
|
||||
|
||||
if (index < matchingChildren.size()) {
|
||||
current = matchingChildren.get(index);
|
||||
} else {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Element index %d out of bounds for tag %s (found %d)",
|
||||
index, tagName, matchingChildren.size()));
|
||||
}
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
private CfiPathResult parseCfiPath(String contentPath) {
|
||||
List<CfiStep> steps = new ArrayList<>();
|
||||
Integer textOffset = null;
|
||||
|
||||
Matcher stepMatcher = CFI_PATH_STEP_PATTERN.matcher(contentPath);
|
||||
while (stepMatcher.find()) {
|
||||
int stepIndex = Integer.parseInt(stepMatcher.group(1));
|
||||
String assertion = stepMatcher.group(2);
|
||||
String offsetStr = stepMatcher.group(3);
|
||||
|
||||
if (offsetStr != null) {
|
||||
textOffset = Integer.parseInt(offsetStr);
|
||||
}
|
||||
|
||||
steps.add(new CfiStep(stepIndex, assertion));
|
||||
}
|
||||
|
||||
return new CfiPathResult(steps, textOffset);
|
||||
}
|
||||
|
||||
private Element resolveElementFromCfiSteps(List<CfiStep> steps) {
|
||||
Element current = document.body();
|
||||
if (current == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (CfiStep step : steps) {
|
||||
int childIndex = (step.index() / 2) - 1;
|
||||
|
||||
Elements children = current.children();
|
||||
if (childIndex < 0 || childIndex >= children.size()) {
|
||||
log.debug("CFI step {} out of bounds (children: {})", step.index(), children.size());
|
||||
return current;
|
||||
}
|
||||
|
||||
current = children.get(childIndex);
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
private String buildCfiPathFromElement(Element element) {
|
||||
List<String> pathParts = new ArrayList<>();
|
||||
Element current = element;
|
||||
|
||||
while (current != null && !current.tagName().equalsIgnoreCase("body")) {
|
||||
Element parent = current.parent();
|
||||
if (parent == null) {
|
||||
break;
|
||||
}
|
||||
|
||||
int siblingIndex = 0;
|
||||
for (Element sibling : parent.children()) {
|
||||
siblingIndex++;
|
||||
if (sibling == current) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int cfiStep = siblingIndex * 2;
|
||||
pathParts.add(0, "/" + cfiStep);
|
||||
|
||||
current = parent;
|
||||
}
|
||||
|
||||
pathParts.add(0, "/4");
|
||||
|
||||
return String.join("", pathParts);
|
||||
}
|
||||
|
||||
private String buildFullCfi(String contentPath) {
|
||||
int spineStep = (spineItemIndex + 1) * 2;
|
||||
return String.format("epubcfi(/6/%d!%s)", spineStep, contentPath);
|
||||
}
|
||||
|
||||
private String buildXPointerPath(Element targetElement) {
|
||||
List<String> pathParts = new ArrayList<>();
|
||||
Element current = targetElement;
|
||||
|
||||
Element root = document.body() != null ? document.body().parent() : null;
|
||||
while (current != null && current != root) {
|
||||
Element parent = current.parent();
|
||||
if (parent == null) {
|
||||
break;
|
||||
}
|
||||
|
||||
String tagName = current.tagName().toLowerCase();
|
||||
|
||||
int siblingIndex = 0;
|
||||
int totalSameTagSiblings = 0;
|
||||
for (Element sibling : parent.children()) {
|
||||
if (sibling.tagName().equalsIgnoreCase(tagName)) {
|
||||
if (sibling == current) {
|
||||
siblingIndex = totalSameTagSiblings;
|
||||
}
|
||||
totalSameTagSiblings++;
|
||||
}
|
||||
}
|
||||
|
||||
if (totalSameTagSiblings == 1) {
|
||||
pathParts.add(0, tagName);
|
||||
} else {
|
||||
pathParts.add(0, String.format("%s[%d]", tagName, siblingIndex + 1));
|
||||
}
|
||||
|
||||
current = parent;
|
||||
}
|
||||
|
||||
StringBuilder xpointer = new StringBuilder("/body/DocFragment[")
|
||||
.append(spineItemIndex + 1)
|
||||
.append("]");
|
||||
|
||||
if (!pathParts.isEmpty() && pathParts.get(0).startsWith("body")) {
|
||||
pathParts.remove(0);
|
||||
}
|
||||
|
||||
xpointer.append("/body");
|
||||
|
||||
if (!pathParts.isEmpty()) {
|
||||
xpointer.append("/").append(String.join("/", pathParts));
|
||||
}
|
||||
|
||||
return xpointer.toString();
|
||||
}
|
||||
|
||||
private String handleTextOffset(Element element, int cfiOffset) {
|
||||
List<TextNode> textNodes = collectTextNodes(element);
|
||||
|
||||
int totalChars = 0;
|
||||
TextNode targetTextNode = null;
|
||||
int offsetInNode = 0;
|
||||
|
||||
for (TextNode textNode : textNodes) {
|
||||
String nodeText = textNode.text();
|
||||
int nodeLength = nodeText.length();
|
||||
|
||||
if (totalChars + nodeLength >= cfiOffset) {
|
||||
targetTextNode = textNode;
|
||||
offsetInNode = cfiOffset - totalChars;
|
||||
break;
|
||||
}
|
||||
|
||||
totalChars += nodeLength;
|
||||
}
|
||||
|
||||
if (targetTextNode == null) {
|
||||
return buildXPointerPath(element);
|
||||
}
|
||||
|
||||
Element textParent = (Element) targetTextNode.parent();
|
||||
while (textParent != null && !isSignificantElement(textParent)) {
|
||||
textParent = textParent.parent();
|
||||
}
|
||||
|
||||
if (textParent == null) {
|
||||
textParent = element;
|
||||
}
|
||||
|
||||
String basePath = buildXPointerPath(textParent);
|
||||
return basePath + "/text()." + offsetInNode;
|
||||
}
|
||||
|
||||
private List<TextNode> collectTextNodes(Element element) {
|
||||
List<TextNode> textNodes = new ArrayList<>();
|
||||
collectTextNodesRecursive(element, textNodes);
|
||||
return textNodes;
|
||||
}
|
||||
|
||||
private void collectTextNodesRecursive(Node node, List<TextNode> textNodes) {
|
||||
for (Node child : node.childNodes()) {
|
||||
if (child instanceof TextNode textNode) {
|
||||
String text = textNode.text();
|
||||
if (!text.isEmpty()) {
|
||||
textNodes.add(textNode);
|
||||
}
|
||||
} else if (child instanceof Element) {
|
||||
collectTextNodesRecursive(child, textNodes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isSignificantElement(Element element) {
|
||||
String tagName = element.tagName().toLowerCase();
|
||||
return !INLINE_ELEMENTS.contains(tagName);
|
||||
}
|
||||
|
||||
@Getter
|
||||
public static class XPointerResult {
|
||||
private final String xpointer;
|
||||
private final String pos0;
|
||||
private final String pos1;
|
||||
|
||||
public XPointerResult(String xpointer, String pos0, String pos1) {
|
||||
this.xpointer = xpointer;
|
||||
this.pos0 = pos0;
|
||||
this.pos1 = pos1;
|
||||
}
|
||||
|
||||
public XPointerResult(String xpointer) {
|
||||
this(xpointer, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
private record XPointerParseResult(Element element, Integer textOffset) {}
|
||||
|
||||
private record CfiStep(int index, String assertion) {}
|
||||
|
||||
private record CfiPathResult(List<CfiStep> steps, Integer textOffset) {}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
package org.booklore.util.koreader;
|
||||
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.util.epub.EpubContentReader;
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.grimmory.epub4j.cfi.CfiConverter;
|
||||
import org.grimmory.epub4j.cfi.XPointerResult;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -26,19 +29,19 @@ public class EpubCfiService {
|
||||
.build();
|
||||
}
|
||||
|
||||
public CfiConvertor.XPointerResult convertCfiToXPointer(File epubFile, String cfi) {
|
||||
int spineIndex = CfiConvertor.extractSpineIndex(cfi);
|
||||
CfiConvertor converter = createConverter(epubFile, spineIndex);
|
||||
public XPointerResult convertCfiToXPointer(File epubFile, String cfi) {
|
||||
int spineIndex = CfiConverter.extractSpineIndex(cfi);
|
||||
CfiConverter converter = createConverter(epubFile, spineIndex);
|
||||
return converter.cfiToXPointer(cfi);
|
||||
}
|
||||
|
||||
public CfiConvertor.XPointerResult convertCfiToXPointer(Path epubPath, String cfi) {
|
||||
public XPointerResult convertCfiToXPointer(Path epubPath, String cfi) {
|
||||
return convertCfiToXPointer(epubPath.toFile(), cfi);
|
||||
}
|
||||
|
||||
public String convertXPointerToCfi(File epubFile, String xpointer) {
|
||||
int spineIndex = CfiConvertor.extractSpineIndex(xpointer);
|
||||
CfiConvertor converter = createConverter(epubFile, spineIndex);
|
||||
int spineIndex = CfiConverter.extractSpineIndex(xpointer);
|
||||
CfiConverter converter = createConverter(epubFile, spineIndex);
|
||||
return converter.xPointerToCfi(xpointer);
|
||||
}
|
||||
|
||||
@@ -47,8 +50,14 @@ public class EpubCfiService {
|
||||
}
|
||||
|
||||
public String convertXPointerRangeToCfi(File epubFile, String startXPointer, String endXPointer) {
|
||||
int spineIndex = CfiConvertor.extractSpineIndex(startXPointer);
|
||||
CfiConvertor converter = createConverter(epubFile, spineIndex);
|
||||
int startSpineIndex = extractSpineIndex(startXPointer);
|
||||
int endSpineIndex = extractSpineIndex(endXPointer);
|
||||
|
||||
if (startSpineIndex != endSpineIndex) {
|
||||
throw ApiError.INVALID_INPUT.createException("Start and end XPointers must reference the same spine index");
|
||||
}
|
||||
|
||||
CfiConverter converter = createConverter(epubFile, startSpineIndex);
|
||||
return converter.xPointerToCfi(startXPointer, endXPointer);
|
||||
}
|
||||
|
||||
@@ -57,8 +66,8 @@ public class EpubCfiService {
|
||||
}
|
||||
|
||||
public String convertCfiToProgressXPointer(File epubFile, String cfi) {
|
||||
CfiConvertor.XPointerResult result = convertCfiToXPointer(epubFile, cfi);
|
||||
return CfiConvertor.normalizeProgressXPointer(result.getXpointer());
|
||||
XPointerResult result = convertCfiToXPointer(epubFile, cfi);
|
||||
return CfiConverter.normalizeProgressXPointer(result.getXpointer());
|
||||
}
|
||||
|
||||
public String convertCfiToProgressXPointer(Path epubPath, String cfi) {
|
||||
@@ -67,8 +76,8 @@ public class EpubCfiService {
|
||||
|
||||
public boolean validateCfi(File epubFile, String cfi) {
|
||||
try {
|
||||
int spineIndex = CfiConvertor.extractSpineIndex(cfi);
|
||||
CfiConvertor converter = createConverter(epubFile, spineIndex);
|
||||
int spineIndex = CfiConverter.extractSpineIndex(cfi);
|
||||
CfiConverter converter = createConverter(epubFile, spineIndex);
|
||||
return converter.validateCfi(cfi);
|
||||
} catch (Exception e) {
|
||||
log.debug("CFI validation failed: {}", e.getMessage());
|
||||
@@ -78,8 +87,8 @@ public class EpubCfiService {
|
||||
|
||||
public boolean validateXPointer(File epubFile, String xpointer) {
|
||||
try {
|
||||
int spineIndex = CfiConvertor.extractSpineIndex(xpointer);
|
||||
CfiConvertor converter = createConverter(epubFile, spineIndex);
|
||||
int spineIndex = CfiConverter.extractSpineIndex(xpointer);
|
||||
CfiConverter converter = createConverter(epubFile, spineIndex);
|
||||
return converter.validateXPointer(xpointer);
|
||||
} catch (Exception e) {
|
||||
log.debug("XPointer validation failed: {}", e.getMessage());
|
||||
@@ -88,19 +97,19 @@ public class EpubCfiService {
|
||||
}
|
||||
|
||||
public int extractSpineIndex(String cfiOrXPointer) {
|
||||
return CfiConvertor.extractSpineIndex(cfiOrXPointer);
|
||||
return CfiConverter.extractSpineIndex(cfiOrXPointer);
|
||||
}
|
||||
|
||||
public int getSpineSize(File epubFile) {
|
||||
return EpubContentReader.getSpineSize(epubFile);
|
||||
}
|
||||
|
||||
public CfiConvertor createConverter(File epubFile, int spineIndex) {
|
||||
public CfiConverter createConverter(File epubFile, int spineIndex) {
|
||||
Document doc = getCachedDocument(epubFile, spineIndex);
|
||||
return new CfiConvertor(doc, spineIndex);
|
||||
return new CfiConverter(new JsoupDocumentNavigator(doc), spineIndex);
|
||||
}
|
||||
|
||||
public CfiConvertor createConverter(Path epubPath, int spineIndex) {
|
||||
public CfiConverter createConverter(Path epubPath, int spineIndex) {
|
||||
return createConverter(epubPath.toFile(), spineIndex);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package org.booklore.util.koreader;
|
||||
|
||||
import org.grimmory.epub4j.cfi.DocumentNavigator;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.jsoup.nodes.Element;
|
||||
import org.jsoup.nodes.Node;
|
||||
import org.jsoup.nodes.TextNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Jsoup-backed implementation of epub4j's {@link DocumentNavigator}, enabling
|
||||
* the library's {@link org.grimmory.epub4j.cfi.CfiConverter} to navigate a
|
||||
* Jsoup-parsed HTML document.
|
||||
*/
|
||||
public class JsoupDocumentNavigator implements DocumentNavigator {
|
||||
|
||||
private final Document document;
|
||||
|
||||
public JsoupDocumentNavigator(Document document) {
|
||||
this.document = document;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getBody() {
|
||||
return document.body();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Object> getChildElements(Object element) {
|
||||
Element el = (Element) element;
|
||||
return new ArrayList<>(el.children());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Object> getElementsByTag(Object root, String tagName) {
|
||||
Element el = (Element) root;
|
||||
return new ArrayList<>(el.getElementsByTag(tagName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTagName(Object element) {
|
||||
Element el = (Element) element;
|
||||
return el.tagName().toLowerCase();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getParent(Object element) {
|
||||
Element el = (Element) element;
|
||||
return el.parent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> collectTextContent(Object element) {
|
||||
List<String> texts = new ArrayList<>();
|
||||
collectTexts((Node) element, texts);
|
||||
return texts;
|
||||
}
|
||||
|
||||
private void collectTexts(Node node, List<String> texts) {
|
||||
for (Node child : node.childNodes()) {
|
||||
if (child instanceof TextNode textNode) {
|
||||
String text = textNode.text();
|
||||
if (!text.isEmpty()) {
|
||||
texts.add(text);
|
||||
}
|
||||
} else if (child instanceof Element) {
|
||||
collectTexts(child, texts);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+159
-397
@@ -1,7 +1,5 @@
|
||||
package org.booklore.service.reader;
|
||||
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.response.EpubBookInfo;
|
||||
import org.booklore.model.dto.response.EpubManifestItem;
|
||||
@@ -10,6 +8,8 @@ import org.booklore.model.dto.response.EpubTocItem;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.util.FileUtils;
|
||||
import org.grimmory.epub4j.domain.*;
|
||||
import org.grimmory.epub4j.epub.EpubWriter;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -21,14 +21,12 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -51,52 +49,6 @@ class EpubReaderServiceTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private static final String CONTAINER_XML = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
|
||||
<rootfiles>
|
||||
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
|
||||
</rootfiles>
|
||||
</container>
|
||||
""";
|
||||
|
||||
private static final String CONTENT_OPF = """
|
||||
<?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/">
|
||||
<dc:title>Test Book</dc:title>
|
||||
<dc:creator>Test Author</dc:creator>
|
||||
<dc:language>en</dc:language>
|
||||
</metadata>
|
||||
<manifest>
|
||||
<item id="chapter1" href="chapter1.xhtml" media-type="application/xhtml+xml"/>
|
||||
<item id="chapter2" href="chapter2.xhtml" media-type="application/xhtml+xml"/>
|
||||
<item id="style" href="style.css" media-type="text/css"/>
|
||||
<item id="cover" href="cover.jpg" media-type="image/jpeg" properties="cover-image"/>
|
||||
<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>
|
||||
</manifest>
|
||||
<spine>
|
||||
<itemref idref="chapter1"/>
|
||||
<itemref idref="chapter2"/>
|
||||
</spine>
|
||||
</package>
|
||||
""";
|
||||
|
||||
private static final String NAV_XHTML = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
|
||||
<head><title>Navigation</title></head>
|
||||
<body>
|
||||
<nav epub:type="toc">
|
||||
<ol>
|
||||
<li><a href="chapter1.xhtml">Chapter 1</a></li>
|
||||
<li><a href="chapter2.xhtml">Chapter 2</a></li>
|
||||
</ol>
|
||||
</nav>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
bookEntity = new BookEntity();
|
||||
@@ -105,6 +57,38 @@ class EpubReaderServiceTest {
|
||||
Files.deleteIfExists(epubPath);
|
||||
}
|
||||
|
||||
private void writeTestEpub() throws Exception {
|
||||
Book book = new Book();
|
||||
Metadata metadata = book.getMetadata();
|
||||
metadata.addTitle("Test Book");
|
||||
metadata.addAuthor(new Author("Test", "Author"));
|
||||
metadata.setLanguage("en");
|
||||
|
||||
Resource chapter1 = new Resource(
|
||||
"<html><body>Chapter 1 content</body></html>".getBytes(StandardCharsets.UTF_8),
|
||||
"chapter1.xhtml");
|
||||
chapter1.setId("chapter1");
|
||||
Resource chapter2 = new Resource(
|
||||
"<html><body>Chapter 2 content</body></html>".getBytes(StandardCharsets.UTF_8),
|
||||
"chapter2.xhtml");
|
||||
chapter2.setId("chapter2");
|
||||
Resource style = new Resource("body { color: black; }".getBytes(StandardCharsets.UTF_8), "style.css");
|
||||
style.setId("style");
|
||||
|
||||
byte[] coverData = new byte[5000];
|
||||
Resource cover = new Resource(coverData, "cover.jpg");
|
||||
cover.setId("cover");
|
||||
book.setCoverImage(cover);
|
||||
|
||||
book.addSection("Chapter 1", chapter1);
|
||||
book.addSection("Chapter 2", chapter2);
|
||||
book.getResources().add(style);
|
||||
|
||||
try (FileOutputStream fos = new FileOutputStream(epubPath.toFile())) {
|
||||
new EpubWriter().write(book, fos);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetBookInfo_Success() throws Exception {
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||
@@ -112,27 +96,19 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
assertNotNull(bookInfo);
|
||||
assertEquals("OEBPS/content.opf", bookInfo.getContainerPath());
|
||||
assertEquals("OEBPS/", bookInfo.getRootPath());
|
||||
assertEquals("Test Book", bookInfo.getMetadata().get("title"));
|
||||
assertEquals("Test Author", bookInfo.getMetadata().get("creator"));
|
||||
assertEquals("en", bookInfo.getMetadata().get("language"));
|
||||
assertEquals(5, bookInfo.getManifest().size());
|
||||
assertEquals(2, bookInfo.getSpine().size());
|
||||
assertEquals("OEBPS/cover.jpg", bookInfo.getCoverPath());
|
||||
}
|
||||
assertNotNull(bookInfo);
|
||||
assertNotNull(bookInfo.getContainerPath());
|
||||
assertNotNull(bookInfo.getRootPath());
|
||||
assertEquals("Test Book", bookInfo.getMetadata().get("title"));
|
||||
assertEquals("Test Author", bookInfo.getMetadata().get("creator"));
|
||||
assertEquals("en", bookInfo.getMetadata().get("language"));
|
||||
assertFalse(bookInfo.getManifest().isEmpty());
|
||||
assertEquals(2, bookInfo.getSpine().size());
|
||||
assertNotNull(bookInfo.getCoverPath());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,24 +127,14 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
// First call - should parse
|
||||
EpubBookInfo bookInfo1 = epubReaderService.getBookInfo(1L);
|
||||
// Second call - should use cache
|
||||
EpubBookInfo bookInfo2 = epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
|
||||
// First call - should parse
|
||||
EpubBookInfo bookInfo1 = epubReaderService.getBookInfo(1L);
|
||||
// Second call - should use cache
|
||||
EpubBookInfo bookInfo2 = epubReaderService.getBookInfo(1L);
|
||||
|
||||
assertSame(bookInfo1, bookInfo2);
|
||||
// ZipFile builder should be called only once for parsing
|
||||
verify(builder, times(1)).get();
|
||||
}
|
||||
assertSame(bookInfo1, bookInfo2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,31 +145,23 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
byte[] chapterContent = "<html><body>Chapter 1 content</body></html>".getBytes(StandardCharsets.UTF_8);
|
||||
ZipFile zipFile = createMockZipFileWithStreamableEntry("OEBPS/chapter1.xhtml", chapterContent);
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
// First populate the cache
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
// Find the chapter1 href from the manifest
|
||||
String chapter1Href = bookInfo.getManifest().stream()
|
||||
.filter(m -> "chapter1".equals(m.getId()))
|
||||
.map(EpubManifestItem::getHref)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
epubReaderService.streamFile(1L, chapter1Href, outputStream);
|
||||
|
||||
// Reset mock for streaming call
|
||||
reset(builder);
|
||||
when(builder.setPath(epubPath)).thenReturn(builder);
|
||||
when(builder.setCharset(any(Charset.class))).thenReturn(builder);
|
||||
when(builder.setUseUnicodeExtraFields(anyBoolean())).thenReturn(builder);
|
||||
when(builder.get()).thenReturn(zipFile);
|
||||
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
epubReaderService.streamFile(1L, "chapter1.xhtml", outputStream);
|
||||
|
||||
assertArrayEquals(chapterContent, outputStream.toByteArray());
|
||||
}
|
||||
String content = outputStream.toString(StandardCharsets.UTF_8);
|
||||
assertTrue(content.contains("Chapter 1 content"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,22 +172,14 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
assertThrows(FileNotFoundException.class,
|
||||
() -> epubReaderService.streamFile(1L, "nonexistent.xhtml", outputStream));
|
||||
}
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
assertThrows(FileNotFoundException.class,
|
||||
() -> epubReaderService.streamFile(1L, "nonexistent.xhtml", outputStream));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,22 +190,14 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
assertThrows(FileNotFoundException.class,
|
||||
() -> epubReaderService.streamFile(1L, "../../../etc/passwd", outputStream));
|
||||
}
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
assertThrows(FileNotFoundException.class,
|
||||
() -> epubReaderService.streamFile(1L, "../../../etc/passwd", outputStream));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,31 +208,16 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
byte[] containerContent = CONTAINER_XML.getBytes(StandardCharsets.UTF_8);
|
||||
ZipFile zipFile = createMockZipFileWithStreamableEntry("META-INF/container.xml", containerContent);
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
epubReaderService.streamFile(1L, "META-INF/container.xml", outputStream);
|
||||
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
|
||||
// Reset mock for streaming call
|
||||
reset(builder);
|
||||
when(builder.setPath(epubPath)).thenReturn(builder);
|
||||
when(builder.setCharset(any(Charset.class))).thenReturn(builder);
|
||||
when(builder.setUseUnicodeExtraFields(anyBoolean())).thenReturn(builder);
|
||||
when(builder.get()).thenReturn(zipFile);
|
||||
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
epubReaderService.streamFile(1L, "META-INF/container.xml", outputStream);
|
||||
|
||||
assertArrayEquals(containerContent, outputStream.toByteArray());
|
||||
}
|
||||
String content = outputStream.toString(StandardCharsets.UTF_8);
|
||||
assertTrue(content.contains("rootfile"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -301,22 +228,19 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
// First populate the cache
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
// Find chapter1 href
|
||||
String chapter1Href = bookInfo.getManifest().stream()
|
||||
.filter(m -> "chapter1".equals(m.getId()))
|
||||
.map(EpubManifestItem::getHref)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
|
||||
assertEquals("application/xhtml+xml", epubReaderService.getContentType(1L, "chapter1.xhtml"));
|
||||
assertEquals("text/css", epubReaderService.getContentType(1L, "style.css"));
|
||||
assertEquals("image/jpeg", epubReaderService.getContentType(1L, "cover.jpg"));
|
||||
}
|
||||
assertEquals("application/xhtml+xml", epubReaderService.getContentType(1L, chapter1Href));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -327,24 +251,16 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
|
||||
// Unknown file should use fallback guessing
|
||||
assertEquals("image/png", epubReaderService.getContentType(1L, "image.png"));
|
||||
assertEquals("image/gif", epubReaderService.getContentType(1L, "animation.gif"));
|
||||
assertEquals("font/woff2", epubReaderService.getContentType(1L, "font.woff2"));
|
||||
assertEquals("application/octet-stream", epubReaderService.getContentType(1L, "unknown.xyz"));
|
||||
}
|
||||
// Unknown file should use fallback guessing
|
||||
assertEquals("image/png", epubReaderService.getContentType(1L, "image.png"));
|
||||
assertEquals("image/gif", epubReaderService.getContentType(1L, "animation.gif"));
|
||||
assertEquals("font/woff2", epubReaderService.getContentType(1L, "font.woff2"));
|
||||
assertEquals("application/octet-stream", epubReaderService.getContentType(1L, "unknown.xyz"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,18 +271,18 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFileWithSizes();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
// Find chapter1 href and verify size > 0
|
||||
String chapter1Href = bookInfo.getManifest().stream()
|
||||
.filter(m -> "chapter1".equals(m.getId()))
|
||||
.map(EpubManifestItem::getHref)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
assertEquals(1024L, epubReaderService.getFileSize(1L, "chapter1.xhtml"));
|
||||
assertEquals(2048L, epubReaderService.getFileSize(1L, "chapter2.xhtml"));
|
||||
}
|
||||
assertTrue(epubReaderService.getFileSize(1L, chapter1Href) > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,17 +293,9 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
|
||||
assertEquals(0L, epubReaderService.getFileSize(1L, "nonexistent.xhtml"));
|
||||
}
|
||||
assertEquals(0L, epubReaderService.getFileSize(1L, "nonexistent.xhtml"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,24 +306,16 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
List<EpubSpineItem> spine = bookInfo.getSpine();
|
||||
assertEquals(2, spine.size());
|
||||
assertEquals("chapter1", spine.get(0).getIdref());
|
||||
assertEquals("OEBPS/chapter1.xhtml", spine.get(0).getHref());
|
||||
assertEquals("chapter2", spine.get(1).getIdref());
|
||||
assertEquals("OEBPS/chapter2.xhtml", spine.get(1).getHref());
|
||||
}
|
||||
List<EpubSpineItem> spine = bookInfo.getSpine();
|
||||
assertEquals(2, spine.size());
|
||||
assertEquals("chapter1", spine.get(0).getIdref());
|
||||
assertTrue(spine.get(0).getHref().contains("chapter1"));
|
||||
assertEquals("chapter2", spine.get(1).getIdref());
|
||||
assertTrue(spine.get(1).getHref().contains("chapter2"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,25 +326,17 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
EpubTocItem toc = bookInfo.getToc();
|
||||
assertNotNull(toc);
|
||||
assertEquals("Table of Contents", toc.getLabel());
|
||||
assertNotNull(toc.getChildren());
|
||||
assertEquals(2, toc.getChildren().size());
|
||||
assertEquals("Chapter 1", toc.getChildren().get(0).getLabel());
|
||||
assertEquals("Chapter 2", toc.getChildren().get(1).getLabel());
|
||||
}
|
||||
EpubTocItem toc = bookInfo.getToc();
|
||||
assertNotNull(toc);
|
||||
assertEquals("Table of Contents", toc.getLabel());
|
||||
assertNotNull(toc.getChildren());
|
||||
assertEquals(2, toc.getChildren().size());
|
||||
assertEquals("Chapter 1", toc.getChildren().get(0).getLabel());
|
||||
assertEquals("Chapter 2", toc.getChildren().get(1).getLabel());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -455,37 +347,19 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
// Find cover item - should have cover-image property
|
||||
EpubManifestItem coverItem = bookInfo.getManifest().stream()
|
||||
.filter(item -> "cover".equals(item.getId()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
// Find cover item
|
||||
EpubManifestItem coverItem = bookInfo.getManifest().stream()
|
||||
.filter(item -> "cover".equals(item.getId()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
assertNotNull(coverItem);
|
||||
assertNotNull(coverItem.getProperties());
|
||||
assertTrue(coverItem.getProperties().contains("cover-image"));
|
||||
|
||||
// Find nav item
|
||||
EpubManifestItem navItem = bookInfo.getManifest().stream()
|
||||
.filter(item -> "nav".equals(item.getId()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
assertNotNull(navItem);
|
||||
assertNotNull(navItem.getProperties());
|
||||
assertTrue(navItem.getProperties().contains("nav"));
|
||||
}
|
||||
assertNotNull(coverItem);
|
||||
assertNotNull(coverItem.getProperties());
|
||||
assertTrue(coverItem.getProperties().contains("cover-image"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -496,142 +370,30 @@ class EpubReaderServiceTest {
|
||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||
|
||||
byte[] chapterContent = "<html><body>Chapter 1 content</body></html>".getBytes(StandardCharsets.UTF_8);
|
||||
ZipFile zipFile = createMockZipFileWithStreamableEntry("OEBPS/chapter1.xhtml", chapterContent);
|
||||
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
|
||||
writeTestEpub();
|
||||
|
||||
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
|
||||
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
|
||||
// First populate the cache
|
||||
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
|
||||
|
||||
Files.createFile(epubPath);
|
||||
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
|
||||
// Find the chapter1 relative path (without rootPath prefix)
|
||||
String chapter1Href = bookInfo.getManifest().stream()
|
||||
.filter(m -> "chapter1".equals(m.getId()))
|
||||
.map(EpubManifestItem::getHref)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
// First populate the cache
|
||||
epubReaderService.getBookInfo(1L);
|
||||
// Strip rootPath to get relative path, then add leading slash
|
||||
String rootPath = bookInfo.getRootPath();
|
||||
String relativePath = chapter1Href.startsWith(rootPath)
|
||||
? chapter1Href.substring(rootPath.length())
|
||||
: chapter1Href;
|
||||
|
||||
// Reset mock for streaming call
|
||||
reset(builder);
|
||||
when(builder.setPath(epubPath)).thenReturn(builder);
|
||||
when(builder.setCharset(any(Charset.class))).thenReturn(builder);
|
||||
when(builder.setUseUnicodeExtraFields(anyBoolean())).thenReturn(builder);
|
||||
when(builder.get()).thenReturn(zipFile);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
// Path with leading slash should work
|
||||
epubReaderService.streamFile(1L, "/" + relativePath, outputStream);
|
||||
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
// Path with leading slash should work
|
||||
epubReaderService.streamFile(1L, "/chapter1.xhtml", outputStream);
|
||||
|
||||
assertArrayEquals(chapterContent, outputStream.toByteArray());
|
||||
}
|
||||
String content = outputStream.toString(StandardCharsets.UTF_8);
|
||||
assertTrue(content.contains("Chapter 1 content"));
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods to create mock ZipFile objects
|
||||
|
||||
private ZipFile createMockZipFile() throws Exception {
|
||||
ZipFile zipFile = mock(ZipFile.class);
|
||||
|
||||
// Container entry - use thenAnswer to return fresh stream each time
|
||||
ZipArchiveEntry containerEntry = mock(ZipArchiveEntry.class);
|
||||
when(containerEntry.getSize()).thenReturn((long) CONTAINER_XML.length());
|
||||
when(zipFile.getEntry("META-INF/container.xml")).thenReturn(containerEntry);
|
||||
when(zipFile.getInputStream(containerEntry))
|
||||
.thenAnswer(inv -> new ByteArrayInputStream(CONTAINER_XML.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
// OPF entry
|
||||
ZipArchiveEntry opfEntry = mock(ZipArchiveEntry.class);
|
||||
when(opfEntry.getSize()).thenReturn((long) CONTENT_OPF.length());
|
||||
when(zipFile.getEntry("OEBPS/content.opf")).thenReturn(opfEntry);
|
||||
when(zipFile.getInputStream(opfEntry))
|
||||
.thenAnswer(inv -> new ByteArrayInputStream(CONTENT_OPF.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
// Nav entry
|
||||
ZipArchiveEntry navEntry = mock(ZipArchiveEntry.class);
|
||||
when(navEntry.getSize()).thenReturn((long) NAV_XHTML.length());
|
||||
when(zipFile.getEntry("OEBPS/nav.xhtml")).thenReturn(navEntry);
|
||||
when(zipFile.getInputStream(navEntry))
|
||||
.thenAnswer(inv -> new ByteArrayInputStream(NAV_XHTML.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
// Chapter entries with sizes
|
||||
ZipArchiveEntry chapter1Entry = mock(ZipArchiveEntry.class);
|
||||
when(chapter1Entry.getSize()).thenReturn(100L);
|
||||
when(zipFile.getEntry("OEBPS/chapter1.xhtml")).thenReturn(chapter1Entry);
|
||||
|
||||
ZipArchiveEntry chapter2Entry = mock(ZipArchiveEntry.class);
|
||||
when(chapter2Entry.getSize()).thenReturn(200L);
|
||||
when(zipFile.getEntry("OEBPS/chapter2.xhtml")).thenReturn(chapter2Entry);
|
||||
|
||||
ZipArchiveEntry styleEntry = mock(ZipArchiveEntry.class);
|
||||
when(styleEntry.getSize()).thenReturn(50L);
|
||||
when(zipFile.getEntry("OEBPS/style.css")).thenReturn(styleEntry);
|
||||
|
||||
ZipArchiveEntry coverEntry = mock(ZipArchiveEntry.class);
|
||||
when(coverEntry.getSize()).thenReturn(5000L);
|
||||
when(zipFile.getEntry("OEBPS/cover.jpg")).thenReturn(coverEntry);
|
||||
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
private ZipFile createMockZipFileWithStreamableEntry(String entryPath, byte[] content) throws Exception {
|
||||
ZipFile zipFile = createMockZipFile();
|
||||
|
||||
ZipArchiveEntry entry = mock(ZipArchiveEntry.class);
|
||||
when(entry.getSize()).thenReturn((long) content.length);
|
||||
when(zipFile.getEntry(entryPath)).thenReturn(entry);
|
||||
when(zipFile.getInputStream(entry)).thenAnswer(inv -> new ByteArrayInputStream(content));
|
||||
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
private ZipFile createMockZipFileWithSizes() throws Exception {
|
||||
ZipFile zipFile = mock(ZipFile.class);
|
||||
|
||||
// Container entry - use thenAnswer for fresh stream each time
|
||||
ZipArchiveEntry containerEntry = mock(ZipArchiveEntry.class);
|
||||
when(containerEntry.getSize()).thenReturn((long) CONTAINER_XML.length());
|
||||
when(zipFile.getEntry("META-INF/container.xml")).thenReturn(containerEntry);
|
||||
when(zipFile.getInputStream(containerEntry))
|
||||
.thenAnswer(inv -> new ByteArrayInputStream(CONTAINER_XML.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
// OPF entry
|
||||
ZipArchiveEntry opfEntry = mock(ZipArchiveEntry.class);
|
||||
when(opfEntry.getSize()).thenReturn((long) CONTENT_OPF.length());
|
||||
when(zipFile.getEntry("OEBPS/content.opf")).thenReturn(opfEntry);
|
||||
when(zipFile.getInputStream(opfEntry))
|
||||
.thenAnswer(inv -> new ByteArrayInputStream(CONTENT_OPF.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
// Nav entry
|
||||
ZipArchiveEntry navEntry = mock(ZipArchiveEntry.class);
|
||||
when(navEntry.getSize()).thenReturn((long) NAV_XHTML.length());
|
||||
when(zipFile.getEntry("OEBPS/nav.xhtml")).thenReturn(navEntry);
|
||||
when(zipFile.getInputStream(navEntry))
|
||||
.thenAnswer(inv -> new ByteArrayInputStream(NAV_XHTML.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
// Chapter entries with specific sizes
|
||||
ZipArchiveEntry chapter1Entry = mock(ZipArchiveEntry.class);
|
||||
when(chapter1Entry.getSize()).thenReturn(1024L);
|
||||
when(zipFile.getEntry("OEBPS/chapter1.xhtml")).thenReturn(chapter1Entry);
|
||||
|
||||
ZipArchiveEntry chapter2Entry = mock(ZipArchiveEntry.class);
|
||||
when(chapter2Entry.getSize()).thenReturn(2048L);
|
||||
when(zipFile.getEntry("OEBPS/chapter2.xhtml")).thenReturn(chapter2Entry);
|
||||
|
||||
ZipArchiveEntry styleEntry = mock(ZipArchiveEntry.class);
|
||||
when(styleEntry.getSize()).thenReturn(512L);
|
||||
when(zipFile.getEntry("OEBPS/style.css")).thenReturn(styleEntry);
|
||||
|
||||
ZipArchiveEntry coverEntry = mock(ZipArchiveEntry.class);
|
||||
when(coverEntry.getSize()).thenReturn(10240L);
|
||||
when(zipFile.getEntry("OEBPS/cover.jpg")).thenReturn(coverEntry);
|
||||
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
private ZipFile.Builder createMockZipFileBuilder(ZipFile zipFile) throws Exception {
|
||||
ZipFile.Builder builder = mock(ZipFile.Builder.class, RETURNS_DEEP_STUBS);
|
||||
when(builder.setPath(epubPath)).thenReturn(builder);
|
||||
when(builder.setCharset(any(Charset.class))).thenReturn(builder);
|
||||
when(builder.setUseUnicodeExtraFields(anyBoolean())).thenReturn(builder);
|
||||
when(builder.get()).thenReturn(zipFile);
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package org.booklore.util.epub;
|
||||
|
||||
import io.documentnode.epub4j.domain.Book;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.epub.EpubWriter;
|
||||
import org.grimmory.epub4j.domain.Book;
|
||||
import org.grimmory.epub4j.domain.Resource;
|
||||
import org.grimmory.epub4j.epub.EpubWriter;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -71,7 +71,7 @@ class EpubContentReaderTest {
|
||||
private File createTestEpub(String filename, boolean withSpine) throws IOException {
|
||||
Book book = new Book();
|
||||
book.getMetadata().addTitle("Test Book");
|
||||
book.getMetadata().addAuthor(new io.documentnode.epub4j.domain.Author("Test Author"));
|
||||
book.getMetadata().addAuthor(new org.grimmory.epub4j.domain.Author("Test Author"));
|
||||
|
||||
if (withSpine) {
|
||||
Resource chapter1 = new Resource(CHAPTER1_CONTENT.getBytes(StandardCharsets.UTF_8), "chapter1.xhtml");
|
||||
@@ -198,12 +198,13 @@ class EpubContentReaderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineSize_nonExistentFile_returnsZero() {
|
||||
void getSpineSize_nonExistentFile_throwsException() {
|
||||
File nonExistent = new File(tempDir.toFile(), "nonexistent.epub");
|
||||
|
||||
int size = EpubContentReader.getSpineSize(nonExistent);
|
||||
|
||||
assertEquals(0, size);
|
||||
assertThrows(
|
||||
EpubContentReader.EpubReadException.class,
|
||||
() -> EpubContentReader.getSpineSize(nonExistent)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+51
-48
@@ -1,5 +1,7 @@
|
||||
package org.booklore.util.koreader;
|
||||
|
||||
import org.grimmory.epub4j.cfi.CfiConverter;
|
||||
import org.grimmory.epub4j.cfi.XPointerResult;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -12,7 +14,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CfiConvertorTest {
|
||||
class CfiConverterTest {
|
||||
|
||||
private Document simpleDocument;
|
||||
private Document complexDocument;
|
||||
@@ -66,42 +68,42 @@ class CfiConvertorTest {
|
||||
@Test
|
||||
void extractSpineIndex_fromCfi_spineIndex0() {
|
||||
String cfi = "epubcfi(/6/2!/4/2)";
|
||||
int result = CfiConvertor.extractSpineIndex(cfi);
|
||||
int result = CfiConverter.extractSpineIndex(cfi);
|
||||
assertEquals(0, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromCfi_spineIndex1() {
|
||||
String cfi = "epubcfi(/6/4!/4/2)";
|
||||
int result = CfiConvertor.extractSpineIndex(cfi);
|
||||
int result = CfiConverter.extractSpineIndex(cfi);
|
||||
assertEquals(1, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromCfi_spineIndex5() {
|
||||
String cfi = "epubcfi(/6/12!/4/2:10)";
|
||||
int result = CfiConvertor.extractSpineIndex(cfi);
|
||||
int result = CfiConverter.extractSpineIndex(cfi);
|
||||
assertEquals(5, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromXPointer_spineIndex0() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p";
|
||||
int result = CfiConvertor.extractSpineIndex(xpointer);
|
||||
int result = CfiConverter.extractSpineIndex(xpointer);
|
||||
assertEquals(0, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromXPointer_spineIndex2() {
|
||||
String xpointer = "/body/DocFragment[3]/body/section/div/p";
|
||||
int result = CfiConvertor.extractSpineIndex(xpointer);
|
||||
int result = CfiConverter.extractSpineIndex(xpointer);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromXPointer_withTextOffset() {
|
||||
String xpointer = "/body/DocFragment[5]/body/p/text().42";
|
||||
int result = CfiConvertor.extractSpineIndex(xpointer);
|
||||
int result = CfiConverter.extractSpineIndex(xpointer);
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@@ -110,19 +112,19 @@ class CfiConvertorTest {
|
||||
@ValueSource(strings = {" ", "\t", "\n"})
|
||||
void extractSpineIndex_nullOrEmpty_throwsException(String input) {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> CfiConvertor.extractSpineIndex(input));
|
||||
() -> CfiConverter.extractSpineIndex(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_invalidFormat_throwsException() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> CfiConvertor.extractSpineIndex("invalid/path/here"));
|
||||
() -> CfiConverter.extractSpineIndex("invalid/path/here"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_malformedCfi_throwsException() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> CfiConvertor.extractSpineIndex("epubcfi(malformed)"));
|
||||
() -> CfiConverter.extractSpineIndex("epubcfi(malformed)"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,7 +133,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_simpleElement() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
@@ -144,7 +146,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_withTextOffset() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().5";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
@@ -156,7 +158,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_differentSpineIndex() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 2);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 2);
|
||||
String xpointer = "/body/DocFragment[3]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
@@ -167,7 +169,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_bodyOnly() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String xpointer = "/body/DocFragment[1]/body";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
@@ -178,7 +180,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_rangeWithStartAndEnd() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String startXPointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().0";
|
||||
String endXPointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().10";
|
||||
|
||||
@@ -190,7 +192,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_invalidPath_throwsException() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> converter.xPointerToCfi("/invalid/path"));
|
||||
@@ -202,10 +204,10 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void cfiToXPointer_simpleElement() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String cfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getXpointer());
|
||||
@@ -214,10 +216,10 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void cfiToXPointer_withTextOffset() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String cfi = "epubcfi(/6/2!/4/2/2:5)";
|
||||
|
||||
CfiConvertor.XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.getXpointer().contains("/text()."));
|
||||
@@ -225,7 +227,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void cfiToXPointer_spineIndexMismatch_throwsException() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String cfi = "epubcfi(/6/4!/4/2)"; // Spine index 1, but converter is 0
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
@@ -234,7 +236,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void cfiToXPointer_invalidCfiFormat_throwsException() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> converter.cfiToXPointer("not-a-valid-cfi"));
|
||||
@@ -242,7 +244,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void cfiToXPointer_malformedCfi_throwsException() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> converter.cfiToXPointer("epubcfi(invalid)"));
|
||||
@@ -254,7 +256,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void validateCfi_validCfi_returnsTrue() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String cfi = "epubcfi(/6/2!/4/2)";
|
||||
|
||||
assertTrue(converter.validateCfi(cfi));
|
||||
@@ -262,7 +264,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void validateCfi_invalidCfi_returnsFalse() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
|
||||
assertFalse(converter.validateCfi("invalid"));
|
||||
assertFalse(converter.validateCfi("epubcfi(malformed)"));
|
||||
@@ -270,7 +272,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void validateCfi_wrongSpineIndex_returnsFalse() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String cfi = "epubcfi(/6/10!/4/2)"; // Spine index 4, converter is 0
|
||||
|
||||
assertFalse(converter.validateCfi(cfi));
|
||||
@@ -278,7 +280,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void validateXPointer_validXPointer_returnsTrue() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
assertTrue(converter.validateXPointer(xpointer));
|
||||
@@ -286,7 +288,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void validateXPointer_invalidXPointer_returnsFalse() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
|
||||
assertFalse(converter.validateXPointer("/invalid/path"));
|
||||
assertFalse(converter.validateXPointer("not-an-xpointer"));
|
||||
@@ -294,11 +296,12 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void validateXPointer_withPos1_returnsTrue() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String pos0 = "/body/DocFragment[1]/body/div[1]/p[1]/text().0";
|
||||
String pos1 = "/body/DocFragment[1]/body/div[1]/p[1]/text().10";
|
||||
|
||||
assertTrue(converter.validateXPointer(pos0, pos1));
|
||||
assertTrue(converter.validateXPointer(pos0));
|
||||
assertTrue(converter.validateXPointer(pos1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -309,7 +312,7 @@ class CfiConvertorTest {
|
||||
void normalizeProgressXPointer_removesTextOffset() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p/text().42";
|
||||
|
||||
String result = CfiConvertor.normalizeProgressXPointer(xpointer);
|
||||
String result = CfiConverter.normalizeProgressXPointer(xpointer);
|
||||
|
||||
assertEquals("/body/DocFragment[1]/body/div/p", result);
|
||||
}
|
||||
@@ -318,7 +321,7 @@ class CfiConvertorTest {
|
||||
void normalizeProgressXPointer_removesNodeSuffix() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p.5";
|
||||
|
||||
String result = CfiConvertor.normalizeProgressXPointer(xpointer);
|
||||
String result = CfiConverter.normalizeProgressXPointer(xpointer);
|
||||
|
||||
assertEquals("/body/DocFragment[1]/body/div/p", result);
|
||||
}
|
||||
@@ -327,7 +330,7 @@ class CfiConvertorTest {
|
||||
void normalizeProgressXPointer_removesBothTextOffsetAndNodeSuffix() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p/text().10.5";
|
||||
|
||||
String result = CfiConvertor.normalizeProgressXPointer(xpointer);
|
||||
String result = CfiConverter.normalizeProgressXPointer(xpointer);
|
||||
|
||||
assertEquals("/body/DocFragment[1]/body/div/p", result);
|
||||
}
|
||||
@@ -336,14 +339,14 @@ class CfiConvertorTest {
|
||||
void normalizeProgressXPointer_noChangesNeeded() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p";
|
||||
|
||||
String result = CfiConvertor.normalizeProgressXPointer(xpointer);
|
||||
String result = CfiConverter.normalizeProgressXPointer(xpointer);
|
||||
|
||||
assertEquals("/body/DocFragment[1]/body/div/p", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeProgressXPointer_nullInput_returnsNull() {
|
||||
assertNull(CfiConvertor.normalizeProgressXPointer(null));
|
||||
assertNull(CfiConverter.normalizeProgressXPointer(null));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -353,7 +356,7 @@ class CfiConvertorTest {
|
||||
"/body/DocFragment[1]/body/div[2]/p[3]/text().5, /body/DocFragment[1]/body/div[2]/p[3]"
|
||||
})
|
||||
void normalizeProgressXPointer_variousInputs(String input, String expected) {
|
||||
assertEquals(expected, CfiConvertor.normalizeProgressXPointer(input));
|
||||
assertEquals(expected, CfiConverter.normalizeProgressXPointer(input));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,7 +365,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_nestedElements() {
|
||||
CfiConvertor converter = new CfiConvertor(complexDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(complexDocument), 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/section[1]/div[1]/p[1]";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
@@ -373,7 +376,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_deeplyNestedElement() {
|
||||
CfiConvertor converter = new CfiConvertor(complexDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(complexDocument), 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/section[1]/div[1]/h1";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
@@ -383,7 +386,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_secondSection() {
|
||||
CfiConvertor converter = new CfiConvertor(complexDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(complexDocument), 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/section[2]/div/p";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
@@ -397,11 +400,11 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void roundTrip_xPointerToCfiAndBack() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String originalXPointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = converter.xPointerToCfi(originalXPointer);
|
||||
CfiConvertor.XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
|
||||
assertNotNull(result.getXpointer());
|
||||
// The path should resolve to the same element, though format may differ
|
||||
@@ -410,10 +413,10 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void roundTrip_cfiToXPointerAndBack() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String originalCfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult xpointerResult = converter.cfiToXPointer(originalCfi);
|
||||
XPointerResult xpointerResult = converter.cfiToXPointer(originalCfi);
|
||||
String cfi = converter.xPointerToCfi(xpointerResult.getXpointer());
|
||||
|
||||
assertNotNull(cfi);
|
||||
@@ -427,7 +430,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void constructor_withDefaultSpineIndex() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
|
||||
// Should work with spine index 0
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
@@ -439,7 +442,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_elementWithoutIndex() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
// Using tag without index (implicit [1])
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p";
|
||||
|
||||
@@ -450,7 +453,7 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_largeSpineIndex() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 99);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 99);
|
||||
String xpointer = "/body/DocFragment[100]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
@@ -461,10 +464,10 @@ class CfiConvertorTest {
|
||||
|
||||
@Test
|
||||
void xPointerResult_allFieldsPopulated() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
CfiConverter converter = new CfiConverter(new JsoupDocumentNavigator(simpleDocument), 0);
|
||||
String cfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
|
||||
assertNotNull(result.getXpointer());
|
||||
assertNotNull(result.getPos0());
|
||||
@@ -1,9 +1,12 @@
|
||||
package org.booklore.util.koreader;
|
||||
|
||||
import io.documentnode.epub4j.domain.Author;
|
||||
import io.documentnode.epub4j.domain.Book;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.epub.EpubWriter;
|
||||
import org.booklore.exception.APIException;
|
||||
import org.grimmory.epub4j.cfi.CfiConverter;
|
||||
import org.grimmory.epub4j.cfi.XPointerResult;
|
||||
import org.grimmory.epub4j.domain.Author;
|
||||
import org.grimmory.epub4j.domain.Book;
|
||||
import org.grimmory.epub4j.domain.Resource;
|
||||
import org.grimmory.epub4j.epub.EpubWriter;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -99,22 +102,22 @@ class EpubCfiServiceTest {
|
||||
|
||||
@Test
|
||||
void createConverter_validFile_returnsConverter() {
|
||||
CfiConvertor converter = service.createConverter(testEpubFile, 0);
|
||||
CfiConverter converter = service.createConverter(testEpubFile, 0);
|
||||
|
||||
assertNotNull(converter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createConverter_withPath_returnsConverter() {
|
||||
CfiConvertor converter = service.createConverter(testEpubFile.toPath(), 0);
|
||||
CfiConverter converter = service.createConverter(testEpubFile.toPath(), 0);
|
||||
|
||||
assertNotNull(converter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createConverter_differentSpineIndices_returnsDifferentConverters() {
|
||||
CfiConvertor converter0 = service.createConverter(testEpubFile, 0);
|
||||
CfiConvertor converter1 = service.createConverter(testEpubFile, 1);
|
||||
CfiConverter converter0 = service.createConverter(testEpubFile, 0);
|
||||
CfiConverter converter1 = service.createConverter(testEpubFile, 1);
|
||||
|
||||
assertNotNull(converter0);
|
||||
assertNotNull(converter1);
|
||||
@@ -163,7 +166,7 @@ class EpubCfiServiceTest {
|
||||
void convertCfiToXPointer_validCfi_returnsXPointerResult() {
|
||||
String cfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult result = service.convertCfiToXPointer(testEpubFile, cfi);
|
||||
XPointerResult result = service.convertCfiToXPointer(testEpubFile, cfi);
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getXpointer());
|
||||
@@ -174,7 +177,7 @@ class EpubCfiServiceTest {
|
||||
void convertCfiToXPointer_withPath_returnsXPointerResult() {
|
||||
String cfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult result = service.convertCfiToXPointer(testEpubFile.toPath(), cfi);
|
||||
XPointerResult result = service.convertCfiToXPointer(testEpubFile.toPath(), cfi);
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getXpointer());
|
||||
@@ -204,6 +207,15 @@ class EpubCfiServiceTest {
|
||||
|
||||
assertNotNull(cfi);
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertXPointerRangeToCfi_mismatchedSpineIndices_throwsAPIException() {
|
||||
String startXPointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().0";
|
||||
String endXPointer = "/body/DocFragment[2]/body/div[1]/p[1]/text().10";
|
||||
|
||||
assertThrows(APIException.class, () ->
|
||||
service.convertXPointerRangeToCfi(testEpubFile, startXPointer, endXPointer));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@@ -306,8 +318,8 @@ class EpubCfiServiceTest {
|
||||
|
||||
@Test
|
||||
void createConverter_calledTwice_usesCachedDocument() {
|
||||
CfiConvertor converter1 = service.createConverter(testEpubFile, 0);
|
||||
CfiConvertor converter2 = service.createConverter(testEpubFile, 0);
|
||||
CfiConverter converter1 = service.createConverter(testEpubFile, 0);
|
||||
CfiConverter converter2 = service.createConverter(testEpubFile, 0);
|
||||
|
||||
assertNotNull(converter1);
|
||||
assertNotNull(converter2);
|
||||
@@ -320,7 +332,7 @@ class EpubCfiServiceTest {
|
||||
|
||||
service.evictCache(testEpubFile);
|
||||
|
||||
CfiConvertor converter = service.createConverter(testEpubFile, 0);
|
||||
CfiConverter converter = service.createConverter(testEpubFile, 0);
|
||||
assertNotNull(converter);
|
||||
}
|
||||
|
||||
@@ -331,7 +343,7 @@ class EpubCfiServiceTest {
|
||||
|
||||
service.clearCache();
|
||||
|
||||
CfiConvertor converter = service.createConverter(testEpubFile, 0);
|
||||
CfiConverter converter = service.createConverter(testEpubFile, 0);
|
||||
assertNotNull(converter);
|
||||
}
|
||||
|
||||
@@ -341,9 +353,9 @@ class EpubCfiServiceTest {
|
||||
service.createConverter(testEpubFile, 1);
|
||||
service.createConverter(testEpubFile, 2);
|
||||
|
||||
CfiConvertor converter0 = service.createConverter(testEpubFile, 0);
|
||||
CfiConvertor converter1 = service.createConverter(testEpubFile, 1);
|
||||
CfiConvertor converter2 = service.createConverter(testEpubFile, 2);
|
||||
CfiConverter converter0 = service.createConverter(testEpubFile, 0);
|
||||
CfiConverter converter1 = service.createConverter(testEpubFile, 1);
|
||||
CfiConverter converter2 = service.createConverter(testEpubFile, 2);
|
||||
|
||||
assertNotNull(converter0);
|
||||
assertNotNull(converter1);
|
||||
@@ -359,7 +371,7 @@ class EpubCfiServiceTest {
|
||||
String originalXPointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = service.convertXPointerToCfi(testEpubFile, originalXPointer);
|
||||
CfiConvertor.XPointerResult result = service.convertCfiToXPointer(testEpubFile, cfi);
|
||||
XPointerResult result = service.convertCfiToXPointer(testEpubFile, cfi);
|
||||
|
||||
assertNotNull(result.getXpointer());
|
||||
assertTrue(result.getXpointer().contains("/body/DocFragment[1]/body"));
|
||||
@@ -369,7 +381,7 @@ class EpubCfiServiceTest {
|
||||
void roundTrip_cfiToXPointerAndBack() {
|
||||
String originalCfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult xpointerResult = service.convertCfiToXPointer(testEpubFile, originalCfi);
|
||||
XPointerResult xpointerResult = service.convertCfiToXPointer(testEpubFile, originalCfi);
|
||||
String cfi = service.convertXPointerToCfi(testEpubFile, xpointerResult.getXpointer());
|
||||
|
||||
assertNotNull(cfi);
|
||||
@@ -388,8 +400,8 @@ class EpubCfiServiceTest {
|
||||
service.createConverter(testEpubFile, 0);
|
||||
service.createConverter(secondEpub, 0);
|
||||
|
||||
CfiConvertor converter1 = service.createConverter(testEpubFile, 0);
|
||||
CfiConvertor converter2 = service.createConverter(secondEpub, 0);
|
||||
CfiConverter converter1 = service.createConverter(testEpubFile, 0);
|
||||
CfiConverter converter2 = service.createConverter(secondEpub, 0);
|
||||
|
||||
assertNotNull(converter1);
|
||||
assertNotNull(converter2);
|
||||
@@ -404,7 +416,7 @@ class EpubCfiServiceTest {
|
||||
|
||||
service.evictCache(testEpubFile);
|
||||
|
||||
CfiConvertor converter = service.createConverter(secondEpub, 0);
|
||||
CfiConverter converter = service.createConverter(secondEpub, 0);
|
||||
assertNotNull(converter);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user