fix(kobo): fix epub cfi parsing for kobo progress sync (#861)

This commit is contained in:
Alex
2026-04-25 14:49:08 +01:00
committed by GitHub
parent 59fcfb1689
commit 3fda81b539
2 changed files with 53 additions and 41 deletions
@@ -5,7 +5,9 @@ import org.booklore.util.epub.EpubContentReader;
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.grimmory.epub4j.cfi.CfiExpression;
import org.grimmory.epub4j.cfi.CfiConverter; import org.grimmory.epub4j.cfi.CfiConverter;
import org.grimmory.epub4j.cfi.CfiParser;
import org.grimmory.epub4j.cfi.XPointerResult; import org.grimmory.epub4j.cfi.XPointerResult;
import org.jsoup.Jsoup; import org.jsoup.Jsoup;
import org.jsoup.nodes.Document; import org.jsoup.nodes.Document;
@@ -21,17 +23,11 @@ import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j @Slf4j
@Service @Service
public class EpubCfiService { public class EpubCfiService {
private static final Pattern XPOINTER_BODY_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_PATTERN = Pattern.compile("^(\\w+)(?:\\[(\\d+)])?$");
private final Cache<String, Document> documentCache; private final Cache<String, Document> documentCache;
public EpubCfiService() { public EpubCfiService() {
@@ -94,7 +90,8 @@ public class EpubCfiService {
try { try {
String normalizedCfi = normalizeContentDocumentCfi(cfi); String normalizedCfi = normalizeContentDocumentCfi(cfi);
int spineIndex = CfiConverter.extractSpineIndex(normalizedCfi); CfiExpression expression = CfiParser.parse(normalizedCfi);
int spineIndex = expression.spineIndex();
String href = EpubContentReader.getSpineItemHref(epubFile, spineIndex); String href = EpubContentReader.getSpineItemHref(epubFile, spineIndex);
if (href == null || href.isBlank()) { if (href == null || href.isBlank()) {
return Optional.empty(); return Optional.empty();
@@ -105,8 +102,7 @@ public class EpubCfiService {
return Optional.empty(); return Optional.empty();
} }
XPointerResult xpointerResult = convertCfiToXPointer(epubFile, normalizedCfi); Integer sourceOffset = resolveSourceOffset(getCachedDocument(epubFile, spineIndex), expression);
Integer sourceOffset = resolveSourceOffset(getCachedDocument(epubFile, spineIndex), xpointerResult.getXpointer());
Float contentSourceProgressPercent = sourceOffset == null Float contentSourceProgressPercent = sourceOffset == null
? null ? null
: clampPercent((sourceOffset / (float) Math.max(html.length(), 1)) * 100f); : clampPercent((sourceOffset / (float) Math.max(html.length(), 1)) * 100f);
@@ -200,25 +196,19 @@ public class EpubCfiService {
return cfi.replaceFirst("!/4(?=/)", "!"); return cfi.replaceFirst("!/4(?=/)", "!");
} }
private Integer resolveSourceOffset(Document document, String xpointer) { private Integer resolveSourceOffset(Document document, CfiExpression expression) {
if (xpointer == null || xpointer.isBlank()) { if (document == null || expression == null) {
return null; return null;
} }
Matcher pathMatcher = XPOINTER_BODY_PATTERN.matcher(xpointer); List<CfiExpression.PathStep> targetSteps = expression.isRange() && expression.rangeEndSteps() != null
if (!pathMatcher.matches()) { ? expression.rangeEndSteps()
throw new IllegalArgumentException("Invalid XPointer format: " + xpointer); : expression.contentSteps();
} Integer textOffset = expression.isRange() && expression.rangeEndOffset() != null
? expression.rangeEndOffset()
: expression.charOffset();
String remainingPath = pathMatcher.group(2); Element element = resolveElement(document.body(), targetSteps);
Integer textOffset = null;
Matcher textOffsetMatcher = XPOINTER_TEXT_OFFSET_PATTERN.matcher(remainingPath);
if (textOffsetMatcher.find()) {
textOffset = Integer.parseInt(textOffsetMatcher.group(1));
remainingPath = XPOINTER_TEXT_OFFSET_PATTERN.matcher(remainingPath).replaceAll("");
}
Element element = resolveElementPath(document.body(), remainingPath);
if (element == null) { if (element == null) {
return null; return null;
} }
@@ -233,33 +223,28 @@ public class EpubCfiService {
return element.sourceRange() == null ? null : Math.max(element.sourceRange().startPos(), 0); return element.sourceRange() == null ? null : Math.max(element.sourceRange().startPos(), 0);
} }
private Element resolveElementPath(Element root, String path) { private Element resolveElement(Element root, List<CfiExpression.PathStep> steps) {
Element current = root; Element current = root;
if (path == null || path.isBlank()) { if (current == null || steps == null || steps.isEmpty()) {
return current; return current;
} }
for (String rawSegment : path.split("/")) { for (int i = 0; i < steps.size(); i++) {
if (rawSegment.isBlank()) { CfiExpression.PathStep step = steps.get(i);
if (!step.targetsElement()) {
break;
}
if (i == 0 && step.position() == 4) {
continue; continue;
} }
Matcher segmentMatcher = XPOINTER_SEGMENT_PATTERN.matcher(rawSegment); int childIndex = step.childElementIndex();
if (!segmentMatcher.matches()) { if (childIndex < 0 || childIndex >= current.childrenSize()) {
throw new IllegalArgumentException("Invalid XPointer segment: " + rawSegment);
}
String tagName = segmentMatcher.group(1).toLowerCase();
int index = segmentMatcher.group(2) == null ? 1 : Integer.parseInt(segmentMatcher.group(2));
List<Element> matchingChildren = current.children().stream()
.filter(child -> child.tagName().equalsIgnoreCase(tagName))
.toList();
if (matchingChildren.size() < index) {
return null; return null;
} }
current = matchingChildren.get(index - 1); current = current.child(childIndex);
} }
return current; return current;
@@ -272,6 +272,33 @@ class EpubCfiServiceTest {
assertTrue(earlyLocation.contentSourceProgressPercent() < laterLocation.contentSourceProgressPercent()); assertTrue(earlyLocation.contentSourceProgressPercent() < laterLocation.contentSourceProgressPercent());
} }
@Test
void resolveCfiLocation_webReaderStyleTerminalTextStepResolvesDeepIntoChapter() {
String earlyCfi = "epubcfi(/6/2!/4/2/2/1:0)";
String laterCfi = "epubcfi(/6/2!/4/2/4/1:10)";
EpubCfiService.CfiLocation earlyLocation = service.resolveCfiLocation(testEpubFile, earlyCfi).orElseThrow();
EpubCfiService.CfiLocation laterLocation = service.resolveCfiLocation(testEpubFile, laterCfi).orElseThrow();
assertEquals("chapter1.xhtml", earlyLocation.href());
assertEquals("chapter1.xhtml", laterLocation.href());
assertNotNull(earlyLocation.contentSourceProgressPercent());
assertNotNull(laterLocation.contentSourceProgressPercent());
assertTrue(earlyLocation.contentSourceProgressPercent() > 10f);
assertTrue(laterLocation.contentSourceProgressPercent() > earlyLocation.contentSourceProgressPercent() + 10f);
}
@Test
void resolveCfiLocation_rangeCfiUsesRangeEndPosition() {
String rangeCfi = "epubcfi(/6/2!/4/2,/2/1:0,/4/1:10)";
EpubCfiService.CfiLocation location = service.resolveCfiLocation(testEpubFile, rangeCfi).orElseThrow();
assertEquals("chapter1.xhtml", location.href());
assertNotNull(location.contentSourceProgressPercent());
assertTrue(location.contentSourceProgressPercent() > 30f);
}
@Test @Test
void resolveCfiLocation_invalidCfiReturnsEmpty() { void resolveCfiLocation_invalidCfiReturnsEmpty() {
assertTrue(service.resolveCfiLocation(testEpubFile, "invalid").isEmpty()); assertTrue(service.resolveCfiLocation(testEpubFile, "invalid").isEmpty());