Bidirectional progress sync between koreader and booklore reader (#2312)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
@@ -90,6 +90,9 @@ dependencies {
|
||||
// --- Template Engine ---
|
||||
implementation 'org.freemarker:freemarker:2.3.34'
|
||||
|
||||
// --- Caching ---
|
||||
implementation 'com.github.ben-manes.caffeine:caffeine:3.2.0'
|
||||
|
||||
// --- Test Dependencies ---
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testImplementation 'org.assertj:assertj-core:3.27.6'
|
||||
|
||||
+1
@@ -49,6 +49,7 @@ public class KoreaderAuthFilter extends OncePerRequestFilter {
|
||||
user.getUsername(),
|
||||
user.getPasswordMD5(),
|
||||
user.isSyncEnabled(),
|
||||
user.isSyncWithBookloreReader(),
|
||||
bookLoreUserId,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER"))
|
||||
);
|
||||
|
||||
+4
-1
@@ -13,13 +13,16 @@ public class KoreaderUserDetails implements UserDetails {
|
||||
@Getter
|
||||
private final boolean syncEnabled;
|
||||
@Getter
|
||||
private final boolean syncWithBookloreReader;
|
||||
@Getter
|
||||
private final Long bookLoreUserId;
|
||||
private final Collection<? extends GrantedAuthority> authorities;
|
||||
|
||||
public KoreaderUserDetails(String username, String password, boolean syncEnabled, Long bookLoreUserId, Collection<? extends GrantedAuthority> authorities) {
|
||||
public KoreaderUserDetails(String username, String password, boolean syncEnabled, boolean syncWithBookloreReader, Long bookLoreUserId, Collection<? extends GrantedAuthority> authorities) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.syncEnabled = syncEnabled;
|
||||
this.syncWithBookloreReader = syncWithBookloreReader;
|
||||
this.bookLoreUserId = bookLoreUserId;
|
||||
this.authorities = authorities;
|
||||
}
|
||||
|
||||
+10
@@ -50,4 +50,14 @@ public class KoreaderUserController {
|
||||
koreaderUserService.toggleSync(enabled);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Toggle sync progress with Booklore reader", description = "Enable or disable syncing reading progress with Booklore reader.")
|
||||
@ApiResponse(responseCode = "204", description = "Sync progress toggled successfully")
|
||||
@PatchMapping("/me/sync-progress-with-booklore")
|
||||
@PreAuthorize("@securityUtil.canSyncKoReader() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Void> toggleSyncProgressWithBooklore(
|
||||
@Parameter(description = "Enable or disable sync progress") @RequestParam boolean enabled) {
|
||||
koreaderUserService.toggleSyncProgressWithBooklore(enabled);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
|
||||
+4
@@ -38,6 +38,10 @@ public class KoreaderUserEntity {
|
||||
@Builder.Default
|
||||
private boolean syncEnabled = false;
|
||||
|
||||
@Column(name = "sync_with_booklore_reader", nullable = false)
|
||||
@Builder.Default
|
||||
private boolean syncWithBookloreReader = false;
|
||||
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "booklore_user_id")
|
||||
private BookLoreUserEntity bookLoreUser;
|
||||
|
||||
+32
-12
@@ -1,15 +1,5 @@
|
||||
package com.adityachandel.booklore.service.koreader;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import com.adityachandel.booklore.config.security.userdetails.KoreaderUserDetails;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.progress.KoreaderProgress;
|
||||
@@ -23,6 +13,17 @@ import com.adityachandel.booklore.repository.KoreaderUserRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.hardcover.HardcoverSyncService;
|
||||
import com.adityachandel.booklore.util.koreader.EpubCfiService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@@ -34,6 +35,7 @@ public class KoreaderService {
|
||||
private final UserRepository userRepository;
|
||||
private final KoreaderUserRepository koreaderUserRepository;
|
||||
private final HardcoverSyncService hardcoverSyncService;
|
||||
private final EpubCfiService epubCfiService;
|
||||
|
||||
public ResponseEntity<Map<String, String>> authorizeUser() {
|
||||
KoreaderUserDetails authDetails = getAuthDetails();
|
||||
@@ -73,7 +75,7 @@ public class KoreaderService {
|
||||
BookLoreUserEntity user = findBookLoreUser(authDetails.getBookLoreUserId());
|
||||
|
||||
UserBookProgressEntity userProgress = getOrCreateUserProgress(user, book);
|
||||
updateProgressData(userProgress, koProgress);
|
||||
updateProgressData(userProgress, koProgress, authDetails.isSyncWithBookloreReader(), book);
|
||||
|
||||
progressRepository.save(userProgress);
|
||||
|
||||
@@ -83,13 +85,31 @@ public class KoreaderService {
|
||||
hardcoverSyncService.syncProgressToHardcover(book.getId(), progressPercent, authDetails.getBookLoreUserId());
|
||||
}
|
||||
|
||||
private void updateProgressData(UserBookProgressEntity userProgress, KoreaderProgress koProgress) {
|
||||
private void updateProgressData(UserBookProgressEntity userProgress, KoreaderProgress koProgress, boolean syncWithBookloreReader, BookEntity book) {
|
||||
userProgress.setKoreaderProgress(koProgress.getProgress());
|
||||
userProgress.setKoreaderProgressPercent(koProgress.getPercentage());
|
||||
userProgress.setKoreaderDevice(koProgress.getDevice());
|
||||
userProgress.setKoreaderDeviceId(koProgress.getDevice_id());
|
||||
userProgress.setKoreaderLastSyncTime(Instant.now());
|
||||
userProgress.setLastReadTime(Instant.now());
|
||||
if (syncWithBookloreReader && koProgress.getProgress() != null) {
|
||||
try {
|
||||
String cfi = epubCfiService.convertXPointerToCfi(book.getFullFilePath(), koProgress.getProgress());
|
||||
|
||||
float percent = koProgress.getPercentage() * 100f;
|
||||
float rounded = BigDecimal
|
||||
.valueOf(percent)
|
||||
.setScale(1, RoundingMode.HALF_UP)
|
||||
.floatValue();
|
||||
|
||||
userProgress.setEpubProgress(cfi);
|
||||
userProgress.setEpubProgressPercent(rounded);
|
||||
|
||||
log.info("Converted xpointer to CFI for BookLore reader sync: {}", cfi);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to convert xpointer to CFI: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
updateReadStatus(userProgress, koProgress.getPercentage());
|
||||
}
|
||||
|
||||
+12
-4
@@ -30,7 +30,7 @@ public class KoreaderUserService {
|
||||
public KoreaderUser upsertUser(String username, String rawPassword) {
|
||||
Long ownerId = authService.getAuthenticatedUser().getId();
|
||||
BookLoreUserEntity owner = userRepository.findById(ownerId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(ownerId));
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(ownerId));
|
||||
|
||||
String md5Password = Md5Util.md5Hex(rawPassword);
|
||||
Optional<KoreaderUserEntity> existing = koreaderUserRepository.findByBookLoreUserId(ownerId);
|
||||
@@ -47,9 +47,9 @@ public class KoreaderUserService {
|
||||
KoreaderUserEntity saved = koreaderUserRepository.save(user);
|
||||
|
||||
log.info("upsertUser: {} KoreaderUser [id={}, username='{}'] for BookLoreUser='{}'",
|
||||
isUpdate ? "Updated" : "Created",
|
||||
saved.getId(), saved.getUsername(),
|
||||
authService.getAuthenticatedUser().getUsername());
|
||||
isUpdate ? "Updated" : "Created",
|
||||
saved.getId(), saved.getUsername(),
|
||||
authService.getAuthenticatedUser().getUsername());
|
||||
|
||||
return koreaderUserMapper.toDto(saved);
|
||||
}
|
||||
@@ -68,4 +68,12 @@ public class KoreaderUserService {
|
||||
user.setSyncEnabled(enabled);
|
||||
koreaderUserRepository.save(user);
|
||||
}
|
||||
|
||||
public void toggleSyncProgressWithBooklore(boolean enabled) {
|
||||
Long id = authService.getAuthenticatedUser().getId();
|
||||
KoreaderUserEntity user = koreaderUserRepository.findByBookLoreUserId(id)
|
||||
.orElseThrow(() -> ApiError.GENERIC_NOT_FOUND.createException("Koreader user not found for BookLore user ID: " + id));
|
||||
user.setSyncWithBookloreReader(enabled);
|
||||
koreaderUserRepository.save(user);
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package com.adityachandel.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 lombok.extern.slf4j.Slf4j;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
public class EpubContentReader {
|
||||
|
||||
private static final List<MediaType> MEDIA_TYPES = new ArrayList<>();
|
||||
static {
|
||||
MEDIA_TYPES.addAll(Arrays.asList(MediaTypes.mediaTypes));
|
||||
MEDIA_TYPES.add(null);
|
||||
}
|
||||
|
||||
private 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);
|
||||
|
||||
Spine spine = epub.getSpine();
|
||||
if (spine == null || spine.size() == 0) {
|
||||
throw new EpubReadException("EPUB has no spine: " + epubFile.getName());
|
||||
}
|
||||
|
||||
if (spineIndex < 0 || spineIndex >= spine.size()) {
|
||||
throw new EpubReadException(
|
||||
String.format("Spine index %d out of bounds (0-%d) for: %s",
|
||||
spineIndex, spine.size() - 1, epubFile.getName()));
|
||||
}
|
||||
|
||||
Resource resource = spine.getResource(spineIndex);
|
||||
if (resource == null) {
|
||||
throw new EpubReadException(
|
||||
String.format("Spine item %d has no resource in: %s", spineIndex, epubFile.getName()));
|
||||
}
|
||||
|
||||
return new String(resource.getData(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new EpubReadException("Failed to read EPUB file: " + epubFile.getName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getSpineItemContent(Path epubPath, int spineIndex) {
|
||||
return getSpineItemContent(epubPath.toFile(), spineIndex);
|
||||
}
|
||||
|
||||
public static int getSpineSize(File epubFile) {
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
Book epub = new EpubReader().readEpubLazy(zip, "UTF-8", MEDIA_TYPES);
|
||||
Spine spine = epub.getSpine();
|
||||
return spine != null ? spine.size() : 0;
|
||||
} catch (IOException e) {
|
||||
throw new EpubReadException("Failed to read EPUB file: " + epubFile.getName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getSpineItemHref(File epubFile, int spineIndex) {
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
Book epub = new EpubReader().readEpubLazy(zip, "UTF-8", MEDIA_TYPES);
|
||||
|
||||
Spine spine = epub.getSpine();
|
||||
if (spine == null || spineIndex < 0 || spineIndex >= spine.size()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Resource resource = spine.getResource(spineIndex);
|
||||
return resource != null ? resource.getHref() : null;
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to get spine item href from EPUB: {}", epubFile.getName(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
Spine spine = epub.getSpine();
|
||||
if (spine != null) {
|
||||
for (int i = 0; i < spine.size(); i++) {
|
||||
Resource resource = spine.getResource(i);
|
||||
hrefs.add(resource != null ? resource.getHref() : null);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to get spine items from EPUB: {}", epubFile.getName(), e);
|
||||
}
|
||||
return hrefs;
|
||||
}
|
||||
|
||||
public static class EpubReadException extends RuntimeException {
|
||||
public EpubReadException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public EpubReadException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
+521
@@ -0,0 +1,521 @@
|
||||
package com.adityachandel.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) {}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package com.adityachandel.booklore.util.koreader;
|
||||
|
||||
import com.adityachandel.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.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class EpubCfiService {
|
||||
|
||||
private final Cache<String, Document> documentCache;
|
||||
|
||||
public EpubCfiService() {
|
||||
this.documentCache = Caffeine.newBuilder()
|
||||
.maximumSize(50)
|
||||
.expireAfterAccess(Duration.ofMinutes(10))
|
||||
.softValues()
|
||||
.build();
|
||||
}
|
||||
|
||||
public CfiConvertor.XPointerResult convertCfiToXPointer(File epubFile, String cfi) {
|
||||
int spineIndex = CfiConvertor.extractSpineIndex(cfi);
|
||||
CfiConvertor converter = createConverter(epubFile, spineIndex);
|
||||
return converter.cfiToXPointer(cfi);
|
||||
}
|
||||
|
||||
public CfiConvertor.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);
|
||||
return converter.xPointerToCfi(xpointer);
|
||||
}
|
||||
|
||||
public String convertXPointerToCfi(Path epubPath, String xpointer) {
|
||||
return convertXPointerToCfi(epubPath.toFile(), xpointer);
|
||||
}
|
||||
|
||||
public String convertXPointerRangeToCfi(File epubFile, String startXPointer, String endXPointer) {
|
||||
int spineIndex = CfiConvertor.extractSpineIndex(startXPointer);
|
||||
CfiConvertor converter = createConverter(epubFile, spineIndex);
|
||||
return converter.xPointerToCfi(startXPointer, endXPointer);
|
||||
}
|
||||
|
||||
public String convertXPointerRangeToCfi(Path epubPath, String startXPointer, String endXPointer) {
|
||||
return convertXPointerRangeToCfi(epubPath.toFile(), startXPointer, endXPointer);
|
||||
}
|
||||
|
||||
public String convertCfiToProgressXPointer(File epubFile, String cfi) {
|
||||
CfiConvertor.XPointerResult result = convertCfiToXPointer(epubFile, cfi);
|
||||
return CfiConvertor.normalizeProgressXPointer(result.getXpointer());
|
||||
}
|
||||
|
||||
public String convertCfiToProgressXPointer(Path epubPath, String cfi) {
|
||||
return convertCfiToProgressXPointer(epubPath.toFile(), cfi);
|
||||
}
|
||||
|
||||
public boolean validateCfi(File epubFile, String cfi) {
|
||||
try {
|
||||
int spineIndex = CfiConvertor.extractSpineIndex(cfi);
|
||||
CfiConvertor converter = createConverter(epubFile, spineIndex);
|
||||
return converter.validateCfi(cfi);
|
||||
} catch (Exception e) {
|
||||
log.debug("CFI validation failed: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean validateXPointer(File epubFile, String xpointer) {
|
||||
try {
|
||||
int spineIndex = CfiConvertor.extractSpineIndex(xpointer);
|
||||
CfiConvertor converter = createConverter(epubFile, spineIndex);
|
||||
return converter.validateXPointer(xpointer);
|
||||
} catch (Exception e) {
|
||||
log.debug("XPointer validation failed: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public int extractSpineIndex(String cfiOrXPointer) {
|
||||
return CfiConvertor.extractSpineIndex(cfiOrXPointer);
|
||||
}
|
||||
|
||||
public int getSpineSize(File epubFile) {
|
||||
return EpubContentReader.getSpineSize(epubFile);
|
||||
}
|
||||
|
||||
public CfiConvertor createConverter(File epubFile, int spineIndex) {
|
||||
Document doc = getCachedDocument(epubFile, spineIndex);
|
||||
return new CfiConvertor(doc, spineIndex);
|
||||
}
|
||||
|
||||
public CfiConvertor createConverter(Path epubPath, int spineIndex) {
|
||||
return createConverter(epubPath.toFile(), spineIndex);
|
||||
}
|
||||
|
||||
private Document getCachedDocument(File epubFile, int spineIndex) {
|
||||
String cacheKey = buildCacheKey(epubFile, spineIndex);
|
||||
return documentCache.get(cacheKey, key -> {
|
||||
log.debug("Cache miss for epub spine: {} index {}", epubFile.getName(), spineIndex);
|
||||
String html = EpubContentReader.getSpineItemContent(epubFile, spineIndex);
|
||||
return Jsoup.parse(html);
|
||||
});
|
||||
}
|
||||
|
||||
private String buildCacheKey(File epubFile, int spineIndex) {
|
||||
try {
|
||||
return epubFile.getCanonicalPath() + ":" + spineIndex;
|
||||
} catch (IOException e) {
|
||||
return epubFile.getAbsolutePath() + ":" + spineIndex;
|
||||
}
|
||||
}
|
||||
|
||||
public void evictCache(File epubFile) {
|
||||
try {
|
||||
String pathPrefix = epubFile.getCanonicalPath() + ":";
|
||||
documentCache.asMap().keySet().removeIf(key -> key.startsWith(pathPrefix));
|
||||
} catch (IOException e) {
|
||||
String pathPrefix = epubFile.getAbsolutePath() + ":";
|
||||
documentCache.asMap().keySet().removeIf(key -> key.startsWith(pathPrefix));
|
||||
}
|
||||
}
|
||||
|
||||
public void clearCache() {
|
||||
documentCache.invalidateAll();
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE koreader_user
|
||||
ADD COLUMN IF NOT EXISTS sync_with_booklore_reader BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
package com.adityachandel.booklore.util.epub;
|
||||
|
||||
import io.documentnode.epub4j.domain.Book;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.epub.EpubWriter;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class EpubContentReaderTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private File validEpubFile;
|
||||
private File emptySpineEpubFile;
|
||||
|
||||
private static final String CHAPTER1_CONTENT = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head><title>Chapter 1</title></head>
|
||||
<body>
|
||||
<h1>Chapter 1</h1>
|
||||
<p>This is the first paragraph of chapter one.</p>
|
||||
<p>This is the second paragraph.</p>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
|
||||
private static final String CHAPTER2_CONTENT = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head><title>Chapter 2</title></head>
|
||||
<body>
|
||||
<h1>Chapter 2</h1>
|
||||
<p>Content of chapter two.</p>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
|
||||
private static final String CHAPTER3_CONTENT = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head><title>Chapter 3</title></head>
|
||||
<body>
|
||||
<h1>Chapter 3</h1>
|
||||
<p>Final chapter content.</p>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
validEpubFile = createTestEpub("valid.epub", true);
|
||||
emptySpineEpubFile = createTestEpub("empty_spine.epub", false);
|
||||
}
|
||||
|
||||
private File createTestEpub(String filename, boolean withSpine) throws IOException {
|
||||
Book book = new Book();
|
||||
book.getMetadata().addTitle("Test Book");
|
||||
book.getMetadata().addAuthor(new io.documentnode.epub4j.domain.Author("Test Author"));
|
||||
|
||||
if (withSpine) {
|
||||
Resource chapter1 = new Resource(CHAPTER1_CONTENT.getBytes(StandardCharsets.UTF_8), "chapter1.xhtml");
|
||||
Resource chapter2 = new Resource(CHAPTER2_CONTENT.getBytes(StandardCharsets.UTF_8), "chapter2.xhtml");
|
||||
Resource chapter3 = new Resource(CHAPTER3_CONTENT.getBytes(StandardCharsets.UTF_8), "chapter3.xhtml");
|
||||
|
||||
book.addSection("Chapter 1", chapter1);
|
||||
book.addSection("Chapter 2", chapter2);
|
||||
book.addSection("Chapter 3", chapter3);
|
||||
}
|
||||
|
||||
File epubFile = tempDir.resolve(filename).toFile();
|
||||
try (FileOutputStream out = new FileOutputStream(epubFile)) {
|
||||
new EpubWriter().write(book, out);
|
||||
}
|
||||
return epubFile;
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetSpineItemContentTests {
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_firstChapter_returnsContent() {
|
||||
String content = EpubContentReader.getSpineItemContent(validEpubFile, 0);
|
||||
|
||||
assertNotNull(content);
|
||||
assertTrue(content.contains("Chapter 1"));
|
||||
assertTrue(content.contains("first paragraph"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_secondChapter_returnsContent() {
|
||||
String content = EpubContentReader.getSpineItemContent(validEpubFile, 1);
|
||||
|
||||
assertNotNull(content);
|
||||
assertTrue(content.contains("Chapter 2"));
|
||||
assertTrue(content.contains("chapter two"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_lastChapter_returnsContent() {
|
||||
String content = EpubContentReader.getSpineItemContent(validEpubFile, 2);
|
||||
|
||||
assertNotNull(content);
|
||||
assertTrue(content.contains("Chapter 3"));
|
||||
assertTrue(content.contains("Final chapter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_withPath_returnsContent() {
|
||||
String content = EpubContentReader.getSpineItemContent(validEpubFile.toPath(), 0);
|
||||
|
||||
assertNotNull(content);
|
||||
assertTrue(content.contains("Chapter 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_negativeIndex_throwsException() {
|
||||
EpubContentReader.EpubReadException exception = assertThrows(
|
||||
EpubContentReader.EpubReadException.class,
|
||||
() -> EpubContentReader.getSpineItemContent(validEpubFile, -1)
|
||||
);
|
||||
|
||||
assertTrue(exception.getMessage().contains("out of bounds"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_indexTooLarge_throwsException() {
|
||||
EpubContentReader.EpubReadException exception = assertThrows(
|
||||
EpubContentReader.EpubReadException.class,
|
||||
() -> EpubContentReader.getSpineItemContent(validEpubFile, 999)
|
||||
);
|
||||
|
||||
assertTrue(exception.getMessage().contains("out of bounds"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_emptySpine_throwsException() {
|
||||
EpubContentReader.EpubReadException exception = assertThrows(
|
||||
EpubContentReader.EpubReadException.class,
|
||||
() -> EpubContentReader.getSpineItemContent(emptySpineEpubFile, 0)
|
||||
);
|
||||
|
||||
assertTrue(exception.getMessage().contains("no spine"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_nonExistentFile_throwsException() {
|
||||
File nonExistent = new File(tempDir.toFile(), "nonexistent.epub");
|
||||
|
||||
assertThrows(
|
||||
EpubContentReader.EpubReadException.class,
|
||||
() -> EpubContentReader.getSpineItemContent(nonExistent, 0)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_invalidEpubFile_throwsException() throws IOException {
|
||||
File invalidFile = tempDir.resolve("invalid.epub").toFile();
|
||||
java.nio.file.Files.writeString(invalidFile.toPath(), "not an epub");
|
||||
|
||||
assertThrows(
|
||||
EpubContentReader.EpubReadException.class,
|
||||
() -> EpubContentReader.getSpineItemContent(invalidFile, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetSpineSizeTests {
|
||||
|
||||
@Test
|
||||
void getSpineSize_validEpub_returnsCorrectSize() {
|
||||
int size = EpubContentReader.getSpineSize(validEpubFile);
|
||||
|
||||
assertEquals(3, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineSize_emptySpine_returnsZero() {
|
||||
int size = EpubContentReader.getSpineSize(emptySpineEpubFile);
|
||||
|
||||
assertEquals(0, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineSize_nonExistentFile_returnsZero() {
|
||||
File nonExistent = new File(tempDir.toFile(), "nonexistent.epub");
|
||||
|
||||
int size = EpubContentReader.getSpineSize(nonExistent);
|
||||
|
||||
assertEquals(0, size);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetSpineItemHrefTests {
|
||||
|
||||
@Test
|
||||
void getSpineItemHref_validIndex_returnsHref() {
|
||||
String href = EpubContentReader.getSpineItemHref(validEpubFile, 0);
|
||||
|
||||
assertNotNull(href);
|
||||
assertTrue(href.contains("chapter1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemHref_secondItem_returnsCorrectHref() {
|
||||
String href = EpubContentReader.getSpineItemHref(validEpubFile, 1);
|
||||
|
||||
assertNotNull(href);
|
||||
assertTrue(href.contains("chapter2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemHref_negativeIndex_returnsNull() {
|
||||
String href = EpubContentReader.getSpineItemHref(validEpubFile, -1);
|
||||
|
||||
assertNull(href);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemHref_indexTooLarge_returnsNull() {
|
||||
String href = EpubContentReader.getSpineItemHref(validEpubFile, 999);
|
||||
|
||||
assertNull(href);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemHref_emptySpine_returnsNull() {
|
||||
String href = EpubContentReader.getSpineItemHref(emptySpineEpubFile, 0);
|
||||
|
||||
assertNull(href);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetAllSpineItemHrefsTests {
|
||||
|
||||
@Test
|
||||
void getAllSpineItemHrefs_validEpub_returnsAllHrefs() {
|
||||
List<String> hrefs = EpubContentReader.getAllSpineItemHrefs(validEpubFile);
|
||||
|
||||
assertEquals(3, hrefs.size());
|
||||
assertTrue(hrefs.get(0).contains("chapter1"));
|
||||
assertTrue(hrefs.get(1).contains("chapter2"));
|
||||
assertTrue(hrefs.get(2).contains("chapter3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllSpineItemHrefs_emptySpine_returnsEmptyList() {
|
||||
List<String> hrefs = EpubContentReader.getAllSpineItemHrefs(emptySpineEpubFile);
|
||||
|
||||
assertTrue(hrefs.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllSpineItemHrefs_nonExistentFile_returnsEmptyList() {
|
||||
File nonExistent = new File(tempDir.toFile(), "nonexistent.epub");
|
||||
|
||||
List<String> hrefs = EpubContentReader.getAllSpineItemHrefs(nonExistent);
|
||||
|
||||
assertTrue(hrefs.isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class EpubReadExceptionTests {
|
||||
|
||||
@Test
|
||||
void epubReadException_withMessage_containsMessage() {
|
||||
EpubContentReader.EpubReadException exception =
|
||||
new EpubContentReader.EpubReadException("Test message");
|
||||
|
||||
assertEquals("Test message", exception.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void epubReadException_withCause_containsCause() {
|
||||
IOException cause = new IOException("IO error");
|
||||
EpubContentReader.EpubReadException exception =
|
||||
new EpubContentReader.EpubReadException("Test message", cause);
|
||||
|
||||
assertEquals("Test message", exception.getMessage());
|
||||
assertEquals(cause, exception.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ContentValidationTests {
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_returnsUtf8Content() {
|
||||
String content = EpubContentReader.getSpineItemContent(validEpubFile, 0);
|
||||
|
||||
assertNotNull(content);
|
||||
assertFalse(content.isEmpty());
|
||||
assertTrue(content.contains("<body>") || content.contains("<BODY>") || content.toLowerCase().contains("<body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_preservesHtmlStructure() {
|
||||
String content = EpubContentReader.getSpineItemContent(validEpubFile, 0);
|
||||
|
||||
assertTrue(content.contains("<h1>") || content.toLowerCase().contains("<h1"));
|
||||
assertTrue(content.contains("<p>") || content.toLowerCase().contains("<p"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpineItemContent_multipleReadsReturnSameContent() {
|
||||
String content1 = EpubContentReader.getSpineItemContent(validEpubFile, 0);
|
||||
String content2 = EpubContentReader.getSpineItemContent(validEpubFile, 0);
|
||||
|
||||
assertEquals(content1, content2);
|
||||
}
|
||||
}
|
||||
}
|
||||
+474
@@ -0,0 +1,474 @@
|
||||
package com.adityachandel.booklore.util.koreader;
|
||||
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CfiConvertorTest {
|
||||
|
||||
private Document simpleDocument;
|
||||
private Document complexDocument;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Simple HTML document for basic tests
|
||||
simpleDocument = Jsoup.parse("""
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
<div id="chapter1">
|
||||
<p>First paragraph with some text.</p>
|
||||
<p>Second paragraph with more text.</p>
|
||||
</div>
|
||||
<div id="chapter2">
|
||||
<p>Third paragraph.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
""");
|
||||
|
||||
// Complex HTML document with nested elements
|
||||
complexDocument = Jsoup.parse("""
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
<section>
|
||||
<div class="content">
|
||||
<h1>Chapter Title</h1>
|
||||
<p>This is <em>emphasized</em> and <strong>bold</strong> text.</p>
|
||||
<p>Another paragraph with <span class="highlight">highlighted</span> content.</p>
|
||||
</div>
|
||||
<div class="sidebar">
|
||||
<p>Sidebar content here.</p>
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<div>
|
||||
<p>Second section paragraph.</p>
|
||||
</div>
|
||||
</section>
|
||||
</body>
|
||||
</html>
|
||||
""");
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ExtractSpineIndexTests {
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromCfi_spineIndex0() {
|
||||
String cfi = "epubcfi(/6/2!/4/2)";
|
||||
int result = CfiConvertor.extractSpineIndex(cfi);
|
||||
assertEquals(0, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromCfi_spineIndex1() {
|
||||
String cfi = "epubcfi(/6/4!/4/2)";
|
||||
int result = CfiConvertor.extractSpineIndex(cfi);
|
||||
assertEquals(1, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromCfi_spineIndex5() {
|
||||
String cfi = "epubcfi(/6/12!/4/2:10)";
|
||||
int result = CfiConvertor.extractSpineIndex(cfi);
|
||||
assertEquals(5, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromXPointer_spineIndex0() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p";
|
||||
int result = CfiConvertor.extractSpineIndex(xpointer);
|
||||
assertEquals(0, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromXPointer_spineIndex2() {
|
||||
String xpointer = "/body/DocFragment[3]/body/section/div/p";
|
||||
int result = CfiConvertor.extractSpineIndex(xpointer);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromXPointer_withTextOffset() {
|
||||
String xpointer = "/body/DocFragment[5]/body/p/text().42";
|
||||
int result = CfiConvertor.extractSpineIndex(xpointer);
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" ", "\t", "\n"})
|
||||
void extractSpineIndex_nullOrEmpty_throwsException(String input) {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> CfiConvertor.extractSpineIndex(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_invalidFormat_throwsException() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> CfiConvertor.extractSpineIndex("invalid/path/here"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_malformedCfi_throwsException() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> CfiConvertor.extractSpineIndex("epubcfi(malformed)"));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class XPointerToCfiTests {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_simpleElement() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.startsWith("epubcfi("));
|
||||
assertTrue(cfi.endsWith(")"));
|
||||
assertTrue(cfi.contains("/6/2!")); // Spine index 0 = step 2
|
||||
}
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_withTextOffset() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().5";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.startsWith("epubcfi("));
|
||||
assertTrue(cfi.contains(":5")); // Text offset
|
||||
}
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_differentSpineIndex() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 2);
|
||||
String xpointer = "/body/DocFragment[3]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.contains("/6/6!")); // Spine index 2 = step 6
|
||||
}
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_bodyOnly() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String xpointer = "/body/DocFragment[1]/body";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.startsWith("epubcfi("));
|
||||
}
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_rangeWithStartAndEnd() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String startXPointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().0";
|
||||
String endXPointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().10";
|
||||
|
||||
String cfi = converter.xPointerToCfi(startXPointer, endXPointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.startsWith("epubcfi("));
|
||||
}
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_invalidPath_throwsException() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> converter.xPointerToCfi("/invalid/path"));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CfiToXPointerTests {
|
||||
|
||||
@Test
|
||||
void cfiToXPointer_simpleElement() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String cfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getXpointer());
|
||||
assertTrue(result.getXpointer().startsWith("/body/DocFragment[1]/body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cfiToXPointer_withTextOffset() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String cfi = "epubcfi(/6/2!/4/2/2:5)";
|
||||
|
||||
CfiConvertor.XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.getXpointer().contains("/text()."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cfiToXPointer_spineIndexMismatch_throwsException() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String cfi = "epubcfi(/6/4!/4/2)"; // Spine index 1, but converter is 0
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> converter.cfiToXPointer(cfi));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cfiToXPointer_invalidCfiFormat_throwsException() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> converter.cfiToXPointer("not-a-valid-cfi"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cfiToXPointer_malformedCfi_throwsException() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> converter.cfiToXPointer("epubcfi(invalid)"));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ValidationTests {
|
||||
|
||||
@Test
|
||||
void validateCfi_validCfi_returnsTrue() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String cfi = "epubcfi(/6/2!/4/2)";
|
||||
|
||||
assertTrue(converter.validateCfi(cfi));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateCfi_invalidCfi_returnsFalse() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
|
||||
assertFalse(converter.validateCfi("invalid"));
|
||||
assertFalse(converter.validateCfi("epubcfi(malformed)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateCfi_wrongSpineIndex_returnsFalse() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String cfi = "epubcfi(/6/10!/4/2)"; // Spine index 4, converter is 0
|
||||
|
||||
assertFalse(converter.validateCfi(cfi));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateXPointer_validXPointer_returnsTrue() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
assertTrue(converter.validateXPointer(xpointer));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateXPointer_invalidXPointer_returnsFalse() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
|
||||
assertFalse(converter.validateXPointer("/invalid/path"));
|
||||
assertFalse(converter.validateXPointer("not-an-xpointer"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateXPointer_withPos1_returnsTrue() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String pos0 = "/body/DocFragment[1]/body/div[1]/p[1]/text().0";
|
||||
String pos1 = "/body/DocFragment[1]/body/div[1]/p[1]/text().10";
|
||||
|
||||
assertTrue(converter.validateXPointer(pos0, pos1));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class NormalizeProgressXPointerTests {
|
||||
|
||||
@Test
|
||||
void normalizeProgressXPointer_removesTextOffset() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p/text().42";
|
||||
|
||||
String result = CfiConvertor.normalizeProgressXPointer(xpointer);
|
||||
|
||||
assertEquals("/body/DocFragment[1]/body/div/p", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeProgressXPointer_removesNodeSuffix() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p.5";
|
||||
|
||||
String result = CfiConvertor.normalizeProgressXPointer(xpointer);
|
||||
|
||||
assertEquals("/body/DocFragment[1]/body/div/p", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeProgressXPointer_removesBothTextOffsetAndNodeSuffix() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p/text().10.5";
|
||||
|
||||
String result = CfiConvertor.normalizeProgressXPointer(xpointer);
|
||||
|
||||
assertEquals("/body/DocFragment[1]/body/div/p", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeProgressXPointer_noChangesNeeded() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p";
|
||||
|
||||
String result = CfiConvertor.normalizeProgressXPointer(xpointer);
|
||||
|
||||
assertEquals("/body/DocFragment[1]/body/div/p", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeProgressXPointer_nullInput_returnsNull() {
|
||||
assertNull(CfiConvertor.normalizeProgressXPointer(null));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"/body/DocFragment[1]/body/text().0, /body/DocFragment[1]/body",
|
||||
"/body/DocFragment[3]/body/section/div/p/text().100, /body/DocFragment[3]/body/section/div/p",
|
||||
"/body/DocFragment[1]/body/div[2]/p[3]/text().5, /body/DocFragment[1]/body/div[2]/p[3]"
|
||||
})
|
||||
void normalizeProgressXPointer_variousInputs(String input, String expected) {
|
||||
assertEquals(expected, CfiConvertor.normalizeProgressXPointer(input));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ComplexDocumentTests {
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_nestedElements() {
|
||||
CfiConvertor converter = new CfiConvertor(complexDocument, 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/section[1]/div[1]/p[1]";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.startsWith("epubcfi("));
|
||||
}
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_deeplyNestedElement() {
|
||||
CfiConvertor converter = new CfiConvertor(complexDocument, 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/section[1]/div[1]/h1";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
}
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_secondSection() {
|
||||
CfiConvertor converter = new CfiConvertor(complexDocument, 0);
|
||||
String xpointer = "/body/DocFragment[1]/body/section[2]/div/p";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class RoundTripTests {
|
||||
|
||||
@Test
|
||||
void roundTrip_xPointerToCfiAndBack() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String originalXPointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = converter.xPointerToCfi(originalXPointer);
|
||||
CfiConvertor.XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
|
||||
assertNotNull(result.getXpointer());
|
||||
// The path should resolve to the same element, though format may differ
|
||||
assertTrue(result.getXpointer().contains("/body/DocFragment[1]/body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roundTrip_cfiToXPointerAndBack() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String originalCfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult xpointerResult = converter.cfiToXPointer(originalCfi);
|
||||
String cfi = converter.xPointerToCfi(xpointerResult.getXpointer());
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.startsWith("epubcfi("));
|
||||
assertTrue(cfi.contains("/6/2!")); // Same spine index
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class EdgeCaseTests {
|
||||
|
||||
@Test
|
||||
void constructor_withDefaultSpineIndex() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument);
|
||||
|
||||
// Should work with spine index 0
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.contains("/6/2!")); // Default spine index 0
|
||||
}
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_elementWithoutIndex() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
// Using tag without index (implicit [1])
|
||||
String xpointer = "/body/DocFragment[1]/body/div/p";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
}
|
||||
|
||||
@Test
|
||||
void xPointerToCfi_largeSpineIndex() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 99);
|
||||
String xpointer = "/body/DocFragment[100]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = converter.xPointerToCfi(xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.contains("/6/200!")); // Spine index 99 = step 200
|
||||
}
|
||||
|
||||
@Test
|
||||
void xPointerResult_allFieldsPopulated() {
|
||||
CfiConvertor converter = new CfiConvertor(simpleDocument, 0);
|
||||
String cfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult result = converter.cfiToXPointer(cfi);
|
||||
|
||||
assertNotNull(result.getXpointer());
|
||||
assertNotNull(result.getPos0());
|
||||
assertNotNull(result.getPos1());
|
||||
}
|
||||
}
|
||||
}
|
||||
+411
@@ -0,0 +1,411 @@
|
||||
package com.adityachandel.booklore.util.koreader;
|
||||
|
||||
import io.documentnode.epub4j.domain.Author;
|
||||
import io.documentnode.epub4j.domain.Book;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.epub.EpubWriter;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class EpubCfiServiceTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private EpubCfiService service;
|
||||
private File testEpubFile;
|
||||
|
||||
private static final String CHAPTER1_CONTENT = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head><title>Chapter 1</title></head>
|
||||
<body>
|
||||
<div id="chapter1">
|
||||
<h1>Chapter 1</h1>
|
||||
<p>First paragraph with some text content.</p>
|
||||
<p>Second paragraph with more text.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
|
||||
private static final String CHAPTER2_CONTENT = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head><title>Chapter 2</title></head>
|
||||
<body>
|
||||
<div id="chapter2">
|
||||
<h1>Chapter 2</h1>
|
||||
<p>Content of chapter two.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
|
||||
private static final String CHAPTER3_CONTENT = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head><title>Chapter 3</title></head>
|
||||
<body>
|
||||
<div id="chapter3">
|
||||
<h1>Chapter 3</h1>
|
||||
<p>Final chapter content here.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
service = new EpubCfiService();
|
||||
testEpubFile = createTestEpub("test.epub");
|
||||
}
|
||||
|
||||
private File createTestEpub(String filename) throws IOException {
|
||||
Book book = new Book();
|
||||
book.getMetadata().addTitle("Test Book");
|
||||
book.getMetadata().addAuthor(new Author("Test Author"));
|
||||
|
||||
Resource chapter1 = new Resource(CHAPTER1_CONTENT.getBytes(StandardCharsets.UTF_8), "chapter1.xhtml");
|
||||
Resource chapter2 = new Resource(CHAPTER2_CONTENT.getBytes(StandardCharsets.UTF_8), "chapter2.xhtml");
|
||||
Resource chapter3 = new Resource(CHAPTER3_CONTENT.getBytes(StandardCharsets.UTF_8), "chapter3.xhtml");
|
||||
|
||||
book.addSection("Chapter 1", chapter1);
|
||||
book.addSection("Chapter 2", chapter2);
|
||||
book.addSection("Chapter 3", chapter3);
|
||||
|
||||
File epubFile = tempDir.resolve(filename).toFile();
|
||||
try (FileOutputStream out = new FileOutputStream(epubFile)) {
|
||||
new EpubWriter().write(book, out);
|
||||
}
|
||||
return epubFile;
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CreateConverterTests {
|
||||
|
||||
@Test
|
||||
void createConverter_validFile_returnsConverter() {
|
||||
CfiConvertor converter = service.createConverter(testEpubFile, 0);
|
||||
|
||||
assertNotNull(converter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createConverter_withPath_returnsConverter() {
|
||||
CfiConvertor converter = service.createConverter(testEpubFile.toPath(), 0);
|
||||
|
||||
assertNotNull(converter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createConverter_differentSpineIndices_returnsDifferentConverters() {
|
||||
CfiConvertor converter0 = service.createConverter(testEpubFile, 0);
|
||||
CfiConvertor converter1 = service.createConverter(testEpubFile, 1);
|
||||
|
||||
assertNotNull(converter0);
|
||||
assertNotNull(converter1);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConvertXPointerToCfiTests {
|
||||
|
||||
@Test
|
||||
void convertXPointerToCfi_validXPointer_returnsCfi() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = service.convertXPointerToCfi(testEpubFile, xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.startsWith("epubcfi("));
|
||||
assertTrue(cfi.endsWith(")"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertXPointerToCfi_withPath_returnsCfi() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = service.convertXPointerToCfi(testEpubFile.toPath(), xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.startsWith("epubcfi("));
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertXPointerToCfi_secondSpine_returnsCfiWithCorrectSpineIndex() {
|
||||
String xpointer = "/body/DocFragment[2]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = service.convertXPointerToCfi(testEpubFile, xpointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.contains("/6/4!"));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConvertCfiToXPointerTests {
|
||||
|
||||
@Test
|
||||
void convertCfiToXPointer_validCfi_returnsXPointerResult() {
|
||||
String cfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult result = service.convertCfiToXPointer(testEpubFile, cfi);
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getXpointer());
|
||||
assertTrue(result.getXpointer().startsWith("/body/DocFragment[1]/body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCfiToXPointer_withPath_returnsXPointerResult() {
|
||||
String cfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult result = service.convertCfiToXPointer(testEpubFile.toPath(), cfi);
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getXpointer());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConvertXPointerRangeToCfiTests {
|
||||
|
||||
@Test
|
||||
void convertXPointerRangeToCfi_validRange_returnsCfi() {
|
||||
String startXPointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().0";
|
||||
String endXPointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().10";
|
||||
|
||||
String cfi = service.convertXPointerRangeToCfi(testEpubFile, startXPointer, endXPointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.startsWith("epubcfi("));
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertXPointerRangeToCfi_withPath_returnsCfi() {
|
||||
String startXPointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().0";
|
||||
String endXPointer = "/body/DocFragment[1]/body/div[1]/p[1]/text().10";
|
||||
|
||||
String cfi = service.convertXPointerRangeToCfi(testEpubFile.toPath(), startXPointer, endXPointer);
|
||||
|
||||
assertNotNull(cfi);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ConvertCfiToProgressXPointerTests {
|
||||
|
||||
@Test
|
||||
void convertCfiToProgressXPointer_validCfi_returnsNormalizedXPointer() {
|
||||
String cfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
String progressXPointer = service.convertCfiToProgressXPointer(testEpubFile, cfi);
|
||||
|
||||
assertNotNull(progressXPointer);
|
||||
assertFalse(progressXPointer.contains("/text()."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCfiToProgressXPointer_withPath_returnsNormalizedXPointer() {
|
||||
String cfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
String progressXPointer = service.convertCfiToProgressXPointer(testEpubFile.toPath(), cfi);
|
||||
|
||||
assertNotNull(progressXPointer);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ValidationTests {
|
||||
|
||||
@Test
|
||||
void validateCfi_validCfi_returnsTrue() {
|
||||
String cfi = "epubcfi(/6/2!/4/2)";
|
||||
|
||||
boolean result = service.validateCfi(testEpubFile, cfi);
|
||||
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateCfi_invalidCfi_returnsFalse() {
|
||||
boolean result = service.validateCfi(testEpubFile, "invalid-cfi");
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateCfi_malformedCfi_returnsFalse() {
|
||||
boolean result = service.validateCfi(testEpubFile, "epubcfi(malformed)");
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateXPointer_validXPointer_returnsTrue() {
|
||||
String xpointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
boolean result = service.validateXPointer(testEpubFile, xpointer);
|
||||
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateXPointer_invalidXPointer_returnsFalse() {
|
||||
boolean result = service.validateXPointer(testEpubFile, "/invalid/path");
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class ExtractSpineIndexTests {
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromCfi_returnsCorrectIndex() {
|
||||
int index = service.extractSpineIndex("epubcfi(/6/4!/4/2)");
|
||||
|
||||
assertEquals(1, index);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSpineIndex_fromXPointer_returnsCorrectIndex() {
|
||||
int index = service.extractSpineIndex("/body/DocFragment[3]/body/div/p");
|
||||
|
||||
assertEquals(2, index);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class GetSpineSizeTests {
|
||||
|
||||
@Test
|
||||
void getSpineSize_validEpub_returnsCorrectSize() {
|
||||
int size = service.getSpineSize(testEpubFile);
|
||||
|
||||
assertEquals(3, size);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CacheTests {
|
||||
|
||||
@Test
|
||||
void createConverter_calledTwice_usesCachedDocument() {
|
||||
CfiConvertor converter1 = service.createConverter(testEpubFile, 0);
|
||||
CfiConvertor converter2 = service.createConverter(testEpubFile, 0);
|
||||
|
||||
assertNotNull(converter1);
|
||||
assertNotNull(converter2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void evictCache_removesEntriesForFile() {
|
||||
service.createConverter(testEpubFile, 0);
|
||||
service.createConverter(testEpubFile, 1);
|
||||
|
||||
service.evictCache(testEpubFile);
|
||||
|
||||
CfiConvertor converter = service.createConverter(testEpubFile, 0);
|
||||
assertNotNull(converter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearCache_removesAllEntries() {
|
||||
service.createConverter(testEpubFile, 0);
|
||||
service.createConverter(testEpubFile, 1);
|
||||
|
||||
service.clearCache();
|
||||
|
||||
CfiConvertor converter = service.createConverter(testEpubFile, 0);
|
||||
assertNotNull(converter);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cache_differentSpineIndices_cachedSeparately() {
|
||||
service.createConverter(testEpubFile, 0);
|
||||
service.createConverter(testEpubFile, 1);
|
||||
service.createConverter(testEpubFile, 2);
|
||||
|
||||
CfiConvertor converter0 = service.createConverter(testEpubFile, 0);
|
||||
CfiConvertor converter1 = service.createConverter(testEpubFile, 1);
|
||||
CfiConvertor converter2 = service.createConverter(testEpubFile, 2);
|
||||
|
||||
assertNotNull(converter0);
|
||||
assertNotNull(converter1);
|
||||
assertNotNull(converter2);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class RoundTripTests {
|
||||
|
||||
@Test
|
||||
void roundTrip_xPointerToCfiAndBack() {
|
||||
String originalXPointer = "/body/DocFragment[1]/body/div[1]/p[1]";
|
||||
|
||||
String cfi = service.convertXPointerToCfi(testEpubFile, originalXPointer);
|
||||
CfiConvertor.XPointerResult result = service.convertCfiToXPointer(testEpubFile, cfi);
|
||||
|
||||
assertNotNull(result.getXpointer());
|
||||
assertTrue(result.getXpointer().contains("/body/DocFragment[1]/body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roundTrip_cfiToXPointerAndBack() {
|
||||
String originalCfi = "epubcfi(/6/2!/4/2/2)";
|
||||
|
||||
CfiConvertor.XPointerResult xpointerResult = service.convertCfiToXPointer(testEpubFile, originalCfi);
|
||||
String cfi = service.convertXPointerToCfi(testEpubFile, xpointerResult.getXpointer());
|
||||
|
||||
assertNotNull(cfi);
|
||||
assertTrue(cfi.startsWith("epubcfi("));
|
||||
assertTrue(cfi.contains("/6/2!"));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class MultipleFilesTests {
|
||||
|
||||
@Test
|
||||
void cache_differentFiles_cachedSeparately() throws IOException {
|
||||
File secondEpub = createTestEpub("second.epub");
|
||||
|
||||
service.createConverter(testEpubFile, 0);
|
||||
service.createConverter(secondEpub, 0);
|
||||
|
||||
CfiConvertor converter1 = service.createConverter(testEpubFile, 0);
|
||||
CfiConvertor converter2 = service.createConverter(secondEpub, 0);
|
||||
|
||||
assertNotNull(converter1);
|
||||
assertNotNull(converter2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void evictCache_onlyAffectsSpecificFile() throws IOException {
|
||||
File secondEpub = createTestEpub("second.epub");
|
||||
|
||||
service.createConverter(testEpubFile, 0);
|
||||
service.createConverter(secondEpub, 0);
|
||||
|
||||
service.evictCache(testEpubFile);
|
||||
|
||||
CfiConvertor converter = service.createConverter(secondEpub, 0);
|
||||
assertNotNull(converter);
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -45,6 +45,24 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Sync reading progress with Booklore eBook Reader</label>
|
||||
<p-toggle-switch
|
||||
name="syncWithBookloreReader"
|
||||
[(ngModel)]="syncWithBookloreReader"
|
||||
(ngModelChange)="onToggleSyncWithBookloreReader($event)"
|
||||
inputId="syncWithBookloreReader"
|
||||
[disabled]="!credentialsSaved || !koReaderSyncEnabled">
|
||||
</p-toggle-switch>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Enable bidirectional sync between Booklore's eBook reader and KOReader. <strong>Note:</strong> Progress sync is approximate and may update by chapter rather than exact page or location.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
|
||||
+22
@@ -31,6 +31,7 @@ export class KoreaderSettingsComponent implements OnInit, OnDestroy {
|
||||
editMode = true;
|
||||
showPassword = false;
|
||||
koReaderSyncEnabled = false;
|
||||
syncWithBookloreReader = false;
|
||||
koReaderUsername = '';
|
||||
koReaderPassword = '';
|
||||
credentialsSaved = false;
|
||||
@@ -64,6 +65,7 @@ export class KoreaderSettingsComponent implements OnInit, OnDestroy {
|
||||
this.koReaderUsername = koreaderUser.username;
|
||||
this.koReaderPassword = koreaderUser.password;
|
||||
this.koReaderSyncEnabled = koreaderUser.syncEnabled;
|
||||
this.syncWithBookloreReader = koreaderUser.syncWithBookloreReader ?? false;
|
||||
this.credentialsSaved = true;
|
||||
},
|
||||
error: err => {
|
||||
@@ -104,6 +106,26 @@ export class KoreaderSettingsComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
onToggleSyncWithBookloreReader(enabled: boolean) {
|
||||
this.koreaderService.toggleSyncProgressWithBookloreReader(enabled).subscribe({
|
||||
next: () => {
|
||||
this.syncWithBookloreReader = enabled;
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Sync Updated',
|
||||
detail: `Booklore eBook Reader sync has been ${enabled ? 'enabled' : 'disabled'}.`
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Update Failed',
|
||||
detail: 'Unable to update Booklore eBook Reader sync setting. Please try again.'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
toggleShowPassword() {
|
||||
this.showPassword = !this.showPassword;
|
||||
}
|
||||
|
||||
+5
-3
@@ -12,7 +12,8 @@ describe('KoreaderService', () => {
|
||||
const mockUser: KoreaderUser = {
|
||||
username: 'testuser',
|
||||
password: 'secret',
|
||||
syncEnabled: true
|
||||
syncEnabled: true,
|
||||
syncWithBookloreReader: false
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -118,11 +119,12 @@ describe('KoreaderService - API Contract Tests', () => {
|
||||
});
|
||||
|
||||
it('should validate all required KoreaderUser fields exist', () => {
|
||||
const requiredFields: (keyof KoreaderUser)[] = ['username', 'password', 'syncEnabled'];
|
||||
const requiredFields: (keyof KoreaderUser)[] = ['username', 'password', 'syncEnabled', 'syncWithBookloreReader'];
|
||||
const mockResponse: KoreaderUser = {
|
||||
username: 'test',
|
||||
password: 'pw',
|
||||
syncEnabled: true
|
||||
syncEnabled: true,
|
||||
syncWithBookloreReader: false
|
||||
};
|
||||
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||
service.getUser().subscribe(user => {
|
||||
|
||||
+7
@@ -8,6 +8,7 @@ export interface KoreaderUser {
|
||||
username: string;
|
||||
password: string;
|
||||
syncEnabled: boolean;
|
||||
syncWithBookloreReader: boolean;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
@@ -33,4 +34,10 @@ export class KoreaderService {
|
||||
params: {enabled: enabled.toString()}
|
||||
});
|
||||
}
|
||||
|
||||
toggleSyncProgressWithBookloreReader(enabled: boolean): Observable<void> {
|
||||
return this.http.patch<void>(`${this.url}/me/sync-progress-with-booklore`, null, {
|
||||
params: {enabled: enabled.toString()}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user