fix(api): Use fixed-layout epub format in Kobo sync when necessary (Booklore PR Port) (#16)

* fix(api): Correct format for fixed-layout epub when using Kobo Sync

* chore: Cleanup duplicate code

* feat: Cache fixed-layout property in db

* fix: Missing nullcheck in after retrieving BookFileEntity

* fix: Remove memory leak in EpubReaderService.java

* chore: Avoid opening the epub twice for fixed-layout extraction

* chore: Fix DB migration from rebase

---------

Co-authored-by: brios <127139797+balazs-szucs@users.noreply.github.com>
This commit is contained in:
Yussur Mustafa Oraji
2026-04-22 17:26:30 -04:00
committed by Zach Yale
co-authored by brios
parent 5f1d34d716
commit dc1fa74af7
8 changed files with 277 additions and 299 deletions
@@ -68,6 +68,7 @@ public class BookMetadata {
private String thumbnailUrl; private String thumbnailUrl;
private List<BookReview> bookReviews; private List<BookReview> bookReviews;
private Double rating; private Double rating;
private Boolean isFixedLayout;
private Boolean allMetadataLocked; private Boolean allMetadataLocked;
@@ -48,6 +48,10 @@ public class BookFileEntity {
@Column(name = "book_type", nullable = false) @Column(name = "book_type", nullable = false)
private BookFileType bookType; private BookFileType bookType;
@Column(name = "is_fixed_layout", nullable = false)
@Builder.Default
private boolean isFixedLayout = false;
@Column(name = "archive_type") @Column(name = "archive_type")
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private ArchiveUtils.ArchiveType archiveType; private ArchiveUtils.ArchiveType archiveType;
@@ -96,6 +100,10 @@ public class BookFileEntity {
return isBookFormat; return isBookFormat;
} }
public boolean isFixedLayout() {
return isFixedLayout;
}
public Path getFullFilePath() { public Path getFullFilePath() {
if (book == null || book.getLibraryPath() == null || book.getLibraryPath().getPath() == null if (book == null || book.getLibraryPath() == null || book.getLibraryPath().getPath() == null
|| fileSubPath == null || fileName == null) { || fileSubPath == null || fileName == null) {
@@ -3,4 +3,5 @@ package org.booklore.model.enums;
public enum KoboBookFormat { public enum KoboBookFormat {
EPUB3, EPUB3,
KEPUB, KEPUB,
EPUB3FL,
} }
@@ -168,5 +168,10 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
.collect(Collectors.toSet()); .collect(Collectors.toSet());
bookCreatorService.addTagsToBook(validTags, bookEntity); bookCreatorService.addTagsToBook(validTags, bookEntity);
} }
bookEntity.getBookFiles().stream()
.filter(bf -> bf.getBookType() == BookFileType.EPUB && bf.isBook())
.findFirst()
.ifPresent(ent -> ent.setFixedLayout(Boolean.TRUE.equals(epubMetadata.getIsFixedLayout())));
} }
} }
@@ -19,6 +19,7 @@ import org.booklore.service.opds.MagicShelfBookService;
import org.booklore.util.kobo.KoboUrlBuilder; import org.booklore.util.kobo.KoboUrlBuilder;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.math.BigDecimal; import java.math.BigDecimal;
@@ -328,7 +329,9 @@ public class KoboEntitlementService {
boolean isCbxFile = primaryFile.getBookType() == BookFileType.CBX; boolean isCbxFile = primaryFile.getBookType() == BookFileType.CBX;
if (koboSettings != null) { if (koboSettings != null) {
if (isEpubFile && koboSettings.isConvertToKepub()) { if (isEpubFile && primaryFile.isFixedLayout()) {
bookFormat = KoboBookFormat.EPUB3FL;
} else if (isEpubFile && koboSettings.isConvertToKepub()) {
bookFormat = KoboBookFormat.KEPUB; bookFormat = KoboBookFormat.KEPUB;
} else if (isCbxFile && koboSettings.isConvertCbxToEpub()) { } else if (isCbxFile && koboSettings.isConvertCbxToEpub()) {
bookFormat = KoboBookFormat.EPUB3; bookFormat = KoboBookFormat.EPUB3;
@@ -12,6 +12,7 @@ import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.BookMetadata;
import org.booklore.service.metadata.BookLoreMetadata; import org.booklore.service.metadata.BookLoreMetadata;
import org.booklore.service.reader.EpubReaderService;
import org.booklore.util.SecureXmlUtils; import org.booklore.util.SecureXmlUtils;
import org.springframework.boot.configurationprocessor.json.JSONException; import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject; import org.springframework.boot.configurationprocessor.json.JSONObject;
@@ -149,25 +150,9 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
} }
private String findManifestCoverByHeuristic(File epubFile) { private String findManifestCoverByHeuristic(File epubFile) {
try (ZipFile zip = new ZipFile(epubFile)) { try {
DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true); Document doc = EpubReaderService.getOPFDocument(epubFile);
FileHeader containerHdr = zip.getFileHeader("META-INF/container.xml");
if (containerHdr == null) return null;
try (InputStream cis = zip.getInputStream(containerHdr)) {
Document containerDoc = builder.parse(cis);
NodeList roots = containerDoc.getElementsByTagName("rootfile");
if (roots.getLength() == 0) return null;
String opfPath = ((Element) roots.item(0)).getAttribute("full-path");
if (StringUtils.isBlank(opfPath)) return null;
FileHeader opfHdr = zip.getFileHeader(opfPath);
if (opfHdr == null) return null;
try (InputStream in = zip.getInputStream(opfHdr)) {
Document doc = builder.parse(in);
NodeList manifestItems = doc.getElementsByTagName("item"); NodeList manifestItems = doc.getElementsByTagName("item");
for (int i = 0; i < manifestItems.getLength(); i++) { for (int i = 0; i < manifestItems.getLength(); i++) {
@@ -179,9 +164,7 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
if ((id != null && id.toLowerCase().contains("cover")) || (href != null && href.toLowerCase().contains("cover"))) { if ((id != null && id.toLowerCase().contains("cover")) || (href != null && href.toLowerCase().contains("cover"))) {
if (mediaType != null && mediaType.startsWith("image/")) { if (mediaType != null && mediaType.startsWith("image/")) {
String decodedHref = URLDecoder.decode(href, StandardCharsets.UTF_8); String decodedHref = URLDecoder.decode(href, StandardCharsets.UTF_8);
return resolvePath(opfPath, decodedHref); return resolvePath(EpubReaderService.getOPFPath(epubFile), decodedHref);
}
}
} }
} }
} }
@@ -210,24 +193,9 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
@Override @Override
public BookMetadata extractMetadata(File epubFile) { public BookMetadata extractMetadata(File epubFile) {
try (ZipFile zip = new ZipFile(epubFile)) { try {
DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true); Document doc = EpubReaderService.getOPFDocument(epubFile);
FileHeader containerHdr = zip.getFileHeader("META-INF/container.xml");
if (containerHdr == null) return null;
try (InputStream cis = zip.getInputStream(containerHdr)) {
Document containerDoc = builder.parse(cis);
NodeList roots = containerDoc.getElementsByTagName("rootfile");
if (roots.getLength() == 0) return null;
String opfPath = ((Element) roots.item(0)).getAttribute("full-path");
if (StringUtils.isBlank(opfPath)) return null;
FileHeader opfHdr = zip.getFileHeader(opfPath);
if (opfHdr == null) return null;
try (InputStream in = zip.getInputStream(opfHdr)) {
Document doc = builder.parse(in);
Element metadata = (Element) doc.getElementsByTagNameNS("*", "metadata").item(0); Element metadata = (Element) doc.getElementsByTagNameNS("*", "metadata").item(0);
if (metadata == null) return null; if (metadata == null) return null;
@@ -278,6 +246,10 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
creatorRoleById.put(refines.substring(1), content.toLowerCase()); creatorRoleById.put(refines.substring(1), content.toLowerCase());
} }
if ("rendition:layout".equals(prop) && "pre-paginated".equals(content)) {
builderMeta.isFixedLayout(true);
}
if (!seriesFound && ((BookLoreMetadata.NS_PREFIX + ":series").equals(prop) || "calibre:series".equals(name) || "belongs-to-collection".equals(prop))) { if (!seriesFound && ((BookLoreMetadata.NS_PREFIX + ":series").equals(prop) || "calibre:series".equals(name) || "belongs-to-collection".equals(prop))) {
builderMeta.seriesName(content); builderMeta.seriesName(content);
seriesFound = true; seriesFound = true;
@@ -471,9 +443,6 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
} }
return extractedMetadata; return extractedMetadata;
}
}
} catch (Exception e) { } catch (Exception e) {
log.error("Failed to read metadata from EPUB file {}: {}", epubFile.getName(), e.getMessage(), e); log.error("Failed to read metadata from EPUB file {}: {}", epubFile.getName(), e.getMessage(), e);
return null; return null;
@@ -625,25 +594,8 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
} }
private String findCoverImageHrefInOpf(File epubFile) { private String findCoverImageHrefInOpf(File epubFile) {
try (ZipFile zip = new ZipFile(epubFile)) { try {
DocumentBuilder builder = SecureXmlUtils.createSecureDocumentBuilder(true); Document doc = EpubReaderService.getOPFDocument(epubFile);
FileHeader containerHdr = zip.getFileHeader("META-INF/container.xml");
if (containerHdr == null) return null;
try (InputStream cis = zip.getInputStream(containerHdr)) {
Document containerDoc = builder.parse(cis);
NodeList roots = containerDoc.getElementsByTagName("rootfile");
if (roots.getLength() == 0) return null;
String opfPath = ((Element) roots.item(0)).getAttribute("full-path");
if (StringUtils.isBlank(opfPath)) return null;
FileHeader opfHdr = zip.getFileHeader(opfPath);
if (opfHdr == null) return null;
try (InputStream in = zip.getInputStream(opfHdr)) {
Document doc = builder.parse(in);
NodeList manifestItems = doc.getElementsByTagName("item"); NodeList manifestItems = doc.getElementsByTagName("item");
for (int i = 0; i < manifestItems.getLength(); i++) { for (int i = 0; i < manifestItems.getLength(); i++) {
@@ -652,9 +604,7 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
if (properties != null && properties.contains("cover-image")) { if (properties != null && properties.contains("cover-image")) {
String href = item.getAttribute("href"); String href = item.getAttribute("href");
String decodedHref = URLDecoder.decode(href, StandardCharsets.UTF_8); String decodedHref = URLDecoder.decode(href, StandardCharsets.UTF_8);
return resolvePath(opfPath, decodedHref); return resolvePath(EpubReaderService.getOPFPath(epubFile), decodedHref);
}
}
} }
} }
} catch (Exception e) { } catch (Exception e) {
@@ -15,11 +15,6 @@ import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.enums.BookFileType; import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookRepository; import org.booklore.repository.BookRepository;
import org.booklore.util.FileUtils; import org.booklore.util.FileUtils;
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.apache.pdfbox.io.IOUtils;
import org.booklore.util.SecureXmlUtils; import org.booklore.util.SecureXmlUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.w3c.dom.Document; import org.w3c.dom.Document;
@@ -335,7 +330,7 @@ public class EpubReaderService {
} }
} }
private String parseContainerXml(ZipFile zipFile) throws Exception { private static String parseContainerXml(ZipFile zipFile) throws Exception {
Document doc = parseXmlEntry(zipFile, CONTAINER_PATH); Document doc = parseXmlEntry(zipFile, CONTAINER_PATH);
NodeList rootfiles = doc.getElementsByTagNameNS(CONTAINER_NS, "rootfile"); NodeList rootfiles = doc.getElementsByTagNameNS(CONTAINER_NS, "rootfile");
if (rootfiles.getLength() == 0) { if (rootfiles.getLength() == 0) {
@@ -352,6 +347,19 @@ public class EpubReaderService {
return fullPath; return fullPath;
} }
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> parseManifest(Document opfDoc, String rootPath, ZipFile zipFile) {
List<EpubManifestItem> manifest = new ArrayList<>(); List<EpubManifestItem> manifest = new ArrayList<>();
NodeList items = opfDoc.getElementsByTagNameNS(OPF_NS, "item"); NodeList items = opfDoc.getElementsByTagNameNS(OPF_NS, "item");
@@ -638,7 +646,7 @@ public class EpubReaderService {
return null; return null;
} }
private Document parseXmlEntry(ZipFile zipFile, String entryPath) throws Exception { private static Document parseXmlEntry(ZipFile zipFile, String entryPath) throws Exception {
ZipArchiveEntry entry = zipFile.getEntry(entryPath); ZipArchiveEntry entry = zipFile.getEntry(entryPath);
if (entry == null) { if (entry == null) {
throw new FileNotFoundException("Entry not found: " + entryPath); throw new FileNotFoundException("Entry not found: " + entryPath);
@@ -0,0 +1,2 @@
ALTER TABLE book_file
ADD COLUMN IF NOT EXISTS is_fixed_layout BOOLEAN NOT NULL DEFAULT FALSE;