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:
+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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user