fix(kobo-sync): use KoboSpan for progress sync (#253)

This commit is contained in:
Alex
2026-04-23 13:36:15 +01:00
committed by GitHub
parent bfca35b03c
commit f21cf1aee9
60 changed files with 2770 additions and 161 deletions
@@ -0,0 +1,37 @@
package org.booklore.convertor;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import org.booklore.model.dto.kobo.KoboSpanPositionMap;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.ObjectMapper;
@Converter
public class KoboSpanMapJsonConverter implements AttributeConverter<KoboSpanPositionMap, String> {
private static final ObjectMapper objectMapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(KoboSpanPositionMap attribute) {
if (attribute == null) {
return null;
}
try {
return objectMapper.writeValueAsString(attribute);
} catch (JacksonException e) {
throw new IllegalStateException("Failed to serialize Kobo span map to JSON", e);
}
}
@Override
public KoboSpanPositionMap convertToEntityAttribute(String dbData) {
if (dbData == null || dbData.isEmpty()) {
return null;
}
try {
return objectMapper.readValue(dbData, KoboSpanPositionMap.class);
} catch (JacksonException e) {
throw new IllegalStateException("Failed to deserialize Kobo span map from JSON", e);
}
}
}
@@ -0,0 +1,25 @@
package org.booklore.model.dto.kobo;
import java.util.List;
public record KoboSpanPositionMap(List<Chapter> chapters) {
public KoboSpanPositionMap {
chapters = chapters == null ? List.of() : List.copyOf(chapters);
}
public record Chapter(String sourceHref,
String normalizedHref,
int spineIndex,
float globalStartProgress,
float globalEndProgress,
List<Span> spans) {
public Chapter {
spans = spans == null ? List.of() : List.copyOf(spans);
}
}
public record Span(String id, float progression) {
}
}
@@ -11,9 +11,9 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
public class EpubProgress { public class EpubProgress {
@NotNull
String cfi; String cfi;
String href; String href;
Float contentSourceProgressPercent;
@NotNull @NotNull
Float percentage; Float percentage;
String ttsPositionCfi; String ttsPositionCfi;
@@ -7,5 +7,6 @@ public record BookFileProgress(
String positionData, String positionData,
String positionHref, String positionHref,
@NotNull Float progressPercent, @NotNull Float progressPercent,
String ttsPositionCfi) { String ttsPositionCfi,
Float contentSourceProgressPercent) {
} }
@@ -14,7 +14,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor(onConstructor_ = @JsonCreator) @NoArgsConstructor(onConstructor_ = @JsonCreator)
public class KoboSettings { public class KoboSettings {
@Builder.Default @JsonSetter(nulls = Nulls.SKIP) @Builder.Default @JsonSetter(nulls = Nulls.SKIP)
private boolean convertToKepub = false; private boolean convertToKepub = true;
@Builder.Default @JsonSetter(nulls = Nulls.SKIP) @Builder.Default @JsonSetter(nulls = Nulls.SKIP)
private int conversionLimitInMb = 100; private int conversionLimitInMb = 100;
@Builder.Default @JsonSetter(nulls = Nulls.SKIP) @Builder.Default @JsonSetter(nulls = Nulls.SKIP)
@@ -0,0 +1,37 @@
package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.booklore.convertor.KoboSpanMapJsonConverter;
import org.booklore.model.dto.kobo.KoboSpanPositionMap;
import java.time.Instant;
@Entity
@Table(name = "kobo_span_map",
uniqueConstraints = @UniqueConstraint(name = "uk_kobo_span_map_book_file", columnNames = "book_file_id"))
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class KoboSpanMapEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "book_file_id", nullable = false)
private BookFileEntity bookFile;
@Column(name = "file_hash", nullable = false, length = 128)
private String fileHash;
@Convert(converter = KoboSpanMapJsonConverter.class)
@Column(name = "span_map_json", nullable = false, columnDefinition = "LONGTEXT")
private KoboSpanPositionMap spanMap;
@Column(name = "created_at", nullable = false)
private Instant createdAt;
}
@@ -36,6 +36,9 @@ public class UserBookFileProgressEntity {
@Column(name = "progress_percent") @Column(name = "progress_percent")
private Float progressPercent; private Float progressPercent;
@Column(name = "content_source_progress_percent")
private Float contentSourceProgressPercent;
@Column(name = "tts_position_cfi", length = 1000) @Column(name = "tts_position_cfi", length = 1000)
private String ttsPositionCfi; private String ttsPositionCfi;
@@ -0,0 +1,21 @@
package org.booklore.repository;
import org.booklore.model.entity.KoboSpanMapEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@Repository
public interface KoboSpanMapRepository extends JpaRepository<KoboSpanMapEntity, Long> {
@Query("SELECT ksm FROM KoboSpanMapEntity ksm WHERE ksm.bookFile.id = :bookFileId")
Optional<KoboSpanMapEntity> findByBookFileId(@Param("bookFileId") Long bookFileId);
@Query("SELECT ksm FROM KoboSpanMapEntity ksm WHERE ksm.bookFile.id IN :bookFileIds")
List<KoboSpanMapEntity> findByBookFileIdIn(@Param("bookFileIds") Collection<Long> bookFileIds);
}
@@ -63,6 +63,17 @@ public interface UserBookFileProgressRepository extends JpaRepository<UserBookFi
@Param("bookIds") Iterable<Long> bookIds @Param("bookIds") Iterable<Long> bookIds
); );
@EntityGraph(attributePaths = {"bookFile", "bookFile.book"})
@Query("""
SELECT ubfp FROM UserBookFileProgressEntity ubfp
WHERE ubfp.user.id = :userId
AND ubfp.bookFile.id IN :bookFileIds
""")
List<UserBookFileProgressEntity> findByUserIdAndBookFileIdIn(
@Param("userId") Long userId,
@Param("bookFileIds") Iterable<Long> bookFileIds
);
@Modifying @Modifying
@Transactional @Transactional
@Query(""" @Query("""
@@ -311,7 +311,7 @@ public class SettingPersistenceHelper {
public KoboSettings getDefaultKoboSettings() { public KoboSettings getDefaultKoboSettings() {
return KoboSettings.builder() return KoboSettings.builder()
.convertToKepub(false) .convertToKepub(true)
.conversionLimitInMb(100) .conversionLimitInMb(100)
.convertCbxToEpub(false) .convertCbxToEpub(false)
.conversionLimitInMbForCbx(100) .conversionLimitInMbForCbx(100)
@@ -13,6 +13,7 @@ import org.booklore.repository.BookRepository;
import org.booklore.service.appsettings.AppSettingService; import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.kobo.CbxConversionService; import org.booklore.service.kobo.CbxConversionService;
import org.booklore.service.kobo.KepubConversionService; import org.booklore.service.kobo.KepubConversionService;
import org.booklore.service.kobo.KoboSpanMapService;
import org.booklore.util.FileUtils; import org.booklore.util.FileUtils;
import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
@@ -45,6 +46,7 @@ public class BookDownloadService {
private final BookFileRepository bookFileRepository; private final BookFileRepository bookFileRepository;
private final KepubConversionService kepubConversionService; private final KepubConversionService kepubConversionService;
private final CbxConversionService cbxConversionService; private final CbxConversionService cbxConversionService;
private final KoboSpanMapService koboSpanMapService;
private final AppSettingService appSettingService; private final AppSettingService appSettingService;
public ResponseEntity<Resource> downloadBook(Long bookId) { public ResponseEntity<Resource> downloadBook(Long bookId) {
@@ -258,7 +260,7 @@ public class BookDownloadService {
throw ApiError.GENERIC_BAD_REQUEST.createException("Kobo settings not found."); throw ApiError.GENERIC_BAD_REQUEST.createException("Kobo settings not found.");
} }
boolean convertEpubToKepub = isEpub && koboSettings.isConvertToKepub() && primaryFile.getFileSizeKb() <= (long) koboSettings.getConversionLimitInMb() * 1024; boolean convertEpubToKepub = isEpub && !primaryFile.isFixedLayout() && koboSettings.isConvertToKepub() && primaryFile.getFileSizeKb() <= (long) koboSettings.getConversionLimitInMb() * 1024;
boolean convertCbxToEpub = isCbx && koboSettings.isConvertCbxToEpub() && primaryFile.getFileSizeKb() <= (long) koboSettings.getConversionLimitInMbForCbx() * 1024; boolean convertCbxToEpub = isCbx && koboSettings.isConvertCbxToEpub() && primaryFile.getFileSizeKb() <= (long) koboSettings.getConversionLimitInMbForCbx() * 1024;
int compressionPercentage = koboSettings.getConversionImageCompressionPercentage(); int compressionPercentage = koboSettings.getConversionImageCompressionPercentage();
@@ -280,6 +282,11 @@ public class BookDownloadService {
if (convertEpubToKepub) { if (convertEpubToKepub) {
fileToSend = kepubConversionService.convertEpubToKepub(inputFile, tempDir.toFile(), fileToSend = kepubConversionService.convertEpubToKepub(inputFile, tempDir.toFile(),
koboSettings.isForceEnableHyphenation()); koboSettings.isForceEnableHyphenation());
try {
koboSpanMapService.computeAndStoreIfNeeded(primaryFile, fileToSend);
} catch (Exception e) {
log.warn("Failed to compute Kobo span map for file {}: {}", primaryFile.getId(), e.getMessage());
}
} }
setResponseHeaders(response, fileToSend); setResponseHeaders(response, fileToSend);
@@ -0,0 +1,245 @@
package org.booklore.service.kobo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.kobo.KoboSpanPositionMap;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.UserBookFileProgressEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.util.koreader.EpubCfiService;
import org.springframework.stereotype.Service;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import static org.booklore.service.kobo.KoboEpubUtils.normalizeHref;
@Slf4j
@Service
@RequiredArgsConstructor
public class KoboBookmarkLocationResolver {
private final KoboSpanMapService koboSpanMapService;
private final EpubCfiService epubCfiService;
public Optional<ResolvedBookmarkLocation> resolve(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress) {
return resolve(progress, fileProgress, null);
}
public Optional<ResolvedBookmarkLocation> resolve(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress,
Map<Long, KoboSpanPositionMap> preloadedMaps) {
BookFileEntity bookFile = resolveBookFile(progress, fileProgress);
if (!isKepubExportEnabled(bookFile)) {
return Optional.empty();
}
Optional<KoboSpanPositionMap> spanMap = lookupSpanMap(bookFile, preloadedMaps);
if (spanMap.isEmpty() || spanMap.get().chapters().isEmpty()) {
return Optional.empty();
}
Optional<EpubCfiService.CfiLocation> cfiLocation = resolveCfiLocation(bookFile, progress, fileProgress);
String href = cfiLocation
.map(EpubCfiService.CfiLocation::href)
.filter(value -> !value.isBlank())
.orElseGet(() -> resolveHref(progress, fileProgress));
Float chapterProgressPercent = Optional.ofNullable(fileProgress)
.map(UserBookFileProgressEntity::getContentSourceProgressPercent)
.orElseGet(() -> cfiLocation
.map(EpubCfiService.CfiLocation::contentSourceProgressPercent)
.orElse(null));
Float globalProgressPercent = resolveGlobalProgressPercent(progress, fileProgress);
Optional<KoboSpanPositionMap.Chapter> chapter = resolveChapter(spanMap.get(), href, globalProgressPercent);
if (chapter.isEmpty()) {
return Optional.empty();
}
Float resolvedChapterProgressPercent = resolveChapterProgressPercent(chapter.get(), chapterProgressPercent,
globalProgressPercent);
KoboSpanPositionMap.Span span = resolveSpanMarker(chapter.get(), resolvedChapterProgressPercent);
if (span == null) {
return Optional.empty();
}
return Optional.of(new ResolvedBookmarkLocation(
span.id(),
"KoboSpan",
chapter.get().sourceHref(),
resolvedChapterProgressPercent));
}
private Optional<EpubCfiService.CfiLocation> resolveCfiLocation(BookFileEntity bookFile,
UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress) {
String cfi = resolveCfi(progress, fileProgress);
if (cfi == null || cfi.isBlank() || bookFile == null) {
return Optional.empty();
}
try {
Path epubPath = bookFile.getFullFilePath();
if (epubPath == null) {
return Optional.empty();
}
return epubCfiService.resolveCfiLocation(epubPath, cfi);
} catch (Exception e) {
log.debug("Failed to derive chapter position from CFI for bookFile {}: {}", bookFile.getId(), e.getMessage());
return Optional.empty();
}
}
private BookFileEntity resolveBookFile(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress) {
if (fileProgress != null && fileProgress.getBookFile() != null) {
return fileProgress.getBookFile();
}
if (progress == null || progress.getBook() == null) {
return null;
}
return progress.getBook().getPrimaryBookFile();
}
private Optional<KoboSpanPositionMap> lookupSpanMap(BookFileEntity bookFile,
Map<Long, KoboSpanPositionMap> preloadedMaps) {
if (preloadedMaps != null && bookFile.getId() != null) {
KoboSpanPositionMap map = preloadedMaps.get(bookFile.getId());
if (map != null) {
return Optional.of(map);
}
}
return koboSpanMapService.getValidMap(bookFile);
}
private boolean isKepubExportEnabled(BookFileEntity bookFile) {
if (bookFile == null) {
return false;
}
return bookFile.getBookType() == BookFileType.EPUB && !bookFile.isFixedLayout();
}
private String resolveHref(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress) {
return Optional.ofNullable(fileProgress)
.map(UserBookFileProgressEntity::getPositionHref)
.filter(value -> !value.isBlank())
.orElseGet(() -> Optional.ofNullable(progress)
.map(UserBookProgressEntity::getEpubProgressHref)
.filter(value -> !value.isBlank())
.orElse(null));
}
private String resolveCfi(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress) {
return Optional.ofNullable(fileProgress)
.map(UserBookFileProgressEntity::getPositionData)
.filter(value -> value != null && value.startsWith("epubcfi("))
.orElseGet(() -> Optional.ofNullable(progress)
.map(UserBookProgressEntity::getEpubProgress)
.filter(value -> value != null && value.startsWith("epubcfi("))
.orElse(null));
}
private Float resolveGlobalProgressPercent(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress) {
Float fileProgressPercent = Optional.ofNullable(fileProgress)
.map(UserBookFileProgressEntity::getProgressPercent)
.orElse(null);
if (fileProgressPercent != null) {
return fileProgressPercent;
}
return Optional.ofNullable(progress)
.map(UserBookProgressEntity::getEpubProgressPercent)
.orElse(null);
}
private Optional<KoboSpanPositionMap.Chapter> resolveChapter(KoboSpanPositionMap spanMap,
String href,
Float globalProgressPercent) {
Optional<KoboSpanPositionMap.Chapter> byHref = findChapterByHref(spanMap, href);
if (byHref.isPresent()) {
return byHref;
}
if (globalProgressPercent == null) {
return Optional.empty();
}
return findChapterByGlobalProgress(spanMap, globalProgressPercent);
}
private Optional<KoboSpanPositionMap.Chapter> findChapterByHref(KoboSpanPositionMap spanMap, String href) {
if (href == null || href.isBlank()) {
return Optional.empty();
}
String normalizedHref = normalizeHref(href);
return spanMap.chapters().stream()
.filter(chapter -> {
String normalizedChapter = chapter.normalizedHref();
return normalizedChapter.equals(normalizedHref)
|| normalizedChapter.endsWith("/" + normalizedHref);
})
.max(Comparator.<KoboSpanPositionMap.Chapter>comparingInt(chapter -> {
String normalizedChapter = chapter.normalizedHref();
return normalizedChapter.equals(normalizedHref) ? 1 : 0;
}).thenComparingInt(chapter -> chapter.normalizedHref().length()));
}
private Optional<KoboSpanPositionMap.Chapter> findChapterByGlobalProgress(KoboSpanPositionMap spanMap,
Float globalProgressPercent) {
float globalProgress = globalProgressPercent / 100f;
return spanMap.chapters().stream()
.min(Comparator.comparingDouble(chapter -> distanceToChapter(globalProgress, chapter)));
}
private Float resolveChapterProgressPercent(KoboSpanPositionMap.Chapter chapter,
Float chapterProgressPercent,
Float globalProgressPercent) {
if (chapterProgressPercent != null) {
return chapterProgressPercent;
}
if (globalProgressPercent != null) {
float chapterStart = chapter.globalStartProgress();
float chapterEnd = chapter.globalEndProgress();
float chapterWidth = chapterEnd - chapterStart;
if (chapterWidth <= 0f) {
return 0f;
}
float chapterProgress = (globalProgressPercent / 100f - chapterStart) / chapterWidth;
return chapterProgress * 100f;
}
return null;
}
private KoboSpanPositionMap.Span resolveSpanMarker(KoboSpanPositionMap.Chapter chapter, Float chapterProgressPercent) {
if (chapter.spans().isEmpty()) {
return null;
}
if (chapterProgressPercent == null) {
return chapter.spans().getFirst();
}
float targetProgress = chapterProgressPercent / 100f;
return chapter.spans().stream()
.min(Comparator.comparingDouble(item -> Math.abs(item.progression() - targetProgress)))
.orElse(null);
}
private double distanceToChapter(float globalProgress, KoboSpanPositionMap.Chapter chapter) {
if (globalProgress < chapter.globalStartProgress()) {
return chapter.globalStartProgress() - globalProgress;
}
if (globalProgress > chapter.globalEndProgress()) {
return globalProgress - chapter.globalEndProgress();
}
return 0d;
}
public record ResolvedBookmarkLocation(String value,
String type,
String source,
Float contentSourceProgressPercent) {
}
}
@@ -14,6 +14,7 @@ import org.booklore.model.enums.ShelfType;
import org.booklore.repository.KoboReadingStateRepository; import org.booklore.repository.KoboReadingStateRepository;
import org.booklore.repository.MagicShelfRepository; import org.booklore.repository.MagicShelfRepository;
import org.booklore.repository.ShelfRepository; import org.booklore.repository.ShelfRepository;
import org.booklore.repository.UserBookFileProgressRepository;
import org.booklore.repository.UserBookProgressRepository; import org.booklore.repository.UserBookProgressRepository;
import org.booklore.service.appsettings.AppSettingService; import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.book.BookQueryService; import org.booklore.service.book.BookQueryService;
@@ -43,6 +44,7 @@ public class KoboEntitlementService {
private final AppSettingService appSettingService; private final AppSettingService appSettingService;
private final KoboCompatibilityService koboCompatibilityService; private final KoboCompatibilityService koboCompatibilityService;
private final UserBookProgressRepository progressRepository; private final UserBookProgressRepository progressRepository;
private final UserBookFileProgressRepository fileProgressRepository;
private final KoboReadingStateRepository readingStateRepository; private final KoboReadingStateRepository readingStateRepository;
private final KoboReadingStateMapper readingStateMapper; private final KoboReadingStateMapper readingStateMapper;
private final AuthenticationService authenticationService; private final AuthenticationService authenticationService;
@@ -51,6 +53,7 @@ public class KoboEntitlementService {
private final MagicShelfRepository magicShelfRepository; private final MagicShelfRepository magicShelfRepository;
private final MagicShelfBookService magicShelfBookService; private final MagicShelfBookService magicShelfBookService;
private final KoboSettingsService koboSettingsService; private final KoboSettingsService koboSettingsService;
private final KoboSpanMapService koboSpanMapService;
public List<NewEntitlement> generateNewEntitlements(Set<Long> bookIds, String token) { public List<NewEntitlement> generateNewEntitlements(Set<Long> bookIds, String token) {
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds); List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
@@ -108,9 +111,40 @@ public class KoboEntitlementService {
public List<ChangedReadingState> generateChangedReadingStates(List<UserBookProgressEntity> progressEntries) { public List<ChangedReadingState> generateChangedReadingStates(List<UserBookProgressEntity> progressEntries) {
OffsetDateTime now = getCurrentUtc(); OffsetDateTime now = getCurrentUtc();
String timestamp = now.toString(); String timestamp = now.toString();
Long userId = authenticationService.getAuthenticatedUser().getId();
Map<Long, Long> syncedEpubFileIdsByBookId = new HashMap<>();
Map<Long, BookFileEntity> bookFilesByFileId = new HashMap<>();
for (UserBookProgressEntity entry : progressEntries) {
BookEntity book = entry.getBook();
if (book != null) {
BookFileEntity syncedFile = KoboEpubUtils.getSyncedEpubFile(book);
if (syncedFile != null) {
syncedEpubFileIdsByBookId.putIfAbsent(book.getId(), syncedFile.getId());
bookFilesByFileId.putIfAbsent(syncedFile.getId(), syncedFile);
}
}
}
Map<Long, UserBookFileProgressEntity> fileProgressByFileId = syncedEpubFileIdsByBookId.isEmpty()
? Collections.emptyMap()
: fileProgressRepository.findByUserIdAndBookFileIdIn(userId, syncedEpubFileIdsByBookId.values()).stream()
.collect(Collectors.toMap(
fp -> fp.getBookFile().getId(),
fp -> fp
));
Map<Long, KoboSpanPositionMap> spanMapsByFileId = bookFilesByFileId.isEmpty()
? Collections.emptyMap()
: koboSpanMapService.getValidMaps(bookFilesByFileId);
return progressEntries.stream() return progressEntries.stream()
.map(progress -> buildChangedReadingState(progress, timestamp, now)) .map(progress -> buildChangedReadingState(
progress,
fileProgressByFileId.get(syncedEpubFileIdsByBookId.get(progress.getBook().getId())),
timestamp,
now,
spanMapsByFileId))
.toList(); .toList();
} }
@@ -180,12 +214,16 @@ public class KoboEntitlementService {
.build(); .build();
} }
private ChangedReadingState buildChangedReadingState(UserBookProgressEntity progress, String timestamp, OffsetDateTime now) { private ChangedReadingState buildChangedReadingState(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress,
String timestamp,
OffsetDateTime now,
Map<Long, KoboSpanPositionMap> preloadedMaps) {
String entitlementId = String.valueOf(progress.getBook().getId()); String entitlementId = String.valueOf(progress.getBook().getId());
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync(); boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
KoboReadingState.CurrentBookmark bookmark = (progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null)) KoboReadingState.CurrentBookmark bookmark = (progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
? readingStateBuilder.buildBookmarkFromProgress(progress, now) ? readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress, now, preloadedMaps)
: readingStateBuilder.buildEmptyBookmark(now); : readingStateBuilder.buildEmptyBookmark(now);
KoboReadingState readingState = KoboReadingState.builder() KoboReadingState readingState = KoboReadingState.builder()
@@ -218,14 +256,15 @@ public class KoboEntitlementService {
.orElse(null); .orElse(null);
Optional<UserBookProgressEntity> userProgress = progressRepository Optional<UserBookProgressEntity> userProgress = progressRepository
.findByUserIdAndBookId(authenticationService.getAuthenticatedUser().getId(), book.getId()); .findByUserIdAndBookId(userId, book.getId());
UserBookFileProgressEntity fileProgress = findSyncedEpubFileProgress(userId, book).orElse(null);
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync(); boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
KoboReadingState.CurrentBookmark webReaderBookmark = twoWaySync KoboReadingState.CurrentBookmark webReaderBookmark = twoWaySync
? userProgress ? userProgress
.filter(progress -> progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null) .filter(readingStateBuilder::shouldUseWebReaderProgress)
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now)) .map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress, now))
.orElse(null) .orElse(null)
: null; : null;
@@ -235,7 +274,7 @@ public class KoboEntitlementService {
? existingState.getCurrentBookmark() ? existingState.getCurrentBookmark()
: userProgress : userProgress
.filter(progress -> progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null)) .filter(progress -> progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now)) .map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress, now))
.orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now)); .orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now));
KoboReadingState.StatusInfo statusInfo = userProgress KoboReadingState.StatusInfo statusInfo = userProgress
@@ -257,6 +296,14 @@ public class KoboEntitlementService {
.build(); .build();
} }
private Optional<UserBookFileProgressEntity> findSyncedEpubFileProgress(Long userId, BookEntity book) {
BookFileEntity syncedFile = KoboEpubUtils.getSyncedEpubFile(book);
if (syncedFile == null) {
return Optional.empty();
}
return fileProgressRepository.findByUserIdAndBookFileId(userId, syncedFile.getId());
}
private BookEntitlement buildBookEntitlement(BookEntity book, boolean removed) { private BookEntitlement buildBookEntitlement(BookEntity book, boolean removed) {
OffsetDateTime now = getCurrentUtc(); OffsetDateTime now = getCurrentUtc();
OffsetDateTime createdOn = getCreatedOn(book); OffsetDateTime createdOn = getCreatedOn(book);
@@ -333,14 +380,12 @@ public class KoboEntitlementService {
boolean isEpubFile = primaryFile.getBookType() == BookFileType.EPUB; boolean isEpubFile = primaryFile.getBookType() == BookFileType.EPUB;
boolean isCbxFile = primaryFile.getBookType() == BookFileType.CBX; boolean isCbxFile = primaryFile.getBookType() == BookFileType.CBX;
if (koboSettings != null) { if (isEpubFile && primaryFile.isFixedLayout()) {
if (isEpubFile && primaryFile.isFixedLayout()) { bookFormat = KoboBookFormat.EPUB3FL;
bookFormat = KoboBookFormat.EPUB3FL; } else if (isEpubFile && koboSettings != null && koboSettings.isConvertToKepub()) {
} else if (isEpubFile && koboSettings.isConvertToKepub()) { bookFormat = KoboBookFormat.KEPUB;
bookFormat = KoboBookFormat.KEPUB; } else if (koboSettings != null && isCbxFile && koboSettings.isConvertCbxToEpub()) {
} else if (isCbxFile && koboSettings.isConvertCbxToEpub()) { bookFormat = KoboBookFormat.EPUB3;
bookFormat = KoboBookFormat.EPUB3;
}
} }
return KoboBookMetadata.builder() return KoboBookMetadata.builder()
@@ -0,0 +1,45 @@
package org.booklore.service.kobo;
import lombok.experimental.UtilityClass;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.enums.BookFileType;
import java.net.URI;
@UtilityClass
class KoboEpubUtils {
static BookFileEntity getSyncedEpubFile(BookEntity book) {
BookFileEntity primaryFile = book != null ? book.getPrimaryBookFile() : null;
if (primaryFile == null || primaryFile.getBookType() != BookFileType.EPUB) {
return null;
}
return primaryFile;
}
static String decodeHrefPath(String href) {
if (href == null) {
return null;
}
String normalizedPath = href.replaceFirst("#.*$", "")
.replace('\\', '/');
try {
String decodedPath = URI.create(normalizedPath).getPath();
return decodedPath != null ? decodedPath : normalizedPath;
} catch (IllegalArgumentException e) {
return normalizedPath;
}
}
static String normalizeHref(String href) {
String decodedHref = decodeHrefPath(href);
if (decodedHref == null) {
return null;
}
return decodedHref.replaceFirst("^/+", "");
}
}
@@ -83,7 +83,7 @@ public class KoboLibrarySyncService {
boolean shouldContinueSync = false; boolean shouldContinueSync = false;
if (prevSnapshot.isPresent()) { if (prevSnapshot.isPresent()) {
int maxRemaining = 5; int maxRemaining = 100;
List<KoboSnapshotBookEntity> removedAll = new ArrayList<>(); List<KoboSnapshotBookEntity> removedAll = new ArrayList<>();
List<KoboSnapshotBookEntity> changedAll = new ArrayList<>(); List<KoboSnapshotBookEntity> changedAll = new ArrayList<>();
@@ -123,7 +123,7 @@ public class KoboLibrarySyncService {
entitlements.addAll(entitlementService.generateTags()); entitlements.addAll(entitlementService.generateTags());
} }
} else { } else {
int maxRemaining = 5; int maxRemaining = 100;
List<KoboSnapshotBookEntity> snapshotBookEntities = new ArrayList<>(); List<KoboSnapshotBookEntity> snapshotBookEntities = new ArrayList<>();
while (maxRemaining > 0) { while (maxRemaining > 0) {
Page<KoboSnapshotBookEntity> page = koboLibrarySnapshotService.getUnsyncedBooks(currSnapshot.getId(), PageRequest.of(0, maxRemaining)); Page<KoboSnapshotBookEntity> page = koboLibrarySnapshotService.getUnsyncedBooks(currSnapshot.getId(), PageRequest.of(0, maxRemaining));
@@ -230,7 +230,7 @@ public class KoboLibrarySyncService {
} }
if (koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync() if (koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()
&& progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null) { && progress.getEpubProgressPercent() != null) {
Instant sentTime = progress.getKoboProgressSentTime(); Instant sentTime = progress.getKoboProgressSentTime();
Instant lastReadTime = progress.getLastReadTime(); Instant lastReadTime = progress.getLastReadTime();
if (lastReadTime != null && (sentTime == null || lastReadTime.isAfter(sentTime))) { if (lastReadTime != null && (sentTime == null || lastReadTime.isAfter(sentTime))) {
@@ -2,21 +2,30 @@ package org.booklore.service.kobo;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.booklore.model.dto.kobo.KoboReadingState; import org.booklore.model.dto.kobo.KoboReadingState;
import org.booklore.model.entity.UserBookFileProgressEntity;
import org.booklore.model.entity.UserBookProgressEntity; import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.KoboReadStatus; import org.booklore.model.enums.KoboReadStatus;
import org.booklore.model.enums.ReadStatus; import org.booklore.model.enums.ReadStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.booklore.model.dto.kobo.KoboSpanPositionMap;
import java.time.Instant; import java.time.Instant;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
public class KoboReadingStateBuilder { public class KoboReadingStateBuilder {
private static final DateTimeFormatter KOBO_TIMESTAMP_FORMAT =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'").withZone(ZoneOffset.UTC);
private final KoboSettingsService koboSettingsService; private final KoboSettingsService koboSettingsService;
private final KoboBookmarkLocationResolver bookmarkLocationResolver;
public KoboReadingState.CurrentBookmark buildEmptyBookmark(OffsetDateTime timestamp) { public KoboReadingState.CurrentBookmark buildEmptyBookmark(OffsetDateTime timestamp) {
return KoboReadingState.CurrentBookmark.builder() return KoboReadingState.CurrentBookmark.builder()
@@ -24,35 +33,80 @@ public class KoboReadingStateBuilder {
.build(); .build();
} }
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress) { public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress,
return buildBookmarkFromProgress(progress, null); UserBookFileProgressEntity fileProgress) {
return buildBookmarkFromProgress(progress, fileProgress, null, null);
} }
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) { public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress,
if (isWebReaderNewer(progress)) { UserBookFileProgressEntity fileProgress,
return buildBookmarkFromWebReaderProgress(progress, defaultTime); OffsetDateTime defaultTime) {
return buildBookmarkFromProgress(progress, fileProgress, defaultTime, null);
}
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress,
OffsetDateTime defaultTime,
Map<Long, KoboSpanPositionMap> preloadedMaps) {
if (shouldUseWebReaderProgress(progress)) {
return buildBookmarkFromWebReaderProgress(progress, fileProgress, defaultTime, preloadedMaps);
} }
return buildBookmarkFromKoboProgress(progress, defaultTime); return buildBookmarkFromKoboProgress(progress, fileProgress, defaultTime);
} }
private boolean isWebReaderNewer(UserBookProgressEntity progress) { public boolean shouldUseWebReaderProgress(UserBookProgressEntity progress) {
return koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync() if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
&& progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null; return false;
}
if (progress.getEpubProgressPercent() == null) {
return false;
}
if (progress.getLastReadTime() == null) {
return false;
}
if (progress.getKoboProgressReceivedTime() == null) {
return true;
}
return progress.getLastReadTime().isAfter(progress.getKoboProgressReceivedTime());
} }
private KoboReadingState.CurrentBookmark buildBookmarkFromWebReaderProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) { private KoboReadingState.CurrentBookmark buildBookmarkFromWebReaderProgress(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress,
OffsetDateTime defaultTime,
Map<Long, KoboSpanPositionMap> preloadedMaps) {
String lastModified = Optional.ofNullable(progress.getLastReadTime()) String lastModified = Optional.ofNullable(progress.getLastReadTime())
.map(this::formatTimestamp) .map(this::formatTimestamp)
.or(() -> Optional.ofNullable(defaultTime).map(OffsetDateTime::toString)) .or(() -> Optional.ofNullable(defaultTime).map(OffsetDateTime::toString))
.orElse(null); .orElse(null);
Optional<KoboBookmarkLocationResolver.ResolvedBookmarkLocation> resolvedLocation =
bookmarkLocationResolver.resolve(progress, fileProgress, preloadedMaps);
KoboReadingState.CurrentBookmark.Location location = resolvedLocation
.map(resolved -> KoboReadingState.CurrentBookmark.Location.builder()
.value(resolved.value())
.type(resolved.type())
.source(resolved.source())
.build())
.orElse(null);
return KoboReadingState.CurrentBookmark.builder() return KoboReadingState.CurrentBookmark.builder()
.progressPercent(Math.round(progress.getEpubProgressPercent())) .progressPercent(Math.round(progress.getEpubProgressPercent()))
.contentSourceProgressPercent(resolvedLocation
.map(KoboBookmarkLocationResolver.ResolvedBookmarkLocation::contentSourceProgressPercent)
.map(Math::round)
.orElseGet(() -> Optional.ofNullable(fileProgress)
.map(UserBookFileProgressEntity::getContentSourceProgressPercent)
.map(Math::round)
.orElse(null)))
.location(location)
.lastModified(lastModified) .lastModified(lastModified)
.build(); .build();
} }
private KoboReadingState.CurrentBookmark buildBookmarkFromKoboProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) { private KoboReadingState.CurrentBookmark buildBookmarkFromKoboProgress(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress,
OffsetDateTime defaultTime) {
KoboReadingState.CurrentBookmark.Location location = Optional.ofNullable(progress.getKoboLocation()) KoboReadingState.CurrentBookmark.Location location = Optional.ofNullable(progress.getKoboLocation())
.map(koboLocation -> KoboReadingState.CurrentBookmark.Location.builder() .map(koboLocation -> KoboReadingState.CurrentBookmark.Location.builder()
.value(koboLocation) .value(koboLocation)
@@ -70,13 +124,19 @@ public class KoboReadingStateBuilder {
.progressPercent(Optional.ofNullable(progress.getKoboProgressPercent()) .progressPercent(Optional.ofNullable(progress.getKoboProgressPercent())
.map(Math::round) .map(Math::round)
.orElse(null)) .orElse(null))
.contentSourceProgressPercent(Optional.ofNullable(fileProgress)
.map(UserBookFileProgressEntity::getContentSourceProgressPercent)
.map(Math::round)
.orElse(null))
.location(location) .location(location)
.lastModified(lastModified) .lastModified(lastModified)
.build(); .build();
} }
public KoboReadingState buildReadingStateFromProgress(String entitlementId, UserBookProgressEntity progress) { public KoboReadingState buildReadingStateFromProgress(String entitlementId,
KoboReadingState.CurrentBookmark bookmark = buildBookmarkFromProgress(progress); UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress) {
KoboReadingState.CurrentBookmark bookmark = buildBookmarkFromProgress(progress, fileProgress);
String lastModified = bookmark.getLastModified(); String lastModified = bookmark.getLastModified();
KoboReadingState.StatusInfo statusInfo = buildStatusInfoFromProgress(progress, lastModified); KoboReadingState.StatusInfo statusInfo = buildStatusInfoFromProgress(progress, lastModified);
@@ -118,6 +178,6 @@ public class KoboReadingStateBuilder {
} }
private String formatTimestamp(Instant instant) { private String formatTimestamp(Instant instant) {
return instant.atOffset(ZoneOffset.UTC).toString(); return KOBO_TIMESTAMP_FORMAT.format(instant);
} }
} }
@@ -9,6 +9,7 @@ import org.booklore.model.dto.KoboSyncSettings;
import org.booklore.model.dto.kobo.KoboReadingState; import org.booklore.model.dto.kobo.KoboReadingState;
import org.booklore.model.dto.response.kobo.KoboReadingStateResponse; import org.booklore.model.dto.response.kobo.KoboReadingStateResponse;
import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.BookLoreUserEntity; import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.KoboReadingStateEntity; import org.booklore.model.entity.KoboReadingStateEntity;
import org.booklore.model.entity.UserBookFileProgressEntity; import org.booklore.model.entity.UserBookFileProgressEntity;
@@ -117,9 +118,8 @@ public class KoboReadingStateService {
syncKoboProgressToUserBookProgress(savedState, userId); syncKoboProgressToUserBookProgress(savedState, userId);
return savedEntity; return savedState;
}) })
.map(mapper::toDto)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@@ -155,19 +155,11 @@ public class KoboReadingStateService {
} }
try { try {
Long bookId = Long.parseLong(entitlementId); Long bookId = Long.parseLong(entitlementId);
UserBookFileProgressEntity fileProgress = findSyncedEpubFileProgress(userId, bookId).orElse(null);
progressRepository.findByUserIdAndBookId(userId, bookId) progressRepository.findByUserIdAndBookId(userId, bookId)
.filter(progress -> progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null) .filter(readingStateBuilder::shouldUseWebReaderProgress)
.ifPresent(progress -> { .ifPresent(progress -> state.setCurrentBookmark(
KoboReadingState.CurrentBookmark existing = state.getCurrentBookmark(); readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress)));
KoboReadingState.CurrentBookmark webReaderBookmark = readingStateBuilder.buildBookmarkFromProgress(progress);
if (existing != null) {
existing.setProgressPercent(webReaderBookmark.getProgressPercent());
existing.setLastModified(webReaderBookmark.getLastModified());
} else {
state.setCurrentBookmark(webReaderBookmark);
}
});
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
// Not a valid book ID, skip overlay // Not a valid book ID, skip overlay
} }
@@ -181,7 +173,10 @@ public class KoboReadingStateService {
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync(); boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
return progressRepository.findByUserIdAndBookId(user.getId(), bookId) return progressRepository.findByUserIdAndBookId(user.getId(), bookId)
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null || (twoWaySync && progress.getEpubProgressPercent() != null)) .filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
.map(progress -> readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress)); .map(progress -> readingStateBuilder.buildReadingStateFromProgress(
entitlementId,
progress,
findSyncedEpubFileProgress(user.getId(), bookId).orElse(null)));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
log.warn("Invalid entitlement ID format when constructing reading state: {}", entitlementId); log.warn("Invalid entitlement ID format when constructing reading state: {}", entitlementId);
return Optional.empty(); return Optional.empty();
@@ -213,7 +208,7 @@ public class KoboReadingStateService {
return newProgress; return newProgress;
}); });
Float prevousKoboProgressPercent = progress.getKoboProgressPercent(); Float previousKoboProgressPercent = progress.getKoboProgressPercent();
ReadStatus previousReadStatus = progress.getReadStatus(); ReadStatus previousReadStatus = progress.getReadStatus();
KoboReadingState.CurrentBookmark bookmark = readingState.getCurrentBookmark(); KoboReadingState.CurrentBookmark bookmark = readingState.getCurrentBookmark();
@@ -231,23 +226,31 @@ public class KoboReadingStateService {
} }
Instant now = Instant.now(); Instant now = Instant.now();
progress.setKoboProgressReceivedTime(now); Instant bookmarkTime = bookmark != null ? parseTimestamp(bookmark.getLastModified()) : null;
Instant effectiveBookmarkTime = bookmarkTime != null ? bookmarkTime : now;
boolean koboApplied = crossPopulateEpubFieldsFromKobo(progress, bookmark, book, userId, now); Optional<UserBookFileProgressEntity> existingFileProgress = findSyncedEpubFileProgress(userId, book);
if (koboApplied) { boolean webReaderIsNewer = isWebReaderNewerThanBookmark(existingFileProgress.orElse(null), bookmarkTime);
progress.setLastReadTime(now); if (bookmark != null && (bookmark.getProgressPercent() != null || bookmark.getLocation() != null)) {
progress.setKoboProgressReceivedTime(effectiveBookmarkTime);
} }
if (progress.getKoboProgressPercent() != null) { boolean koboApplied = crossPopulateEpubFieldsFromKobo(progress, bookmark, book,
updateReadStatusFromKoboProgress(progress, now); existingFileProgress.orElse(null), bookmarkTime, effectiveBookmarkTime);
if (koboApplied) {
progress.setLastReadTime(effectiveBookmarkTime);
}
if (progress.getKoboProgressPercent() != null && !webReaderIsNewer) {
updateReadStatusFromKoboProgress(progress, effectiveBookmarkTime);
} }
progressRepository.save(progress); progressRepository.save(progress);
// Sync progress to Hardcover asynchronously (if enabled for this user) // Sync progress to Hardcover asynchronously (if enabled for this user)
// But only if the progress percentage has changed from last time, or the read status has changed // But only if the progress percentage has changed from last time, or the read status has changed
if (progress.getKoboProgressPercent() != null if (!webReaderIsNewer
&& (!progress.getKoboProgressPercent().equals(prevousKoboProgressPercent) && progress.getKoboProgressPercent() != null
&& (!progress.getKoboProgressPercent().equals(previousKoboProgressPercent)
|| progress.getReadStatus() != previousReadStatus)) { || progress.getReadStatus() != previousReadStatus)) {
hardcoverSyncService.syncProgressToHardcover(book.getId(), progress.getKoboProgressPercent(), userId); hardcoverSyncService.syncProgressToHardcover(book.getId(), progress.getKoboProgressPercent(), userId);
} }
@@ -257,8 +260,11 @@ public class KoboReadingStateService {
} }
private boolean crossPopulateEpubFieldsFromKobo(UserBookProgressEntity progress, private boolean crossPopulateEpubFieldsFromKobo(UserBookProgressEntity progress,
KoboReadingState.CurrentBookmark bookmark, KoboReadingState.CurrentBookmark bookmark,
BookEntity book, Long userId, Instant now) { BookEntity book,
UserBookFileProgressEntity existingFileProgress,
Instant bookmarkTime,
Instant effectiveBookmarkTime) {
if (bookmark == null || bookmark.getProgressPercent() == null) { if (bookmark == null || bookmark.getProgressPercent() == null) {
return false; return false;
} }
@@ -267,40 +273,65 @@ public class KoboReadingStateService {
return false; return false;
} }
UserBookFileProgressEntity fileProgress = book.getPrimaryBookFile() != null boolean webReaderIsNewer = existingFileProgress != null
? fileProgressRepository.findByUserIdAndBookFileId(userId, book.getPrimaryBookFile().getId()).orElse(null) && existingFileProgress.getLastReadTime() != null
: null;
Instant bookmarkTime = parseTimestamp(bookmark.getLastModified());
boolean webReaderIsNewer = fileProgress != null
&& fileProgress.getLastReadTime() != null
&& bookmarkTime != null && bookmarkTime != null
&& fileProgress.getLastReadTime().isAfter(bookmarkTime); && existingFileProgress.getLastReadTime().isAfter(bookmarkTime);
if (webReaderIsNewer) { if (webReaderIsNewer) {
return false; return false;
} }
UserBookFileProgressEntity fileProgress = existingFileProgress;
BookFileEntity syncedEpubFile = KoboEpubUtils.getSyncedEpubFile(book);
if (fileProgress == null && syncedEpubFile != null) {
fileProgress = UserBookFileProgressEntity.builder()
.user(progress.getUser())
.bookFile(syncedEpubFile)
.build();
}
progress.setEpubProgressPercent(bookmark.getProgressPercent().floatValue()); progress.setEpubProgressPercent(bookmark.getProgressPercent().floatValue());
KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation(); KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation();
if (location != null && location.getSource() != null) {
progress.setEpubProgressHref(location.getSource());
}
progress.setEpubProgress(null); progress.setEpubProgress(null);
progress.setEpubProgressHref(location != null ? location.getSource() : null);
if (fileProgress != null) { if (fileProgress != null) {
fileProgress.setProgressPercent(bookmark.getProgressPercent().floatValue()); fileProgress.setProgressPercent(bookmark.getProgressPercent().floatValue());
if (location != null && location.getSource() != null) { fileProgress.setContentSourceProgressPercent(bookmark.getContentSourceProgressPercent() != null
fileProgress.setPositionHref(location.getSource()); ? bookmark.getContentSourceProgressPercent().floatValue()
} : null);
fileProgress.setPositionData(null); fileProgress.setPositionData(null);
fileProgress.setLastReadTime(now); fileProgress.setPositionHref(location != null ? location.getSource() : null);
fileProgress.setLastReadTime(effectiveBookmarkTime);
fileProgressRepository.save(fileProgress); fileProgressRepository.save(fileProgress);
} }
return true; return true;
} }
private Optional<UserBookFileProgressEntity> findSyncedEpubFileProgress(Long userId, Long bookId) {
return bookRepository.findById(bookId)
.flatMap(book -> findSyncedEpubFileProgress(userId, book));
}
private Optional<UserBookFileProgressEntity> findSyncedEpubFileProgress(Long userId, BookEntity book) {
BookFileEntity syncedEpubFile = KoboEpubUtils.getSyncedEpubFile(book);
if (syncedEpubFile == null) {
return Optional.empty();
}
return fileProgressRepository.findByUserIdAndBookFileId(userId, syncedEpubFile.getId());
}
private boolean isWebReaderNewerThanBookmark(UserBookFileProgressEntity fileProgress, Instant bookmarkTime) {
if (bookmarkTime == null || !koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
return false;
}
return fileProgress != null
&& fileProgress.getLastReadTime() != null
&& fileProgress.getLastReadTime().isAfter(bookmarkTime);
}
private void normalizePutTimestamps(List<KoboReadingState> readingStates) { private void normalizePutTimestamps(List<KoboReadingState> readingStates) {
if (readingStates == null || readingStates.isEmpty()) { if (readingStates == null || readingStates.isEmpty()) {
return; return;
@@ -0,0 +1,234 @@
package org.booklore.service.kobo;
import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.kobo.KoboSpanPositionMap;
import org.booklore.util.SecureXmlUtils;
import org.jsoup.Jsoup;
import org.jsoup.parser.Parser;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static org.booklore.service.kobo.KoboEpubUtils.normalizeHref;
@Service
@Slf4j
public class KoboSpanMapExtractionService {
private static final String CONTAINER_PATH = "META-INF/container.xml";
private static final String CONTAINER_NS = "urn:oasis:names:tc:opendocument:xmlns:container";
private static final String OPF_NS = "http://www.idpf.org/2007/opf";
public KoboSpanPositionMap extractFromKepub(File kepubFile) throws IOException {
validateKepub(kepubFile);
try (ZipFile zipFile = new ZipFile(kepubFile)) {
String opfPath = readOpfPath(zipFile);
org.w3c.dom.Document opfDocument = parseXmlEntry(zipFile, opfPath);
String opfRootPath = opfPath.contains("/") ? opfPath.substring(0, opfPath.lastIndexOf('/') + 1) : "";
Map<String, ManifestItem> manifestById = parseManifest(opfDocument, opfRootPath);
List<ManifestItem> spineItems = parseSpine(opfDocument, manifestById);
List<ExtractedChapter> extractedChapters = new ArrayList<>();
for (int i = 0; i < spineItems.size(); i++) {
ExtractedChapter chapter = extractChapter(zipFile, spineItems.get(i), i);
if (chapter != null) {
extractedChapters.add(chapter);
}
}
if (extractedChapters.isEmpty()) {
return new KoboSpanPositionMap(List.of());
}
long totalContentLength = extractedChapters.stream()
.mapToLong(ExtractedChapter::contentLength)
.sum();
long accumulatedLength = 0L;
List<KoboSpanPositionMap.Chapter> chapters = new ArrayList<>(extractedChapters.size());
for (int i = 0; i < extractedChapters.size(); i++) {
ExtractedChapter chapter = extractedChapters.get(i);
float startProgress = accumulatedLength / (float) totalContentLength;
accumulatedLength += chapter.contentLength();
float endProgress = i == extractedChapters.size() - 1
? 1f
: accumulatedLength / (float) totalContentLength;
chapters.add(new KoboSpanPositionMap.Chapter(
chapter.sourceHref(),
normalizeHref(chapter.sourceHref()),
chapter.spineIndex(),
startProgress,
endProgress,
chapter.spans()));
}
return new KoboSpanPositionMap(chapters);
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException("Failed to extract Kobo span map from " + kepubFile.getName(), e);
}
}
private void validateKepub(File kepubFile) {
if (kepubFile == null || !kepubFile.isFile()) {
throw new IllegalArgumentException("Invalid KEPUB file: " + kepubFile);
}
}
private String readOpfPath(ZipFile zipFile) throws Exception {
org.w3c.dom.Document containerDocument = parseXmlEntry(zipFile, CONTAINER_PATH);
NodeList rootfiles = containerDocument.getElementsByTagNameNS(CONTAINER_NS, "rootfile");
if (rootfiles.getLength() == 0) {
rootfiles = containerDocument.getElementsByTagName("rootfile");
}
if (rootfiles.getLength() == 0) {
throw new IOException("No rootfile found in container.xml");
}
Element rootfile = (Element) rootfiles.item(0);
String fullPath = rootfile.getAttribute("full-path");
if (fullPath == null || fullPath.isEmpty()) {
throw new IOException("No full-path attribute found in container.xml");
}
return fullPath;
}
private org.w3c.dom.Document parseXmlEntry(ZipFile zipFile, String entryName) throws Exception {
ZipEntry zipEntry = findEntry(zipFile, entryName);
if (zipEntry == null) {
throw new IOException("Entry not found in archive: " + entryName);
}
try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
return SecureXmlUtils.createSecureDocumentBuilder(true).parse(inputStream);
}
}
private Map<String, ManifestItem> parseManifest(org.w3c.dom.Document opfDocument, String opfRootPath) {
Map<String, ManifestItem> manifestById = new HashMap<>();
NodeList items = opfDocument.getElementsByTagNameNS(OPF_NS, "item");
if (items.getLength() == 0) {
items = opfDocument.getElementsByTagName("item");
}
for (int i = 0; i < items.getLength(); i++) {
Element item = (Element) items.item(i);
String id = item.getAttribute("id");
String href = resolveHref(item.getAttribute("href"), opfRootPath);
if (id != null && !id.isBlank() && href != null && !href.isBlank()) {
manifestById.put(id, new ManifestItem(href));
}
}
return manifestById;
}
private List<ManifestItem> parseSpine(org.w3c.dom.Document opfDocument, Map<String, ManifestItem> manifestById) {
List<ManifestItem> spineItems = new ArrayList<>();
NodeList itemrefs = opfDocument.getElementsByTagNameNS(OPF_NS, "itemref");
if (itemrefs.getLength() == 0) {
itemrefs = opfDocument.getElementsByTagName("itemref");
}
for (int i = 0; i < itemrefs.getLength(); i++) {
Element itemref = (Element) itemrefs.item(i);
ManifestItem manifestItem = manifestById.get(itemref.getAttribute("idref"));
if (manifestItem != null) {
spineItems.add(manifestItem);
}
}
return spineItems;
}
private ExtractedChapter extractChapter(ZipFile zipFile, ManifestItem manifestItem, int spineIndex) throws IOException {
ZipEntry zipEntry = findEntry(zipFile, manifestItem.href());
if (zipEntry == null || zipEntry.isDirectory()) {
log.debug("Skipping missing Kobo span chapter {}", manifestItem.href());
return null;
}
String html;
try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
html = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}
if (html.isBlank()) {
return new ExtractedChapter(zipEntry.getName(), spineIndex, 1, List.of());
}
org.jsoup.nodes.Document document = Jsoup.parse(html, "", Parser.htmlParser().setTrackPosition(true));
List<KoboSpanPositionMap.Span> spans = document.select("span.koboSpan[id]").stream()
.map(span -> {
if (span.id().isBlank() || span.sourceRange() == null) {
return null;
}
return new KoboSpanPositionMap.Span(
span.id(),
span.sourceRange().endPos() / (float) Math.max(html.length(), 1));
})
.filter(Objects::nonNull)
.toList();
return new ExtractedChapter(
zipEntry.getName(),
spineIndex,
Math.max(html.length(), 1),
spans);
}
private ZipEntry findEntry(ZipFile zipFile, String href) {
String normalizedHref = normalizeHref(href);
return zipFile.stream()
.filter(entry -> !entry.isDirectory())
.filter(entry -> {
String normalizedEntry = normalizeHref(entry.getName());
return normalizedEntry.equals(normalizedHref)
|| normalizedEntry.endsWith("/" + normalizedHref);
})
.min(Comparator.comparingInt(entry -> {
String normalizedEntry = normalizeHref(entry.getName());
return normalizedEntry.equals(normalizedHref) ? 0 : normalizedEntry.length();
}))
.orElse(null);
}
private String resolveHref(String href, String rootPath) {
if (href == null || href.isBlank()) {
return null;
}
String decodedHref = KoboEpubUtils.decodeHrefPath(href);
if (decodedHref.startsWith("/")) {
return decodedHref.substring(1);
}
if (rootPath == null || rootPath.isEmpty()) {
return decodedHref;
}
return Path.of(rootPath).resolve(decodedHref).normalize().toString().replace('\\', '/');
}
private record ManifestItem(String href) {
}
private record ExtractedChapter(String sourceHref,
int spineIndex,
int contentLength,
List<KoboSpanPositionMap.Span> spans) {
}
}
@@ -0,0 +1,94 @@
package org.booklore.service.kobo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.kobo.KoboSpanPositionMap;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.KoboSpanMapEntity;
import org.booklore.repository.KoboSpanMapRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.dao.DataIntegrityViolationException;
import java.io.File;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@Service
@RequiredArgsConstructor
@Slf4j
public class KoboSpanMapService {
private final KoboSpanMapRepository koboSpanMapRepository;
private final KoboSpanMapExtractionService koboSpanMapExtractionService;
@Transactional
public void computeAndStoreIfNeeded(BookFileEntity bookFile, File kepubFile) throws java.io.IOException {
if (bookFile == null || bookFile.getId() == null) {
return;
}
String currentHash = bookFile.getCurrentHash();
if (currentHash == null || currentHash.isBlank()) {
log.debug("Skipping Kobo span map creation for file {} because current hash is missing", bookFile.getId());
return;
}
Optional<KoboSpanMapEntity> existingMap = koboSpanMapRepository.findByBookFileId(bookFile.getId());
if (existingMap.filter(map -> currentHash.equals(map.getFileHash()) && map.getSpanMap() != null).isPresent()) {
return;
}
if (kepubFile == null || !kepubFile.isFile()) {
return;
}
KoboSpanPositionMap spanMap = koboSpanMapExtractionService.extractFromKepub(kepubFile);
KoboSpanMapEntity entity = existingMap.orElseGet(KoboSpanMapEntity::new);
entity.setBookFile(bookFile);
entity.setFileHash(currentHash);
entity.setSpanMap(spanMap);
if (entity.getCreatedAt() == null) {
entity.setCreatedAt(Instant.now());
}
try {
koboSpanMapRepository.save(entity);
} catch (DataIntegrityViolationException e) {
log.debug("Kobo span map already stored by a concurrent request for file {}", bookFile.getId());
}
}
@Transactional(readOnly = true)
public Map<Long, KoboSpanPositionMap> getValidMaps(Map<Long, BookFileEntity> bookFilesByFileId) {
if (bookFilesByFileId.isEmpty()) {
return Map.of();
}
Map<Long, KoboSpanPositionMap> result = new HashMap<>();
for (KoboSpanMapEntity entity : koboSpanMapRepository.findByBookFileIdIn(bookFilesByFileId.keySet())) {
Long fileId = entity.getBookFile().getId();
BookFileEntity bookFile = bookFilesByFileId.get(fileId);
if (bookFile != null && bookFile.getCurrentHash() != null
&& bookFile.getCurrentHash().equals(entity.getFileHash())
&& entity.getSpanMap() != null) {
result.put(fileId, entity.getSpanMap());
}
}
return result;
}
@Transactional(readOnly = true)
public Optional<KoboSpanPositionMap> getValidMap(BookFileEntity bookFile) {
if (bookFile == null || bookFile.getId() == null) {
return Optional.empty();
}
String currentHash = bookFile.getCurrentHash();
if (currentHash == null || currentHash.isBlank()) {
return Optional.empty();
}
return koboSpanMapRepository.findByBookFileId(bookFile.getId())
.filter(map -> currentHash.equals(map.getFileHash()))
.map(KoboSpanMapEntity::getSpanMap);
}
}
@@ -153,6 +153,7 @@ public class ReadingProgressService {
case EPUB, FB2, MOBI, AZW3 -> book.setEpubProgress(EpubProgress.builder() case EPUB, FB2, MOBI, AZW3 -> book.setEpubProgress(EpubProgress.builder()
.cfi(fileProgress.getPositionData()) .cfi(fileProgress.getPositionData())
.href(fileProgress.getPositionHref()) .href(fileProgress.getPositionHref())
.contentSourceProgressPercent(roundToOneDecimal(fileProgress.getContentSourceProgressPercent()))
.percentage(roundToOneDecimal(fileProgress.getProgressPercent())) .percentage(roundToOneDecimal(fileProgress.getProgressPercent()))
.ttsPositionCfi(fileProgress.getTtsPositionCfi()) .ttsPositionCfi(fileProgress.getTtsPositionCfi())
.build()); .build());
@@ -303,6 +304,7 @@ public class ReadingProgressService {
entity.setPositionHref(fileProgress.positionHref()); entity.setPositionHref(fileProgress.positionHref());
entity.setProgressPercent(fileProgress.progressPercent()); entity.setProgressPercent(fileProgress.progressPercent());
entity.setTtsPositionCfi(fileProgress.ttsPositionCfi()); entity.setTtsPositionCfi(fileProgress.ttsPositionCfi());
entity.setContentSourceProgressPercent(fileProgress.contentSourceProgressPercent());
entity.setLastReadTime(now); entity.setLastReadTime(now);
userBookFileProgressRepository.save(entity); userBookFileProgressRepository.save(entity);
@@ -317,6 +319,7 @@ public class ReadingProgressService {
entity.setUser(user); entity.setUser(user);
entity.setBookFile(bookFile); entity.setBookFile(bookFile);
entity.setLastReadTime(now); entity.setLastReadTime(now);
entity.setContentSourceProgressPercent(null);
switch (bookFile.getBookType()) { switch (bookFile.getBookType()) {
case PDF -> { case PDF -> {
@@ -9,17 +9,29 @@ import org.grimmory.epub4j.cfi.CfiConverter;
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;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.parser.Parser;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
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() {
@@ -30,9 +42,10 @@ public class EpubCfiService {
} }
public XPointerResult convertCfiToXPointer(File epubFile, String cfi) { public XPointerResult convertCfiToXPointer(File epubFile, String cfi) {
int spineIndex = CfiConverter.extractSpineIndex(cfi); String normalizedCfi = normalizeContentDocumentCfi(cfi);
int spineIndex = CfiConverter.extractSpineIndex(normalizedCfi);
CfiConverter converter = createConverter(epubFile, spineIndex); CfiConverter converter = createConverter(epubFile, spineIndex);
return converter.cfiToXPointer(cfi); return converter.cfiToXPointer(normalizedCfi);
} }
public XPointerResult convertCfiToXPointer(Path epubPath, String cfi) { public XPointerResult convertCfiToXPointer(Path epubPath, String cfi) {
@@ -74,11 +87,47 @@ public class EpubCfiService {
return convertCfiToProgressXPointer(epubPath.toFile(), cfi); return convertCfiToProgressXPointer(epubPath.toFile(), cfi);
} }
public Optional<CfiLocation> resolveCfiLocation(File epubFile, String cfi) {
if (cfi == null || cfi.isBlank()) {
return Optional.empty();
}
try {
String normalizedCfi = normalizeContentDocumentCfi(cfi);
int spineIndex = CfiConverter.extractSpineIndex(normalizedCfi);
String href = EpubContentReader.getSpineItemHref(epubFile, spineIndex);
if (href == null || href.isBlank()) {
return Optional.empty();
}
String html = EpubContentReader.getSpineItemContent(epubFile, spineIndex);
if (html.isBlank()) {
return Optional.empty();
}
XPointerResult xpointerResult = convertCfiToXPointer(epubFile, normalizedCfi);
Integer sourceOffset = resolveSourceOffset(getCachedDocument(epubFile, spineIndex), xpointerResult.getXpointer());
Float contentSourceProgressPercent = sourceOffset == null
? null
: clampPercent((sourceOffset / (float) Math.max(html.length(), 1)) * 100f);
return Optional.of(new CfiLocation(href, contentSourceProgressPercent));
} catch (Exception e) {
log.debug("Failed to resolve chapter position from CFI: {}", e.getMessage());
return Optional.empty();
}
}
public Optional<CfiLocation> resolveCfiLocation(Path epubPath, String cfi) {
return resolveCfiLocation(epubPath.toFile(), cfi);
}
public boolean validateCfi(File epubFile, String cfi) { public boolean validateCfi(File epubFile, String cfi) {
try { try {
int spineIndex = CfiConverter.extractSpineIndex(cfi); String normalizedCfi = normalizeContentDocumentCfi(cfi);
int spineIndex = CfiConverter.extractSpineIndex(normalizedCfi);
CfiConverter converter = createConverter(epubFile, spineIndex); CfiConverter converter = createConverter(epubFile, spineIndex);
return converter.validateCfi(cfi); return converter.validateCfi(normalizedCfi);
} catch (Exception e) { } catch (Exception e) {
log.debug("CFI validation failed: {}", e.getMessage()); log.debug("CFI validation failed: {}", e.getMessage());
return false; return false;
@@ -118,7 +167,7 @@ public class EpubCfiService {
return documentCache.get(cacheKey, key -> { return documentCache.get(cacheKey, key -> {
log.debug("Cache miss for epub spine: {} index {}", epubFile.getName(), spineIndex); log.debug("Cache miss for epub spine: {} index {}", epubFile.getName(), spineIndex);
String html = EpubContentReader.getSpineItemContent(epubFile, spineIndex); String html = EpubContentReader.getSpineItemContent(epubFile, spineIndex);
return Jsoup.parse(html); return Jsoup.parse(html, "", Parser.htmlParser().setTrackPosition(true));
}); });
} }
@@ -143,4 +192,120 @@ public class EpubCfiService {
public void clearCache() { public void clearCache() {
documentCache.invalidateAll(); documentCache.invalidateAll();
} }
private String normalizeContentDocumentCfi(String cfi) {
if (cfi == null) {
return null;
}
return cfi.replaceFirst("!/4(?=/)", "!");
}
private Integer resolveSourceOffset(Document document, String xpointer) {
if (xpointer == null || xpointer.isBlank()) {
return null;
}
Matcher pathMatcher = XPOINTER_BODY_PATTERN.matcher(xpointer);
if (!pathMatcher.matches()) {
throw new IllegalArgumentException("Invalid XPointer format: " + xpointer);
}
String remainingPath = pathMatcher.group(2);
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) {
return null;
}
if (textOffset != null) {
Integer textSourceOffset = resolveTextOffsetSourcePosition(element, textOffset);
if (textSourceOffset != null) {
return textSourceOffset;
}
}
return element.sourceRange() == null ? null : Math.max(element.sourceRange().startPos(), 0);
}
private Element resolveElementPath(Element root, String path) {
Element current = root;
if (path == null || path.isBlank()) {
return current;
}
for (String rawSegment : path.split("/")) {
if (rawSegment.isBlank()) {
continue;
}
Matcher segmentMatcher = XPOINTER_SEGMENT_PATTERN.matcher(rawSegment);
if (!segmentMatcher.matches()) {
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;
}
current = matchingChildren.get(index - 1);
}
return current;
}
private Integer resolveTextOffsetSourcePosition(Element element, int cfiOffset) {
List<TextNode> textNodes = new ArrayList<>();
collectTextNodes(element, textNodes);
int totalChars = 0;
for (TextNode textNode : textNodes) {
String nodeText = textNode.text();
int nodeLength = nodeText.length();
if (totalChars + nodeLength >= cfiOffset) {
if (textNode.sourceRange() == null) {
return null;
}
int offsetInNode = Math.max(cfiOffset - totalChars, 0);
int startPos = Math.max(textNode.sourceRange().startPos(), 0);
return startPos + offsetInNode;
}
totalChars += nodeLength;
}
return element.sourceRange() == null ? null : Math.max(element.sourceRange().startPos(), 0);
}
private void collectTextNodes(Element element, List<TextNode> textNodes) {
for (TextNode textNode : element.textNodes()) {
if (!textNode.text().isEmpty()) {
textNodes.add(textNode);
}
}
for (Element child : element.children()) {
collectTextNodes(child, textNodes);
}
}
private Float clampPercent(float percent) {
return Math.max(0f, Math.min(percent, 100f));
}
public record CfiLocation(String href, Float contentSourceProgressPercent) {
}
} }
@@ -0,0 +1,2 @@
ALTER TABLE user_book_file_progress
ADD COLUMN IF NOT EXISTS content_source_progress_percent FLOAT NULL;
@@ -0,0 +1,14 @@
CREATE TABLE kobo_span_map
(
id BIGINT AUTO_INCREMENT NOT NULL,
book_file_id BIGINT NOT NULL,
file_hash VARCHAR(128) NOT NULL,
span_map_json LONGTEXT NOT NULL,
created_at datetime NOT NULL,
CONSTRAINT pk_kobo_span_map PRIMARY KEY (id),
CONSTRAINT uk_kobo_span_map_book_file UNIQUE (book_file_id)
);
ALTER TABLE kobo_span_map
ADD CONSTRAINT fk_kobo_span_map_book_file
FOREIGN KEY (book_file_id) REFERENCES book_file (id) ON DELETE CASCADE;
@@ -73,7 +73,7 @@ class AppBookServiceProgressTest {
mockBookWithLibrary(bookId, libraryId); mockBookWithLibrary(bookId, libraryId);
UpdateProgressRequest request = new UpdateProgressRequest(); UpdateProgressRequest request = new UpdateProgressRequest();
request.setFileProgress(new BookFileProgress(1L, "pos", "href", 0.5f, null)); request.setFileProgress(new BookFileProgress(1L, "pos", "href", 0.5f, null, null));
service.updateBookProgress(bookId, request); service.updateBookProgress(bookId, request);
@@ -92,7 +92,7 @@ class AppBookServiceProgressTest {
mockBookWithLibrary(bookId, libraryId); mockBookWithLibrary(bookId, libraryId);
UpdateProgressRequest request = new UpdateProgressRequest(); UpdateProgressRequest request = new UpdateProgressRequest();
request.setFileProgress(new BookFileProgress(1L, null, null, 0.75f, null)); request.setFileProgress(new BookFileProgress(1L, null, null, 0.75f, null, null));
service.updateBookProgress(bookId, request); service.updateBookProgress(bookId, request);
@@ -118,7 +118,7 @@ class AppBookServiceProgressTest {
mockBookWithLibrary(bookId, libraryId); mockBookWithLibrary(bookId, libraryId);
UpdateProgressRequest request = new UpdateProgressRequest(); UpdateProgressRequest request = new UpdateProgressRequest();
request.setFileProgress(new BookFileProgress(1L, null, null, 0.5f, null)); request.setFileProgress(new BookFileProgress(1L, null, null, 0.5f, null, null));
assertThrows(APIException.class, () -> service.updateBookProgress(bookId, request)); assertThrows(APIException.class, () -> service.updateBookProgress(bookId, request));
verify(bookService, never()).updateReadProgress(any()); verify(bookService, never()).updateReadProgress(any());
@@ -130,7 +130,7 @@ class AppBookServiceProgressTest {
mockBookWithLibrary(bookId, libraryId); mockBookWithLibrary(bookId, libraryId);
UpdateProgressRequest request = new UpdateProgressRequest(); UpdateProgressRequest request = new UpdateProgressRequest();
request.setFileProgress(new BookFileProgress(1L, null, null, 0.5f, null)); request.setFileProgress(new BookFileProgress(1L, null, null, 0.5f, null, null));
service.updateBookProgress(bookId, request); service.updateBookProgress(bookId, request);
@@ -147,7 +147,7 @@ class AppBookServiceProgressTest {
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.empty()); when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.empty());
UpdateProgressRequest request = new UpdateProgressRequest(); UpdateProgressRequest request = new UpdateProgressRequest();
request.setFileProgress(new BookFileProgress(1L, null, null, 0.5f, null)); request.setFileProgress(new BookFileProgress(1L, null, null, 0.5f, null, null));
assertThrows(APIException.class, () -> service.updateBookProgress(bookId, request)); assertThrows(APIException.class, () -> service.updateBookProgress(bookId, request));
verify(bookService, never()).updateReadProgress(any()); verify(bookService, never()).updateReadProgress(any());
@@ -25,14 +25,17 @@ import org.booklore.mapper.KoboReadingStateMapper;
import org.booklore.model.dto.KoboSyncSettings; import org.booklore.model.dto.KoboSyncSettings;
import org.booklore.model.dto.kobo.*; import org.booklore.model.dto.kobo.*;
import org.booklore.model.entity.KoboReadingStateEntity; import org.booklore.model.entity.KoboReadingStateEntity;
import org.booklore.model.entity.UserBookFileProgressEntity;
import org.booklore.model.entity.UserBookProgressEntity; import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.KoboReadStatus; import org.booklore.model.enums.KoboReadStatus;
import org.booklore.model.enums.ReadStatus; import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.KoboReadingStateRepository; import org.booklore.repository.KoboReadingStateRepository;
import org.booklore.repository.UserBookFileProgressRepository;
import org.booklore.repository.UserBookProgressRepository; import org.booklore.repository.UserBookProgressRepository;
import org.booklore.service.kobo.KoboEntitlementService; import org.booklore.service.kobo.KoboEntitlementService;
import org.booklore.service.kobo.KoboReadingStateBuilder; import org.booklore.service.kobo.KoboReadingStateBuilder;
import org.booklore.service.kobo.KoboSettingsService; import org.booklore.service.kobo.KoboSettingsService;
import org.booklore.service.kobo.KoboSpanMapService;
import org.booklore.service.opds.MagicShelfBookService; import org.booklore.service.opds.MagicShelfBookService;
import org.booklore.util.kobo.KoboUrlBuilder; import org.booklore.util.kobo.KoboUrlBuilder;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@@ -55,6 +58,7 @@ import java.time.ZoneOffset;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@@ -93,6 +97,9 @@ class KoboEntitlementServiceTest {
@Mock @Mock
private UserBookProgressRepository progressRepository; private UserBookProgressRepository progressRepository;
@Mock
private UserBookFileProgressRepository fileProgressRepository;
@Mock @Mock
private KoboReadingStateRepository readingStateRepository; private KoboReadingStateRepository readingStateRepository;
@@ -105,6 +112,9 @@ class KoboEntitlementServiceTest {
@Mock @Mock
private KoboSettingsService koboSettingsService; private KoboSettingsService koboSettingsService;
@Mock
private KoboSpanMapService koboSpanMapService;
@InjectMocks @InjectMocks
private KoboEntitlementService koboEntitlementService; private KoboEntitlementService koboEntitlementService;
@@ -113,7 +123,9 @@ class KoboEntitlementServiceTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions(); BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
user = BookLoreUser.builder().permissions(permissions).build(); user = BookLoreUser.builder().id(1L).permissions(permissions).build();
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(koboSpanMapService.getValidMaps(anyMap())).thenReturn(Map.of());
} }
@Test @Test
@@ -180,6 +192,28 @@ class KoboEntitlementServiceTest {
assertEquals(KoboBookFormat.EPUB3.toString(), result.getDownloadUrls().getFirst().getFormat()); assertEquals(KoboBookFormat.EPUB3.toString(), result.getDownloadUrls().getFirst().getFormat());
} }
@Test
void mapToKoboMetadata_epubBookShouldReturnKepubFormatEvenWhenToggleIsOff() {
long bookId = 1L;
BookEntity epubBook = createEpubBookEntity(bookId);
String token = "test-token";
when(bookQueryService.findAllWithMetadataByIds(Set.of(bookId)))
.thenReturn(List.of(epubBook));
when(koboCompatibilityService.isBookSupportedForKobo(epubBook))
.thenReturn(true);
when(koboUrlBuilder.downloadUrl(token, epubBook.getId()))
.thenReturn("http://test.com/download/" + epubBook.getId());
when(appSettingService.getAppSettings())
.thenReturn(createAppSettingsWithKoboSettings());
KoboBookMetadata result = koboEntitlementService.getMetadataForBook(bookId, token);
assertNotNull(result);
assertEquals(1, result.getDownloadUrls().size());
assertEquals(KoboBookFormat.KEPUB.toString(), result.getDownloadUrls().getFirst().getFormat());
}
private BookEntity createCbxBookEntity(Long id) { private BookEntity createCbxBookEntity(Long id) {
BookEntity book = new BookEntity(); BookEntity book = new BookEntity();
book.setId(id); book.setId(id);
@@ -204,7 +238,6 @@ class KoboEntitlementServiceTest {
KoboSettings koboSettings = KoboSettings.builder() KoboSettings koboSettings = KoboSettings.builder()
.convertCbxToEpub(true) .convertCbxToEpub(true)
.conversionLimitInMbForCbx(50) .conversionLimitInMbForCbx(50)
.convertToKepub(false)
.conversionLimitInMb(50) .conversionLimitInMb(50)
.build(); .build();
appSettings.setKoboSettings(koboSettings); appSettings.setKoboSettings(koboSettings);
@@ -506,6 +539,127 @@ class KoboEntitlementServiceTest {
assertTrue(result.isEmpty()); assertTrue(result.isEmpty());
} }
@Test
@DisplayName("Should prefer href-only web reader bookmark over existing state when two-way sync is on")
void generateNewEntitlements_prefersHrefOnlyWebReaderBookmark() {
BookEntity book = createEpubBookEntity(1L);
book.setAddedOn(Instant.parse("2025-01-01T00:00:00Z"));
book.getPrimaryBookFile().setId(10L);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(book);
progress.setEpubProgressHref("OPS/chapter3.xhtml");
progress.setEpubProgressPercent(54.6f);
KoboReadingState.CurrentBookmark existingBookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(12)
.build();
KoboReadingState existingState = KoboReadingState.builder()
.entitlementId("1")
.currentBookmark(existingBookmark)
.build();
KoboReadingStateEntity existingEntity = new KoboReadingStateEntity();
KoboReadingState.CurrentBookmark webReaderBookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(55)
.build();
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
when(koboCompatibilityService.isBookSupportedForKobo(book)).thenReturn(true);
when(koboUrlBuilder.downloadUrl("token1", 1L)).thenReturn("http://test.com/download/1");
when(appSettingService.getAppSettings()).thenReturn(createAppSettingsWithKoboSettings());
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
when(progressRepository.findByUserIdAndBookId(user.getId(), 1L)).thenReturn(Optional.of(progress));
when(fileProgressRepository.findByUserIdAndBookFileId(user.getId(), 10L)).thenReturn(Optional.empty());
when(readingStateRepository.findByEntitlementIdAndUserId("1", user.getId()))
.thenReturn(Optional.of(existingEntity));
when(readingStateMapper.toDto(existingEntity)).thenReturn(existingState);
when(readingStateBuilder.shouldUseWebReaderProgress(progress)).thenReturn(true);
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), isNull(), any(OffsetDateTime.class)))
.thenReturn(webReaderBookmark);
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
.thenReturn(KoboReadingState.StatusInfo.builder()
.status(KoboReadStatus.READING)
.timesStartedReading(1)
.build());
List<NewEntitlement> result = koboEntitlementService.generateNewEntitlements(Set.of(1L), "token1");
assertEquals(1, result.size());
assertEquals(55, result.getFirst().getNewEntitlement().getReadingState().getCurrentBookmark().getProgressPercent());
verify(readingStateBuilder).buildBookmarkFromProgress(eq(progress), isNull(), any(OffsetDateTime.class));
}
@Test
@DisplayName("Should keep stored Kobo bookmark when mirrored EPUB progress is not newer")
void generateNewEntitlements_preservesStoredKoboBookmarkWhenKoboIsFreshest() {
BookEntity book = createEpubBookEntity(1L);
book.setAddedOn(Instant.parse("2025-01-01T00:00:00Z"));
book.getPrimaryBookFile().setId(10L);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(book);
progress.setKoboProgressPercent(55f);
progress.setKoboLocation("kobo.12.18");
progress.setKoboLocationType("KoboSpan");
progress.setKoboLocationSource("OPS/chapter3.xhtml");
progress.setKoboProgressReceivedTime(Instant.parse("2025-06-15T12:00:00Z"));
progress.setEpubProgressPercent(55f);
progress.setLastReadTime(Instant.parse("2025-06-15T12:00:00Z"));
progress.setReadStatus(ReadStatus.READING);
KoboReadingState.CurrentBookmark existingBookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(55)
.contentSourceProgressPercent(23)
.location(KoboReadingState.CurrentBookmark.Location.builder()
.value("kobo.12.18")
.type("KoboSpan")
.source("OPS/chapter3.xhtml")
.build())
.lastModified("2025-06-15T12:00:00Z")
.build();
KoboReadingState existingState = KoboReadingState.builder()
.entitlementId("1")
.currentBookmark(existingBookmark)
.build();
KoboReadingStateEntity existingEntity = new KoboReadingStateEntity();
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
when(koboCompatibilityService.isBookSupportedForKobo(book)).thenReturn(true);
when(koboUrlBuilder.downloadUrl("token1", 1L)).thenReturn("http://test.com/download/1");
when(appSettingService.getAppSettings()).thenReturn(createAppSettingsWithKoboSettings());
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
when(progressRepository.findByUserIdAndBookId(user.getId(), 1L)).thenReturn(Optional.of(progress));
when(fileProgressRepository.findByUserIdAndBookFileId(user.getId(), 10L)).thenReturn(Optional.empty());
when(readingStateRepository.findByEntitlementIdAndUserId("1", user.getId()))
.thenReturn(Optional.of(existingEntity));
when(readingStateMapper.toDto(existingEntity)).thenReturn(existingState);
when(readingStateBuilder.shouldUseWebReaderProgress(progress)).thenReturn(false);
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
.thenReturn(KoboReadingState.StatusInfo.builder()
.status(KoboReadStatus.READING)
.timesStartedReading(1)
.build());
List<NewEntitlement> result = koboEntitlementService.generateNewEntitlements(Set.of(1L), "token1");
assertEquals(1, result.size());
KoboReadingState.CurrentBookmark bookmark = result.getFirst().getNewEntitlement().getReadingState().getCurrentBookmark();
assertEquals(55, bookmark.getProgressPercent());
assertEquals(23, bookmark.getContentSourceProgressPercent());
assertNotNull(bookmark.getLocation());
assertEquals("kobo.12.18", bookmark.getLocation().getValue());
assertEquals("OPS/chapter3.xhtml", bookmark.getLocation().getSource());
verify(readingStateBuilder).shouldUseWebReaderProgress(progress);
verify(readingStateBuilder, never()).buildBookmarkFromProgress(eq(progress), isNull(), any(OffsetDateTime.class));
}
@Test @Test
@DisplayName("Should handle empty book IDs") @DisplayName("Should handle empty book IDs")
void generateNewEntitlements_emptyIds() { void generateNewEntitlements_emptyIds() {
@@ -563,6 +717,11 @@ class KoboEntitlementServiceTest {
void generateChangedReadingStates_fromProgress() { void generateChangedReadingStates_fromProgress() {
BookEntity book = new BookEntity(); BookEntity book = new BookEntity();
book.setId(1L); book.setId(1L);
BookFileEntity primaryFile = new BookFileEntity();
primaryFile.setId(10L);
primaryFile.setBook(book);
primaryFile.setBookType(BookFileType.EPUB);
book.setBookFiles(List.of(primaryFile));
UserBookProgressEntity progress = new UserBookProgressEntity(); UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(book); progress.setBook(book);
@@ -570,12 +729,19 @@ class KoboEntitlementServiceTest {
progress.setReadStatus(ReadStatus.READING); progress.setReadStatus(ReadStatus.READING);
KoboSyncSettings settings = new KoboSyncSettings(); KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings); when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setBookFile(primaryFile);
fileProgress.setContentSourceProgressPercent(20f);
when(fileProgressRepository.findByUserIdAndBookFileIdIn(eq(1L), any())).thenReturn(List.of(fileProgress));
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder() KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(50) .progressPercent(50)
.contentSourceProgressPercent(20)
.build(); .build();
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), any(OffsetDateTime.class))) when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), eq(fileProgress), any(OffsetDateTime.class), anyMap()))
.thenReturn(bookmark); .thenReturn(bookmark);
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString())) when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
.thenReturn(KoboReadingState.StatusInfo.builder() .thenReturn(KoboReadingState.StatusInfo.builder()
@@ -590,9 +756,68 @@ class KoboEntitlementServiceTest {
KoboReadingState state = result.getFirst().getChangedReadingState().getReadingState(); KoboReadingState state = result.getFirst().getChangedReadingState().getReadingState();
assertEquals("1", state.getEntitlementId()); assertEquals("1", state.getEntitlementId());
assertNotNull(state.getCurrentBookmark()); assertNotNull(state.getCurrentBookmark());
assertEquals(20, state.getCurrentBookmark().getContentSourceProgressPercent());
assertNotNull(state.getStatusInfo()); assertNotNull(state.getStatusInfo());
} }
@Test
@DisplayName("Should use synced EPUB file progress when book has multiple files")
void generateChangedReadingStates_usesSyncedEpubFileProgress() {
BookEntity book = new BookEntity();
book.setId(1L);
BookFileEntity primaryEpub = new BookFileEntity();
primaryEpub.setId(10L);
primaryEpub.setBook(book);
primaryEpub.setBookType(BookFileType.EPUB);
BookFileEntity alternateAudiobook = new BookFileEntity();
alternateAudiobook.setId(20L);
alternateAudiobook.setBook(book);
alternateAudiobook.setBookType(BookFileType.AUDIOBOOK);
book.setBookFiles(List.of(primaryEpub, alternateAudiobook));
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(book);
progress.setEpubProgressPercent(70f);
progress.setReadStatus(ReadStatus.READING);
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
UserBookFileProgressEntity epubFileProgress = new UserBookFileProgressEntity();
epubFileProgress.setBookFile(primaryEpub);
epubFileProgress.setContentSourceProgressPercent(21f);
UserBookFileProgressEntity audiobookProgress = new UserBookFileProgressEntity();
audiobookProgress.setBookFile(alternateAudiobook);
audiobookProgress.setContentSourceProgressPercent(99f);
when(fileProgressRepository.findByUserIdAndBookFileIdIn(eq(1L), any()))
.thenReturn(List.of(epubFileProgress, audiobookProgress));
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(70)
.contentSourceProgressPercent(21)
.build();
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), eq(epubFileProgress), any(OffsetDateTime.class), anyMap()))
.thenReturn(bookmark);
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
.thenReturn(KoboReadingState.StatusInfo.builder()
.status(KoboReadStatus.READING)
.timesStartedReading(1)
.build());
List<ChangedReadingState> result = koboEntitlementService.generateChangedReadingStates(List.of(progress));
assertEquals(1, result.size());
assertEquals(21, result.getFirst().getChangedReadingState().getReadingState()
.getCurrentBookmark().getContentSourceProgressPercent());
verify(readingStateBuilder).buildBookmarkFromProgress(eq(progress), eq(epubFileProgress), any(OffsetDateTime.class), anyMap());
}
@Test @Test
@DisplayName("Should use empty bookmark when no progress data exists") @DisplayName("Should use empty bookmark when no progress data exists")
void generateChangedReadingStates_emptyBookmark() { void generateChangedReadingStates_emptyBookmark() {
@@ -637,7 +862,7 @@ class KoboEntitlementServiceTest {
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder() KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(70) .progressPercent(70)
.build(); .build();
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), any(OffsetDateTime.class))) when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), isNull(), any(OffsetDateTime.class), anyMap()))
.thenReturn(bookmark); .thenReturn(bookmark);
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString())) when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
.thenReturn(KoboReadingState.StatusInfo.builder() .thenReturn(KoboReadingState.StatusInfo.builder()
@@ -682,4 +907,4 @@ class KoboEntitlementServiceTest {
verify(readingStateBuilder).buildEmptyBookmark(any(OffsetDateTime.class)); verify(readingStateBuilder).buildEmptyBookmark(any(OffsetDateTime.class));
} }
} }
} }
@@ -3,9 +3,11 @@ package org.booklore.service;
import org.booklore.model.dto.KoboSyncSettings; import org.booklore.model.dto.KoboSyncSettings;
import org.booklore.model.dto.kobo.KoboReadingState; import org.booklore.model.dto.kobo.KoboReadingState;
import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.UserBookFileProgressEntity;
import org.booklore.model.entity.UserBookProgressEntity; import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.KoboReadStatus; import org.booklore.model.enums.KoboReadStatus;
import org.booklore.model.enums.ReadStatus; import org.booklore.model.enums.ReadStatus;
import org.booklore.service.kobo.KoboBookmarkLocationResolver;
import org.booklore.service.kobo.KoboReadingStateBuilder; import org.booklore.service.kobo.KoboReadingStateBuilder;
import org.booklore.service.kobo.KoboSettingsService; import org.booklore.service.kobo.KoboSettingsService;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@@ -27,6 +29,7 @@ import java.time.ZoneOffset;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@DisplayName("KoboReadingStateBuilder Tests") @DisplayName("KoboReadingStateBuilder Tests")
@@ -37,6 +40,9 @@ class KoboReadingStateBuilderTest {
@Mock @Mock
private KoboSettingsService koboSettingsService; private KoboSettingsService koboSettingsService;
@Mock
private KoboBookmarkLocationResolver bookmarkLocationResolver;
private KoboReadingStateBuilder builder; private KoboReadingStateBuilder builder;
@BeforeEach @BeforeEach
@@ -44,7 +50,8 @@ class KoboReadingStateBuilderTest {
KoboSyncSettings settings = new KoboSyncSettings(); KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true); settings.setTwoWayProgressSync(true);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings); when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
builder = new KoboReadingStateBuilder(koboSettingsService); when(bookmarkLocationResolver.resolve(any(), any(), any())).thenReturn(java.util.Optional.empty());
builder = new KoboReadingStateBuilder(koboSettingsService, bookmarkLocationResolver);
} }
@Nested @Nested
@@ -186,19 +193,19 @@ class KoboReadingStateBuilderTest {
void buildBookmarkFromProgress_WithLocation() { void buildBookmarkFromProgress_WithLocation() {
UserBookProgressEntity progress = new UserBookProgressEntity(); UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setKoboProgressPercent(75.5f); progress.setKoboProgressPercent(75.5f);
progress.setKoboLocation("epubcfi(/6/4[chap01ref]!/4/2/1:3)"); progress.setKoboLocation("kobo.12.18");
progress.setKoboLocationType("EpubCfi"); progress.setKoboLocationType("KoboSpan");
progress.setKoboLocationSource("Kobo"); progress.setKoboLocationSource("OEBPS/chapter3.xhtml");
progress.setKoboProgressReceivedTime(Instant.parse("2025-11-26T10:00:00Z")); progress.setKoboProgressReceivedTime(Instant.parse("2025-11-26T10:00:00Z"));
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress); KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, (UserBookFileProgressEntity) null);
assertNotNull(bookmark); assertNotNull(bookmark);
assertEquals(76, bookmark.getProgressPercent()); // Rounded assertEquals(76, bookmark.getProgressPercent()); // Rounded
assertNotNull(bookmark.getLocation()); assertNotNull(bookmark.getLocation());
assertEquals("epubcfi(/6/4[chap01ref]!/4/2/1:3)", bookmark.getLocation().getValue()); assertEquals("kobo.12.18", bookmark.getLocation().getValue());
assertEquals("EpubCfi", bookmark.getLocation().getType()); assertEquals("KoboSpan", bookmark.getLocation().getType());
assertEquals("Kobo", bookmark.getLocation().getSource()); assertEquals("OEBPS/chapter3.xhtml", bookmark.getLocation().getSource());
} }
@Test @Test
@@ -209,13 +216,161 @@ class KoboReadingStateBuilderTest {
progress.setKoboLocation(null); progress.setKoboLocation(null);
progress.setKoboProgressReceivedTime(Instant.now()); progress.setKoboProgressReceivedTime(Instant.now());
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress); KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, (UserBookFileProgressEntity) null);
assertNotNull(bookmark); assertNotNull(bookmark);
assertEquals(50, bookmark.getProgressPercent()); assertEquals(50, bookmark.getProgressPercent());
assertNull(bookmark.getLocation()); assertNull(bookmark.getLocation());
} }
@Test
@DisplayName("Should carry file content progress into Kobo bookmark")
void buildBookmarkFromProgress_KoboBookmarkReusesFileContentProgress() {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setKoboProgressPercent(44f);
progress.setKoboProgressReceivedTime(Instant.parse("2025-11-26T10:00:00Z"));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setContentSourceProgressPercent(18.6f);
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, fileProgress);
assertNotNull(bookmark);
assertEquals(44, bookmark.getProgressPercent());
assertEquals(19, bookmark.getContentSourceProgressPercent());
}
@Test
@DisplayName("Should build web reader bookmark without a fallback location when no KoboSpan resolves")
void buildBookmarkFromProgress_WebReaderLocation() {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgress("epubcfi(/6/4!/4/2/6/1:1)");
progress.setEpubProgressHref("OPS/chapter1.xhtml");
progress.setEpubProgressPercent(54.6f);
progress.setLastReadTime(Instant.parse("2025-11-26T10:00:00Z"));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setPositionData("epubcfi(/6/8!/4/2/6/1:15)");
fileProgress.setPositionHref("OPS/chapter3.xhtml");
fileProgress.setContentSourceProgressPercent(18.6f);
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, fileProgress);
assertNotNull(bookmark);
assertEquals(55, bookmark.getProgressPercent());
assertEquals(19, bookmark.getContentSourceProgressPercent());
assertNull(bookmark.getLocation());
}
@Test
@DisplayName("Should build web reader bookmark with resolved KoboSpan location")
void buildBookmarkFromProgress_WebReaderResolvedKoboSpanLocation() {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgress("epubcfi(/6/4!/4/2/6/1:1)");
progress.setEpubProgressHref("OPS/chapter3.xhtml");
progress.setEpubProgressPercent(54.6f);
progress.setLastReadTime(Instant.parse("2025-11-26T10:00:00Z"));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setPositionData("epubcfi(/6/8!/4/2/6/1:15)");
fileProgress.setPositionHref("OPS/chapter3.xhtml");
when(bookmarkLocationResolver.resolve(progress, fileProgress, null))
.thenReturn(java.util.Optional.of(
new KoboBookmarkLocationResolver.ResolvedBookmarkLocation(
"kobo.12.18",
"KoboSpan",
"OEBPS/OPS/chapter3.xhtml",
18.6f)));
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, fileProgress);
assertNotNull(bookmark);
assertEquals(55, bookmark.getProgressPercent());
assertEquals(19, bookmark.getContentSourceProgressPercent());
assertNotNull(bookmark.getLocation());
assertEquals("kobo.12.18", bookmark.getLocation().getValue());
assertEquals("KoboSpan", bookmark.getLocation().getType());
assertEquals("OEBPS/OPS/chapter3.xhtml", bookmark.getLocation().getSource());
}
@Test
@DisplayName("Should prefer web reader bookmark when Kobo bookmark timestamp is older")
void buildBookmarkFromProgress_PrefersWebReaderWhenKoboTimestampIsOlder() {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgress("epubcfi(/6/4!/4/2/6/1:1)");
progress.setEpubProgressHref("OPS/chapter3.xhtml");
progress.setEpubProgressPercent(54.6f);
progress.setLastReadTime(Instant.parse("2025-11-26T10:00:00Z"));
progress.setKoboProgressPercent(12f);
progress.setKoboLocation("kobo.1.1");
progress.setKoboLocationType("KoboSpan");
progress.setKoboLocationSource("OPS/chapter1.xhtml");
progress.setKoboProgressReceivedTime(Instant.parse("2025-11-26T09:00:00Z"));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setPositionData("epubcfi(/6/8!/4/2/6/1:15)");
fileProgress.setPositionHref("OPS/chapter3.xhtml");
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, fileProgress);
assertNotNull(bookmark);
assertEquals(55, bookmark.getProgressPercent());
assertNull(bookmark.getLocation());
}
@Test
@DisplayName("Should keep inbound Kobo bookmark when mirrored EPUB progress has the same timestamp")
void buildBookmarkFromProgress_PrefersKoboWhenTimestampsAreEqual() {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgressPercent(54.6f);
progress.setLastReadTime(Instant.parse("2025-11-26T10:00:00Z"));
progress.setKoboProgressPercent(12f);
progress.setKoboLocation("kobo.1.1");
progress.setKoboLocationType("KoboSpan");
progress.setKoboLocationSource("OPS/chapter1.xhtml");
progress.setKoboProgressReceivedTime(Instant.parse("2025-11-26T10:00:00Z"));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setPositionHref("OPS/chapter3.xhtml");
fileProgress.setContentSourceProgressPercent(18.6f);
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, fileProgress);
assertNotNull(bookmark);
assertEquals(12, bookmark.getProgressPercent());
assertEquals(19, bookmark.getContentSourceProgressPercent());
assertNotNull(bookmark.getLocation());
assertEquals("kobo.1.1", bookmark.getLocation().getValue());
assertEquals("KoboSpan", bookmark.getLocation().getType());
assertEquals("OPS/chapter1.xhtml", bookmark.getLocation().getSource());
}
@Test
@DisplayName("Should prefer web reader bookmark when newer progress has href and percent but no CFI")
void buildBookmarkFromProgress_UsesWebReaderWithoutCfi() {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgressHref("OPS/chapter3.xhtml");
progress.setEpubProgressPercent(54.6f);
progress.setLastReadTime(Instant.parse("2025-11-26T10:00:00Z"));
progress.setKoboProgressPercent(12f);
progress.setKoboLocation("kobo.1.1");
progress.setKoboLocationType("KoboSpan");
progress.setKoboLocationSource("OPS/chapter1.xhtml");
progress.setKoboProgressReceivedTime(Instant.parse("2025-11-26T09:00:00Z"));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setPositionHref("OPS/chapter3.xhtml");
fileProgress.setContentSourceProgressPercent(18.6f);
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, fileProgress);
assertNotNull(bookmark);
assertEquals(55, bookmark.getProgressPercent());
assertEquals(19, bookmark.getContentSourceProgressPercent());
assertNull(bookmark.getLocation());
}
@Test @Test
@DisplayName("Should use default time when progress received time is null") @DisplayName("Should use default time when progress received time is null")
void buildBookmarkFromProgress_UseDefaultTime() { void buildBookmarkFromProgress_UseDefaultTime() {
@@ -224,7 +379,7 @@ class KoboReadingStateBuilderTest {
progress.setKoboProgressReceivedTime(null); progress.setKoboProgressReceivedTime(null);
OffsetDateTime defaultTime = OffsetDateTime.parse("2025-11-26T12:00:00Z"); OffsetDateTime defaultTime = OffsetDateTime.parse("2025-11-26T12:00:00Z");
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, defaultTime); KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, null, defaultTime);
assertNotNull(bookmark); assertNotNull(bookmark);
assertEquals(defaultTime.toString(), bookmark.getLastModified()); assertEquals(defaultTime.toString(), bookmark.getLastModified());
@@ -237,7 +392,7 @@ class KoboReadingStateBuilderTest {
progress.setKoboProgressPercent(33.7f); progress.setKoboProgressPercent(33.7f);
progress.setKoboProgressReceivedTime(Instant.now()); progress.setKoboProgressReceivedTime(Instant.now());
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress); KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, (UserBookFileProgressEntity) null);
assertEquals(34, bookmark.getProgressPercent()); // Rounded up assertEquals(34, bookmark.getProgressPercent()); // Rounded up
} }
@@ -256,13 +411,13 @@ class KoboReadingStateBuilderTest {
UserBookProgressEntity progress = new UserBookProgressEntity(); UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(book); progress.setBook(book);
progress.setKoboProgressPercent(75f); progress.setKoboProgressPercent(75f);
progress.setKoboLocation("epubcfi(/6/4!)"); progress.setKoboLocation("kobo.1.1");
progress.setKoboLocationType("EpubCfi"); progress.setKoboLocationType("KoboSpan");
progress.setKoboLocationSource("Kobo"); progress.setKoboLocationSource("OEBPS/CoverImage.xhtml");
progress.setKoboProgressReceivedTime(Instant.parse("2025-11-26T10:00:00Z")); progress.setKoboProgressReceivedTime(Instant.parse("2025-11-26T10:00:00Z"));
progress.setReadStatus(ReadStatus.READING); progress.setReadStatus(ReadStatus.READING);
KoboReadingState state = builder.buildReadingStateFromProgress("100", progress); KoboReadingState state = builder.buildReadingStateFromProgress("100", progress, null);
assertNotNull(state); assertNotNull(state);
assertEquals("100", state.getEntitlementId()); assertEquals("100", state.getEntitlementId());
@@ -9,6 +9,7 @@ import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookLoreUserEntity; import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.KoboReadingStateEntity; import org.booklore.model.entity.KoboReadingStateEntity;
import org.booklore.model.entity.UserBookProgressEntity; import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.KoboReadStatus; import org.booklore.model.enums.KoboReadStatus;
import org.booklore.model.enums.ReadStatus; import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.BookRepository; import org.booklore.repository.BookRepository;
@@ -112,6 +113,15 @@ class KoboReadingStateServiceTest {
lenient().when(mapper.cleanString(any())).thenCallRealMethod(); lenient().when(mapper.cleanString(any())).thenCallRealMethod();
} }
private BookFileEntity setPrimaryEpub(Long bookFileId) {
BookFileEntity primaryFile = new BookFileEntity();
primaryFile.setId(bookFileId);
primaryFile.setBook(testBook);
primaryFile.setBookType(BookFileType.EPUB);
testBook.setBookFiles(List.of(primaryFile));
return primaryFile;
}
@Test @Test
@DisplayName("Should not overwrite existing finished date when syncing completed book") @DisplayName("Should not overwrite existing finished date when syncing completed book")
void testSyncKoboProgressToUserBookProgress_PreserveExistingFinishedDate() { void testSyncKoboProgressToUserBookProgress_PreserveExistingFinishedDate() {
@@ -248,9 +258,9 @@ class KoboReadingStateServiceTest {
String entitlementId = "100"; String entitlementId = "100";
UserBookProgressEntity progress = new UserBookProgressEntity(); UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setKoboProgressPercent(75.5f); progress.setKoboProgressPercent(75.5f);
progress.setKoboLocation("epubcfi(/6/4[chap01ref]!/4/2/1:3)"); progress.setKoboLocation("kobo.12.18");
progress.setKoboLocationType("EpubCfi"); progress.setKoboLocationType("KoboSpan");
progress.setKoboLocationSource("Kobo"); progress.setKoboLocationSource("OEBPS/chapter3.xhtml");
progress.setKoboProgressReceivedTime(Instant.now()); progress.setKoboProgressReceivedTime(Instant.now());
KoboReadingState expectedState = KoboReadingState.builder() KoboReadingState expectedState = KoboReadingState.builder()
@@ -258,9 +268,9 @@ class KoboReadingStateServiceTest {
.currentBookmark(KoboReadingState.CurrentBookmark.builder() .currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(75) .progressPercent(75)
.location(KoboReadingState.CurrentBookmark.Location.builder() .location(KoboReadingState.CurrentBookmark.Location.builder()
.value("epubcfi(/6/4[chap01ref]!/4/2/1:3)") .value("kobo.12.18")
.type("EpubCfi") .type("KoboSpan")
.source("Kobo") .source("OEBPS/chapter3.xhtml")
.build()) .build())
.build()) .build())
.build(); .build();
@@ -268,25 +278,26 @@ class KoboReadingStateServiceTest {
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty()); when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress)); when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
when(readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress)).thenReturn(expectedState); when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(readingStateBuilder.buildReadingStateFromProgress(eq(entitlementId), eq(progress), isNull())).thenReturn(expectedState);
List<KoboReadingState> result = service.getReadingState(entitlementId); List<KoboReadingState> result = service.getReadingState(entitlementId);
assertNotNull(result); assertNotNull(result);
assertEquals(1, result.size()); assertEquals(1, result.size());
KoboReadingState state = result.getFirst(); KoboReadingState state = result.getFirst();
assertEquals(entitlementId, state.getEntitlementId()); assertEquals(entitlementId, state.getEntitlementId());
assertNotNull(state.getCurrentBookmark()); assertNotNull(state.getCurrentBookmark());
assertEquals(75, state.getCurrentBookmark().getProgressPercent()); assertEquals(75, state.getCurrentBookmark().getProgressPercent());
assertNotNull(state.getCurrentBookmark().getLocation()); assertNotNull(state.getCurrentBookmark().getLocation());
assertEquals("epubcfi(/6/4[chap01ref]!/4/2/1:3)", state.getCurrentBookmark().getLocation().getValue()); assertEquals("kobo.12.18", state.getCurrentBookmark().getLocation().getValue());
assertEquals("EpubCfi", state.getCurrentBookmark().getLocation().getType()); assertEquals("KoboSpan", state.getCurrentBookmark().getLocation().getType());
assertEquals("Kobo", state.getCurrentBookmark().getLocation().getSource()); assertEquals("OEBPS/chapter3.xhtml", state.getCurrentBookmark().getLocation().getSource());
verify(repository).findByEntitlementIdAndUserId(entitlementId, 1L); verify(repository).findByEntitlementIdAndUserId(entitlementId, 1L);
verify(progressRepository, atLeastOnce()).findByUserIdAndBookId(1L, 100L); verify(progressRepository, atLeastOnce()).findByUserIdAndBookId(1L, 100L);
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress); verify(readingStateBuilder).buildReadingStateFromProgress(eq(entitlementId), eq(progress), isNull());
} }
@Test @Test
@@ -369,7 +380,7 @@ class KoboReadingStateServiceTest {
UserBookProgressEntity savedProgress = progressCaptor.getValue(); UserBookProgressEntity savedProgress = progressCaptor.getValue();
assertNull(savedProgress.getKoboProgressPercent()); assertNull(savedProgress.getKoboProgressPercent());
assertNotNull(savedProgress.getKoboProgressReceivedTime()); assertNull(savedProgress.getKoboProgressReceivedTime());
} }
@Test @Test
@@ -556,6 +567,7 @@ class KoboReadingStateServiceTest {
void testGetReadingState_overlayWebReaderBookmark() { void testGetReadingState_overlayWebReaderBookmark() {
testSettings.setTwoWayProgressSync(true); testSettings.setTwoWayProgressSync(true);
String entitlementId = "100"; String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
KoboReadingState existingState = KoboReadingState.builder() KoboReadingState existingState = KoboReadingState.builder()
.entitlementId(entitlementId) .entitlementId(entitlementId)
@@ -563,9 +575,9 @@ class KoboReadingStateServiceTest {
.progressPercent(30) .progressPercent(30)
.contentSourceProgressPercent(45) .contentSourceProgressPercent(45)
.location(KoboReadingState.CurrentBookmark.Location.builder() .location(KoboReadingState.CurrentBookmark.Location.builder()
.value("epubcfi(/6/10)") .value("kobo.1.1")
.type("EpubCfi") .type("KoboSpan")
.source("Kobo") .source("OEBPS/CoverImage.xhtml")
.build()) .build())
.lastModified("2025-01-01T00:00:00Z") .lastModified("2025-01-01T00:00:00Z")
.build()) .build())
@@ -580,21 +592,23 @@ class KoboReadingStateServiceTest {
progress.setEpubProgressPercent(65f); progress.setEpubProgressPercent(65f);
progress.setLastReadTime(Instant.parse("2025-06-01T10:00:00Z")); progress.setLastReadTime(Instant.parse("2025-06-01T10:00:00Z"));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress)); when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(fileProgressRepository.findByUserIdAndBookFileId(1L, primaryFile.getId())).thenReturn(Optional.empty());
KoboReadingState.CurrentBookmark webBookmark = KoboReadingState.CurrentBookmark.builder() KoboReadingState.CurrentBookmark webBookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(65) .progressPercent(65)
.lastModified("2025-06-01T10:00:00Z") .lastModified("2025-06-01T10:00:00Z")
.build(); .build();
when(readingStateBuilder.buildBookmarkFromProgress(progress)).thenReturn(webBookmark); when(readingStateBuilder.shouldUseWebReaderProgress(progress)).thenReturn(true);
when(readingStateBuilder.buildBookmarkFromProgress(progress, (UserBookFileProgressEntity) null)).thenReturn(webBookmark);
List<KoboReadingState> result = service.getReadingState(entitlementId); List<KoboReadingState> result = service.getReadingState(entitlementId);
assertEquals(1, result.size()); assertEquals(1, result.size());
KoboReadingState.CurrentBookmark bookmark = result.getFirst().getCurrentBookmark(); KoboReadingState.CurrentBookmark bookmark = result.getFirst().getCurrentBookmark();
assertEquals(65, bookmark.getProgressPercent()); assertEquals(65, bookmark.getProgressPercent());
assertEquals(45, bookmark.getContentSourceProgressPercent()); assertNull(bookmark.getContentSourceProgressPercent());
assertNotNull(bookmark.getLocation()); assertNull(bookmark.getLocation());
assertEquals("epubcfi(/6/10)", bookmark.getLocation().getValue());
} }
@Test @Test
@@ -619,30 +633,142 @@ class KoboReadingStateServiceTest {
assertEquals(1, result.size()); assertEquals(1, result.size());
assertEquals(30, result.getFirst().getCurrentBookmark().getProgressPercent()); assertEquals(30, result.getFirst().getCurrentBookmark().getProgressPercent());
verify(readingStateBuilder, never()).buildBookmarkFromProgress(any()); verify(readingStateBuilder, never()).buildBookmarkFromProgress(any(), any());
} }
@Test @Test
@DisplayName("Should cross-populate epub fields from Kobo when two-way sync is ON") @DisplayName("Should overlay web reader location when available")
void testGetReadingState_overlayWebReaderBookmark_replacesLocation() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
KoboReadingState existingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(30)
.location(KoboReadingState.CurrentBookmark.Location.builder()
.value("kobo.1.1")
.type("KoboSpan")
.source("old.xhtml")
.build())
.lastModified("2025-01-01T00:00:00Z")
.build())
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(entity));
when(mapper.toDto(entity)).thenReturn(existingState);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgress("epubcfi(/6/20)");
progress.setEpubProgressPercent(65f);
progress.setLastReadTime(Instant.parse("2025-06-01T10:00:00Z"));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setContentSourceProgressPercent(22f);
when(fileProgressRepository.findByUserIdAndBookFileId(1L, primaryFile.getId())).thenReturn(Optional.of(fileProgress));
KoboReadingState.CurrentBookmark webBookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(65)
.contentSourceProgressPercent(22)
.location(KoboReadingState.CurrentBookmark.Location.builder()
.value("kobo.12.18")
.type("KoboSpan")
.source("new.xhtml")
.build())
.lastModified("2025-06-01T10:00:00Z")
.build();
when(readingStateBuilder.shouldUseWebReaderProgress(progress)).thenReturn(true);
when(readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress)).thenReturn(webBookmark);
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertEquals(1, result.size());
KoboReadingState.CurrentBookmark bookmark = result.getFirst().getCurrentBookmark();
assertEquals(65, bookmark.getProgressPercent());
assertEquals(22, bookmark.getContentSourceProgressPercent());
assertNotNull(bookmark.getLocation());
assertEquals("kobo.12.18", bookmark.getLocation().getValue());
assertEquals("new.xhtml", bookmark.getLocation().getSource());
}
@Test
@DisplayName("Should keep stored Kobo bookmark when mirrored EPUB progress is not newer")
void testGetReadingState_preservesStoredKoboBookmarkWhenKoboIsFreshest() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
KoboReadingState.CurrentBookmark existingBookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(55)
.contentSourceProgressPercent(23)
.location(KoboReadingState.CurrentBookmark.Location.builder()
.value("kobo.12.18")
.type("KoboSpan")
.source("OEBPS/chapter3.xhtml")
.build())
.lastModified("2025-06-15T12:00:00Z")
.build();
KoboReadingState existingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(existingBookmark)
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(entity));
when(mapper.toDto(entity)).thenReturn(existingState);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setKoboProgressPercent(55f);
progress.setKoboLocation("kobo.12.18");
progress.setKoboLocationType("KoboSpan");
progress.setKoboLocationSource("OEBPS/chapter3.xhtml");
progress.setKoboProgressReceivedTime(Instant.parse("2025-06-15T12:00:00Z"));
progress.setEpubProgressPercent(55f);
progress.setLastReadTime(Instant.parse("2025-06-15T12:00:00Z"));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(fileProgressRepository.findByUserIdAndBookFileId(1L, primaryFile.getId())).thenReturn(Optional.empty());
when(readingStateBuilder.shouldUseWebReaderProgress(progress)).thenReturn(false);
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertEquals(1, result.size());
KoboReadingState.CurrentBookmark bookmark = result.getFirst().getCurrentBookmark();
assertEquals(55, bookmark.getProgressPercent());
assertEquals(23, bookmark.getContentSourceProgressPercent());
assertNotNull(bookmark.getLocation());
assertEquals("kobo.12.18", bookmark.getLocation().getValue());
assertEquals("OEBPS/chapter3.xhtml", bookmark.getLocation().getSource());
verify(readingStateBuilder).shouldUseWebReaderProgress(progress);
verify(readingStateBuilder, never()).buildBookmarkFromProgress(eq(progress), any());
}
@Test
@DisplayName("Should cross-populate chapter-aware EPUB fields from Kobo when two-way sync is ON")
void testSyncKoboProgress_crossPopulateEpubFields() { void testSyncKoboProgress_crossPopulateEpubFields() {
testSettings.setTwoWayProgressSync(true); testSettings.setTwoWayProgressSync(true);
String entitlementId = "100"; String entitlementId = "100";
BookFileEntity primaryFile = BookFileEntity.builder().id(10L).build(); BookFileEntity primaryFile = setPrimaryEpub(10L);
testBook.setBookFiles(List.of(primaryFile));
UserBookProgressEntity existingProgress = new UserBookProgressEntity(); UserBookProgressEntity existingProgress = new UserBookProgressEntity();
existingProgress.setUser(testUserEntity); existingProgress.setUser(testUserEntity);
existingProgress.setBook(testBook); existingProgress.setBook(testBook);
KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder() KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder()
.value("epubcfi(/6/8)") .value("kobo.12.18")
.type("EpubCfi") .type("KoboSpan")
.source("chapter3.xhtml") .source("OEBPS/chapter3.xhtml")
.build(); .build();
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder() KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(55) .progressPercent(55)
.contentSourceProgressPercent(23)
.location(location) .location(location)
.lastModified("2025-06-15T12:00:00Z") .lastModified("2025-06-15T12:00:00Z")
.build(); .build();
@@ -660,17 +786,30 @@ class KoboReadingStateServiceTest {
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook)); when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity)); when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(existingProgress)); when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(existingProgress));
when(fileProgressRepository.findByUserIdAndBookFileId(1L, 10L)).thenReturn(Optional.empty()); UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setUser(testUserEntity);
fileProgress.setBookFile(primaryFile);
when(fileProgressRepository.findByUserIdAndBookFileId(1L, 10L)).thenReturn(Optional.of(fileProgress));
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class); ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
when(progressRepository.save(captor.capture())).thenReturn(existingProgress); when(progressRepository.save(captor.capture())).thenReturn(existingProgress);
ArgumentCaptor<UserBookFileProgressEntity> fileProgressCaptor =
ArgumentCaptor.forClass(UserBookFileProgressEntity.class);
service.saveReadingState(List.of(readingState)); service.saveReadingState(List.of(readingState));
UserBookProgressEntity saved = captor.getValue(); UserBookProgressEntity saved = captor.getValue();
assertEquals(55f, saved.getEpubProgressPercent()); assertEquals(55f, saved.getEpubProgressPercent());
assertEquals("chapter3.xhtml", saved.getEpubProgressHref());
assertNull(saved.getEpubProgress()); assertNull(saved.getEpubProgress());
assertEquals("OEBPS/chapter3.xhtml", saved.getEpubProgressHref());
assertEquals(Instant.parse("2025-06-15T12:00:00Z"), saved.getKoboProgressReceivedTime());
assertEquals(Instant.parse("2025-06-15T12:00:00Z"), saved.getLastReadTime());
verify(fileProgressRepository).save(fileProgressCaptor.capture());
UserBookFileProgressEntity savedFileProgress = fileProgressCaptor.getValue();
assertNull(savedFileProgress.getPositionData());
assertEquals("OEBPS/chapter3.xhtml", savedFileProgress.getPositionHref());
assertEquals(23f, savedFileProgress.getContentSourceProgressPercent());
assertEquals(Instant.parse("2025-06-15T12:00:00Z"), savedFileProgress.getLastReadTime());
} }
@Test @Test
@@ -711,14 +850,135 @@ class KoboReadingStateServiceTest {
assertEquals("epubcfi(/6/4)", saved.getEpubProgress()); assertEquals("epubcfi(/6/4)", saved.getEpubProgress());
} }
@Test
@DisplayName("Should clear stale EPUB CFI but keep chapter source when Kobo sends newer KoboSpan")
void testSyncKoboProgress_clearEpubCfiWhenKoboSendsKoboSpan() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
existingProgress.setUser(testUserEntity);
existingProgress.setBook(testBook);
existingProgress.setEpubProgressPercent(55f);
existingProgress.setEpubProgress("epubcfi(/6/8!/4/2/6/1:15)");
existingProgress.setEpubProgressHref("OPS/chapter3.xhtml");
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setUser(testUserEntity);
fileProgress.setBookFile(primaryFile);
fileProgress.setPositionData("epubcfi(/6/8!/4/2/6/1:15)");
fileProgress.setPositionHref("OPS/chapter3.xhtml");
KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder()
.value("kobo.12.18")
.type("KoboSpan")
.source("OEBPS/OPS/chapter3.xhtml")
.build();
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(55)
.contentSourceProgressPercent(23)
.location(location)
.lastModified("2025-06-15T12:00:00Z")
.build();
KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(bookmark)
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(existingProgress));
when(fileProgressRepository.findByUserIdAndBookFileId(1L, primaryFile.getId())).thenReturn(Optional.of(fileProgress));
ArgumentCaptor<UserBookProgressEntity> progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
when(progressRepository.save(progressCaptor.capture())).thenReturn(existingProgress);
ArgumentCaptor<UserBookFileProgressEntity> fileProgressCaptor =
ArgumentCaptor.forClass(UserBookFileProgressEntity.class);
service.saveReadingState(List.of(readingState));
UserBookProgressEntity savedProgress = progressCaptor.getValue();
assertNull(savedProgress.getEpubProgress());
assertEquals("OEBPS/OPS/chapter3.xhtml", savedProgress.getEpubProgressHref());
verify(fileProgressRepository).save(fileProgressCaptor.capture());
UserBookFileProgressEntity savedFileProgress = fileProgressCaptor.getValue();
assertNull(savedFileProgress.getPositionData());
assertEquals("OEBPS/OPS/chapter3.xhtml", savedFileProgress.getPositionHref());
assertEquals(23f, savedFileProgress.getContentSourceProgressPercent());
}
@Test
@DisplayName("Should clear stale chapter progress when Kobo bookmark omits content source progress")
void testSyncKoboProgress_clearStaleContentSourceProgressPercent() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
existingProgress.setUser(testUserEntity);
existingProgress.setBook(testBook);
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setUser(testUserEntity);
fileProgress.setBookFile(primaryFile);
fileProgress.setContentSourceProgressPercent(23f);
fileProgress.setPositionHref("OPS/chapter3.xhtml");
KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder()
.value("kobo.12.18")
.type("KoboSpan")
.source("OEBPS/OPS/chapter3.xhtml")
.build();
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(55)
.location(location)
.lastModified("2025-06-15T12:00:00Z")
.build();
KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(bookmark)
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(existingProgress));
when(progressRepository.save(any())).thenReturn(existingProgress);
when(fileProgressRepository.findByUserIdAndBookFileId(1L, primaryFile.getId())).thenReturn(Optional.of(fileProgress));
ArgumentCaptor<UserBookFileProgressEntity> fileProgressCaptor =
ArgumentCaptor.forClass(UserBookFileProgressEntity.class);
service.saveReadingState(List.of(readingState));
verify(fileProgressRepository).save(fileProgressCaptor.capture());
assertNull(fileProgressCaptor.getValue().getContentSourceProgressPercent());
}
@Test @Test
@DisplayName("Should not cross-populate when web reader has newer progress") @DisplayName("Should not cross-populate when web reader has newer progress")
void testSyncKoboProgress_skipCrossPopulateWhenWebReaderNewer() { void testSyncKoboProgress_skipCrossPopulateWhenWebReaderNewer() {
testSettings.setTwoWayProgressSync(true); testSettings.setTwoWayProgressSync(true);
String entitlementId = "100"; String entitlementId = "100";
BookFileEntity primaryFile = BookFileEntity.builder().id(10L).build(); BookFileEntity primaryFile = setPrimaryEpub(10L);
testBook.setBookFiles(List.of(primaryFile));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity(); UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setLastReadTime(Instant.now().plusSeconds(3600)); fileProgress.setLastReadTime(Instant.now().plusSeconds(3600));
@@ -728,6 +988,7 @@ class KoboReadingStateServiceTest {
existingProgress.setBook(testBook); existingProgress.setBook(testBook);
existingProgress.setEpubProgressPercent(80f); existingProgress.setEpubProgressPercent(80f);
existingProgress.setEpubProgress("epubcfi(/6/20)"); existingProgress.setEpubProgress("epubcfi(/6/20)");
existingProgress.setReadStatus(ReadStatus.READING);
KoboReadingState readingState = KoboReadingState.builder() KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId) .entitlementId(entitlementId)
@@ -755,6 +1016,9 @@ class KoboReadingStateServiceTest {
UserBookProgressEntity saved = captor.getValue(); UserBookProgressEntity saved = captor.getValue();
assertEquals(80f, saved.getEpubProgressPercent()); assertEquals(80f, saved.getEpubProgressPercent());
assertEquals("epubcfi(/6/20)", saved.getEpubProgress()); assertEquals("epubcfi(/6/20)", saved.getEpubProgress());
assertEquals(ReadStatus.READING, saved.getReadStatus());
assertEquals(Instant.parse("2025-01-01T00:00:00Z"), saved.getKoboProgressReceivedTime());
verify(hardcoverSyncService, never()).syncProgressToHardcover(any(), any(), any());
} }
@Test @Test
@@ -778,18 +1042,24 @@ class KoboReadingStateServiceTest {
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty()); when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress)); when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
when(readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress)).thenReturn(expectedState); BookFileEntity primaryFile = setPrimaryEpub(10L);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setContentSourceProgressPercent(35f);
when(fileProgressRepository.findByUserIdAndBookFileId(1L, primaryFile.getId())).thenReturn(Optional.of(fileProgress));
when(readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress, fileProgress)).thenReturn(expectedState);
KoboReadingState.CurrentBookmark webBookmark = KoboReadingState.CurrentBookmark.builder() KoboReadingState.CurrentBookmark webBookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(60) .progressPercent(60)
.lastModified("2025-06-01T10:00:00Z") .lastModified("2025-06-01T10:00:00Z")
.build(); .build();
when(readingStateBuilder.buildBookmarkFromProgress(progress)).thenReturn(webBookmark); when(readingStateBuilder.shouldUseWebReaderProgress(progress)).thenReturn(true);
when(readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress)).thenReturn(webBookmark);
List<KoboReadingState> result = service.getReadingState(entitlementId); List<KoboReadingState> result = service.getReadingState(entitlementId);
assertEquals(1, result.size()); assertEquals(1, result.size());
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress); verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress, fileProgress);
} }
@Test @Test
@@ -809,7 +1079,7 @@ class KoboReadingStateServiceTest {
List<KoboReadingState> result = service.getReadingState(entitlementId); List<KoboReadingState> result = service.getReadingState(entitlementId);
assertTrue(result.isEmpty()); assertTrue(result.isEmpty());
verify(readingStateBuilder, never()).buildReadingStateFromProgress(any(), any()); verify(readingStateBuilder, never()).buildReadingStateFromProgress(any(), any(), any());
} }
@Test @Test
@@ -818,9 +1088,9 @@ class KoboReadingStateServiceTest {
String entitlementId = "100"; String entitlementId = "100";
KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder() KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder()
.value("epubcfi(/6/4[chap01ref]!/4/2/1:3)") .value("kobo.12.18")
.type("EpubCfi") .type("KoboSpan")
.source("Kobo") .source("OEBPS/chapter3.xhtml")
.build(); .build();
KoboReadingState readingState = KoboReadingState.builder() KoboReadingState readingState = KoboReadingState.builder()
@@ -846,9 +1116,9 @@ class KoboReadingStateServiceTest {
service.saveReadingState(List.of(readingState)); service.saveReadingState(List.of(readingState));
UserBookProgressEntity saved = captor.getValue(); UserBookProgressEntity saved = captor.getValue();
assertEquals("epubcfi(/6/4[chap01ref]!/4/2/1:3)", saved.getKoboLocation()); assertEquals("kobo.12.18", saved.getKoboLocation());
assertEquals("EpubCfi", saved.getKoboLocationType()); assertEquals("KoboSpan", saved.getKoboLocationType());
assertEquals("Kobo", saved.getKoboLocationSource()); assertEquals("OEBPS/chapter3.xhtml", saved.getKoboLocationSource());
assertEquals(42f, saved.getKoboProgressPercent()); assertEquals(42f, saved.getKoboProgressPercent());
} }
@@ -0,0 +1,242 @@
package org.booklore.service.kobo;
import org.booklore.model.dto.kobo.KoboSpanPositionMap;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.entity.UserBookFileProgressEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.util.koreader.EpubCfiService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class KoboBookmarkLocationResolverTest {
@Mock
private KoboSpanMapService koboSpanMapService;
@Mock
private EpubCfiService epubCfiService;
private KoboBookmarkLocationResolver resolver;
@BeforeEach
void setUp() {
resolver = new KoboBookmarkLocationResolver(koboSpanMapService, epubCfiService);
}
@Test
void resolve_UsesFirstKoboSpanWhenOnlyHrefIsAvailable() {
BookFileEntity bookFile = createBookFile();
when(koboSpanMapService.getValidMap(bookFile)).thenReturn(Optional.of(singleChapterMap()));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setBookFile(bookFile);
fileProgress.setPositionHref("chapter1.xhtml");
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgressHref("chapter1.xhtml");
Optional<KoboBookmarkLocationResolver.ResolvedBookmarkLocation> result =
resolver.resolve(progress, fileProgress);
assertTrue(result.isPresent());
assertEquals("kobo.1.1", result.get().value());
assertEquals("KoboSpan", result.get().type());
assertEquals("OPS/chapter1.xhtml", result.get().source());
assertNull(result.get().contentSourceProgressPercent());
}
@Test
void resolve_UsesStoredContentSourceProgressPercentToSelectNearestKoboSpan() {
BookFileEntity bookFile = createBookFile();
when(koboSpanMapService.getValidMap(bookFile)).thenReturn(Optional.of(singleChapterMap()));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setBookFile(bookFile);
fileProgress.setPositionHref("chapter1.xhtml");
fileProgress.setContentSourceProgressPercent(80f);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgressHref("chapter1.xhtml");
Optional<KoboBookmarkLocationResolver.ResolvedBookmarkLocation> result =
resolver.resolve(progress, fileProgress);
assertTrue(result.isPresent());
assertEquals("kobo.1.2", result.get().value());
assertEquals("KoboSpan", result.get().type());
assertEquals("OPS/chapter1.xhtml", result.get().source());
assertEquals(80f, result.get().contentSourceProgressPercent());
}
@Test
void resolve_FallsBackToPrimaryEpubWhenFileProgressIsMissing() {
BookFileEntity bookFile = createBookFile();
when(koboSpanMapService.getValidMap(bookFile)).thenReturn(Optional.of(singleChapterMap()));
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(bookFile.getBook());
progress.setEpubProgressHref("chapter1.xhtml");
Optional<KoboBookmarkLocationResolver.ResolvedBookmarkLocation> result =
resolver.resolve(progress, null);
assertTrue(result.isPresent());
assertEquals("kobo.1.1", result.get().value());
assertEquals("OPS/chapter1.xhtml", result.get().source());
assertNull(result.get().contentSourceProgressPercent());
}
@Test
void resolve_UsesGlobalProgressWhenHrefIsMissing() {
BookFileEntity bookFile = createBookFile();
when(koboSpanMapService.getValidMap(bookFile)).thenReturn(Optional.of(twoChapterMap()));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setBookFile(bookFile);
fileProgress.setProgressPercent(75f);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgressPercent(75f);
Optional<KoboBookmarkLocationResolver.ResolvedBookmarkLocation> result =
resolver.resolve(progress, fileProgress);
assertTrue(result.isPresent());
assertEquals("kobo.2.2", result.get().value());
assertEquals("OPS/chapter2.xhtml", result.get().source());
assertEquals(50f, result.get().contentSourceProgressPercent());
}
@Test
void resolve_UsesCfiDerivedChapterPositionWhenStoredChapterProgressIsMissing() {
BookFileEntity bookFile = createBookFile();
when(koboSpanMapService.getValidMap(bookFile)).thenReturn(Optional.of(singleChapterMap()));
when(epubCfiService.resolveCfiLocation(Path.of("/library/book.epub"), "epubcfi(/6/2!/4/2/2:15)"))
.thenReturn(Optional.of(new EpubCfiService.CfiLocation("chapter1.xhtml", 80f)));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setBookFile(bookFile);
fileProgress.setPositionData("epubcfi(/6/2!/4/2/2:15)");
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgress("epubcfi(/6/2!/4/2/2:15)");
Optional<KoboBookmarkLocationResolver.ResolvedBookmarkLocation> result =
resolver.resolve(progress, fileProgress);
assertTrue(result.isPresent());
assertEquals("kobo.1.2", result.get().value());
assertEquals("OPS/chapter1.xhtml", result.get().source());
assertEquals(80f, result.get().contentSourceProgressPercent());
}
@Test
void resolve_PrefersExactHrefMatchOverSuffixMatch() {
BookFileEntity bookFile = createBookFile();
when(koboSpanMapService.getValidMap(bookFile)).thenReturn(Optional.of(new KoboSpanPositionMap(List.of(
new KoboSpanPositionMap.Chapter(
"OPS/chapter3.xhtml",
"OPS/chapter3.xhtml",
0,
0f,
0.5f,
List.of(new KoboSpanPositionMap.Span("exact-span", 0.2f))),
new KoboSpanPositionMap.Chapter(
"OEBPS/OPS/chapter3.xhtml",
"OEBPS/OPS/chapter3.xhtml",
1,
0.5f,
1f,
List.of(new KoboSpanPositionMap.Span("suffix-span", 0.2f)))
))));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setBookFile(bookFile);
fileProgress.setPositionHref("OPS/chapter3.xhtml");
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgressHref("OPS/chapter3.xhtml");
Optional<KoboBookmarkLocationResolver.ResolvedBookmarkLocation> result =
resolver.resolve(progress, fileProgress);
assertTrue(result.isPresent());
assertEquals("exact-span", result.get().value());
assertEquals("OPS/chapter3.xhtml", result.get().source());
}
private BookFileEntity createBookFile() {
BookEntity book = new BookEntity();
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath("/library");
book.setLibraryPath(libraryPath);
BookFileEntity bookFile = new BookFileEntity();
bookFile.setId(10L);
bookFile.setBook(book);
bookFile.setBookType(BookFileType.EPUB);
bookFile.setCurrentHash("hash-123");
bookFile.setFileName("book.epub");
bookFile.setFileSubPath("");
book.setBookFiles(List.of(bookFile));
return bookFile;
}
private KoboSpanPositionMap singleChapterMap() {
return new KoboSpanPositionMap(List.of(
new KoboSpanPositionMap.Chapter(
"OPS/chapter1.xhtml",
"OPS/chapter1.xhtml",
0,
0f,
1f,
List.of(
new KoboSpanPositionMap.Span("kobo.1.1", 0.2f),
new KoboSpanPositionMap.Span("kobo.1.2", 0.85f)
))
));
}
private KoboSpanPositionMap twoChapterMap() {
return new KoboSpanPositionMap(List.of(
new KoboSpanPositionMap.Chapter(
"OPS/chapter1.xhtml",
"OPS/chapter1.xhtml",
0,
0f,
0.5f,
List.of(
new KoboSpanPositionMap.Span("kobo.1.1", 0.1f),
new KoboSpanPositionMap.Span("kobo.1.2", 0.9f)
)),
new KoboSpanPositionMap.Chapter(
"OPS/chapter2.xhtml",
"OPS/chapter2.xhtml",
1,
0.5f,
1f,
List.of(
new KoboSpanPositionMap.Span("kobo.2.1", 0.1f),
new KoboSpanPositionMap.Span("kobo.2.2", 0.5f),
new KoboSpanPositionMap.Span("kobo.2.3", 0.9f)
))
));
}
}
@@ -35,7 +35,6 @@ class KoboCompatibilityServiceTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
koboSettings = KoboSettings.builder() koboSettings = KoboSettings.builder()
.convertToKepub(false)
.conversionLimitInMb(100) .conversionLimitInMb(100)
.convertCbxToEpub(false) .convertCbxToEpub(false)
.conversionLimitInMbForCbx(50) .conversionLimitInMbForCbx(50)
@@ -0,0 +1,24 @@
package org.booklore.service.kobo;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class KoboEpubUtilsTest {
@Test
void normalizeHref_returnsNullForNullHref() {
assertNull(KoboEpubUtils.normalizeHref(null));
}
@Test
void decodeHrefPath_preservesMalformedPathWhenUriParsingFails() {
assertEquals("chapter%zz.xhtml", KoboEpubUtils.decodeHrefPath("chapter%zz.xhtml"));
}
@Test
void normalizeHref_trimsLeadingSlashFromDecodedHref() {
assertEquals("OPS/chapter 1.xhtml", KoboEpubUtils.normalizeHref("/OPS/chapter%201.xhtml"));
}
}
@@ -230,6 +230,21 @@ class KoboLibrarySyncServiceTest {
assertTrue(needsProgressSync(progress)); assertTrue(needsProgressSync(progress));
} }
@Test
@DisplayName("Should detect href-only web reader progress when toggle ON and lastReadTime after sent")
void needsProgressSync_webReaderHrefOnly() {
testSettings.setTwoWayProgressSync(true);
UserBookProgressEntity progress = createProgress(1L);
progress.setEpubProgressHref("OPS/chapter3.xhtml");
progress.setEpubProgressPercent(65f);
progress.setLastReadTime(Instant.now());
progress.setKoboProgressSentTime(Instant.now().minusSeconds(60));
progress.setKoboProgressReceivedTime(Instant.now().minusSeconds(120));
assertTrue(needsProgressSync(progress));
}
@Test @Test
@DisplayName("Should not sync web reader progress when toggle OFF") @DisplayName("Should not sync web reader progress when toggle OFF")
void needsProgressSync_toggleOff() { void needsProgressSync_toggleOff() {
@@ -286,7 +301,7 @@ class KoboLibrarySyncServiceTest {
if (needsKoboProgressSync(progress)) return true; if (needsKoboProgressSync(progress)) return true;
if (testSettings.isTwoWayProgressSync() if (testSettings.isTwoWayProgressSync()
&& progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null) { && progress.getEpubProgressPercent() != null) {
Instant sentTime = progress.getKoboProgressSentTime(); Instant sentTime = progress.getKoboProgressSentTime();
Instant lastReadTime = progress.getLastReadTime(); Instant lastReadTime = progress.getLastReadTime();
if (lastReadTime != null && (sentTime == null || lastReadTime.isAfter(sentTime))) { if (lastReadTime != null && (sentTime == null || lastReadTime.isAfter(sentTime))) {
@@ -0,0 +1,193 @@
package org.booklore.service.kobo;
import org.booklore.model.dto.kobo.KoboSpanPositionMap;
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.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class KoboSpanMapExtractionServiceTest {
private final KoboSpanMapExtractionService service = new KoboSpanMapExtractionService();
@TempDir
Path tempDir;
@Test
void extractFromKepub_ExtractsSpineEntriesAndProgressBoundaries() throws Exception {
File kepubFile = createKepub(
"OPS/package.opf",
"""
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
<manifest>
<item id="chap1" href="chapter1.xhtml" media-type="application/xhtml+xml"/>
<item id="chap2" href="chapter2.xhtml" media-type="application/xhtml+xml"/>
</manifest>
<spine>
<itemref idref="chap1"/>
<itemref idref="chap2"/>
</spine>
</package>
""",
new ZipResource("OPS/chapter1.xhtml", chapterHtml("kobo.1.1", "kobo.1.2")),
new ZipResource("OPS/chapter2.xhtml", chapterHtml("kobo.2.1", "kobo.2.2"))
);
KoboSpanPositionMap result = service.extractFromKepub(kepubFile);
assertEquals(2, result.chapters().size());
assertEquals("OPS/chapter1.xhtml", result.chapters().get(0).sourceHref());
assertEquals("OPS/chapter2.xhtml", result.chapters().get(1).sourceHref());
assertEquals("kobo.1.1", result.chapters().get(0).spans().get(0).id());
assertEquals("kobo.2.2", result.chapters().get(1).spans().get(1).id());
assertEquals(0f, result.chapters().get(0).globalStartProgress(), 0.0001f);
assertTrue(result.chapters().get(0).globalEndProgress() > 0f);
assertEquals(1f, result.chapters().get(1).globalEndProgress(), 0.0001f);
}
@Test
void extractFromKepub_ResolvesEncodedManifestHrefsToActualEntries() throws Exception {
File kepubFile = createKepub(
"OPS/package.opf",
"""
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
<manifest>
<item id="chap1" href="Text/chapter%202.xhtml" media-type="application/xhtml+xml"/>
</manifest>
<spine>
<itemref idref="chap1"/>
</spine>
</package>
""",
new ZipResource("OPS/Text/chapter 2.xhtml", chapterHtml("kobo.2.1", "kobo.2.2"))
);
KoboSpanPositionMap result = service.extractFromKepub(kepubFile);
assertEquals(1, result.chapters().size());
assertEquals("OPS/Text/chapter 2.xhtml", result.chapters().getFirst().sourceHref());
assertEquals("OPS/Text/chapter 2.xhtml", result.chapters().getFirst().normalizedHref());
}
@Test
void extractFromKepub_PreservesPlusSignsInManifestHrefs() throws Exception {
File kepubFile = createKepub(
"OPS/package.opf",
"""
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
<manifest>
<item id="chap1" href="Text/chapter%2B1.xhtml" media-type="application/xhtml+xml"/>
</manifest>
<spine>
<itemref idref="chap1"/>
</spine>
</package>
""",
new ZipResource("OPS/Text/chapter+1.xhtml", chapterHtml("kobo.1.1", "kobo.1.2"))
);
KoboSpanPositionMap result = service.extractFromKepub(kepubFile);
assertEquals(1, result.chapters().size());
assertEquals("OPS/Text/chapter+1.xhtml", result.chapters().getFirst().sourceHref());
assertEquals("OPS/Text/chapter+1.xhtml", result.chapters().getFirst().normalizedHref());
}
@Test
void extractFromKepub_KeepsSpanlessChaptersInProgressModel() throws Exception {
File kepubFile = createKepub(
"OPS/package.opf",
"""
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
<manifest>
<item id="front" href="front.xhtml" media-type="application/xhtml+xml"/>
<item id="chap1" href="chapter1.xhtml" media-type="application/xhtml+xml"/>
<item id="chap2" href="chapter2.xhtml" media-type="application/xhtml+xml"/>
</manifest>
<spine>
<itemref idref="front"/>
<itemref idref="chap1"/>
<itemref idref="chap2"/>
</spine>
</package>
""",
new ZipResource("OPS/front.xhtml", chapterHtmlWithoutSpans()),
new ZipResource("OPS/chapter1.xhtml", chapterHtml("kobo.1.1", "kobo.1.2")),
new ZipResource("OPS/chapter2.xhtml", chapterHtml("kobo.2.1", "kobo.2.2"))
);
KoboSpanPositionMap result = service.extractFromKepub(kepubFile);
assertEquals(3, result.chapters().size());
assertTrue(result.chapters().getFirst().spans().isEmpty());
assertTrue(result.chapters().get(1).globalStartProgress() > 0f);
}
private File createKepub(String opfPath, String opfContent, ZipResource... resources) throws IOException {
File kepubFile = tempDir.resolve("test.kepub.epub").toFile();
try (ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(kepubFile))) {
outputStream.putNextEntry(new ZipEntry("META-INF/container.xml"));
outputStream.write(containerXml(opfPath).getBytes(StandardCharsets.UTF_8));
outputStream.closeEntry();
outputStream.putNextEntry(new ZipEntry(opfPath));
outputStream.write(opfContent.getBytes(StandardCharsets.UTF_8));
outputStream.closeEntry();
for (ZipResource resource : resources) {
outputStream.putNextEntry(new ZipEntry(resource.path()));
outputStream.write(resource.content().getBytes(StandardCharsets.UTF_8));
outputStream.closeEntry();
}
}
return kepubFile;
}
private String containerXml(String opfPath) {
return """
<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="%s" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>
""".formatted(opfPath);
}
private String chapterHtml(String firstSpanId, String secondSpanId) {
return """
<html>
<body>
<p><span class="koboSpan" id="%s"></span>First paragraph with enough text to move the marker.</p>
<p><span class="koboSpan" id="%s"></span>Second paragraph with even more text to shift the marker later.</p>
</body>
</html>
""".formatted(firstSpanId, secondSpanId);
}
private String chapterHtmlWithoutSpans() {
return """
<html>
<body>
<p>Front matter without Kobo span markers but with enough text to count in the book length.</p>
</body>
</html>
""";
}
private record ZipResource(String path, String content) {
}
}
@@ -0,0 +1,152 @@
package org.booklore.service.kobo;
import org.booklore.model.dto.kobo.KoboSpanPositionMap;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.KoboSpanMapEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.KoboSpanMapRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.File;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class KoboSpanMapServiceTest {
@Mock
private KoboSpanMapRepository koboSpanMapRepository;
@Mock
private KoboSpanMapExtractionService koboSpanMapExtractionService;
private KoboSpanMapService service;
@BeforeEach
void setUp() {
service = new KoboSpanMapService(koboSpanMapRepository, koboSpanMapExtractionService);
}
@Test
void computeAndStoreIfNeeded_SkipsWhenExistingHashMatches() throws Exception {
BookFileEntity bookFile = createBookFile("hash-1");
KoboSpanMapEntity existing = KoboSpanMapEntity.builder()
.bookFile(bookFile)
.fileHash("hash-1")
.spanMap(spanMap())
.createdAt(Instant.now())
.build();
when(koboSpanMapRepository.findByBookFileId(bookFile.getId())).thenReturn(Optional.of(existing));
service.computeAndStoreIfNeeded(bookFile, new File("ignored.kepub.epub"));
verify(koboSpanMapExtractionService, never()).extractFromKepub(any());
verify(koboSpanMapRepository, never()).save(any());
}
@Test
void computeAndStoreIfNeeded_ExtractsAndSavesWhenHashChanges() throws Exception {
BookFileEntity bookFile = createBookFile("hash-2");
KoboSpanMapEntity existing = KoboSpanMapEntity.builder()
.id(99L)
.bookFile(bookFile)
.fileHash("old-hash")
.spanMap(spanMap())
.createdAt(Instant.parse("2024-01-01T00:00:00Z"))
.build();
KoboSpanPositionMap newMap = new KoboSpanPositionMap(List.of(
new KoboSpanPositionMap.Chapter("OPS/chapter2.xhtml", "OPS/chapter2.xhtml", 0, 0f, 1f,
List.of(new KoboSpanPositionMap.Span("kobo.2.1", 0.5f)))
));
when(koboSpanMapRepository.findByBookFileId(bookFile.getId())).thenReturn(Optional.of(existing));
when(koboSpanMapExtractionService.extractFromKepub(any())).thenReturn(newMap);
service.computeAndStoreIfNeeded(bookFile, tempKepubFile());
ArgumentCaptor<KoboSpanMapEntity> captor = ArgumentCaptor.forClass(KoboSpanMapEntity.class);
verify(koboSpanMapRepository).save(captor.capture());
assertEquals(99L, captor.getValue().getId());
assertEquals("hash-2", captor.getValue().getFileHash());
assertEquals(newMap, captor.getValue().getSpanMap());
assertEquals(Instant.parse("2024-01-01T00:00:00Z"), captor.getValue().getCreatedAt());
}
@Test
void getValidMap_ReturnsOnlyWhenHashMatches() {
BookFileEntity bookFile = createBookFile("hash-3");
KoboSpanMapEntity stored = KoboSpanMapEntity.builder()
.bookFile(bookFile)
.fileHash("hash-3")
.spanMap(spanMap())
.createdAt(Instant.now())
.build();
when(koboSpanMapRepository.findByBookFileId(bookFile.getId())).thenReturn(Optional.of(stored));
Optional<KoboSpanPositionMap> validMap = service.getValidMap(bookFile);
assertTrue(validMap.isPresent());
assertEquals(spanMap(), validMap.get());
stored.setFileHash("stale-hash");
Optional<KoboSpanPositionMap> staleMap = service.getValidMap(bookFile);
assertFalse(staleMap.isPresent());
}
@Test
void getValidMaps_SkipsEntriesWithNullSpanMap() {
BookFileEntity bookFile = createBookFile("hash-4");
KoboSpanMapEntity stored = KoboSpanMapEntity.builder()
.bookFile(bookFile)
.fileHash("hash-4")
.spanMap(null)
.createdAt(Instant.now())
.build();
when(koboSpanMapRepository.findByBookFileIdIn(bookFilesById(bookFile).keySet())).thenReturn(List.of(stored));
Map<Long, KoboSpanPositionMap> validMaps = service.getValidMaps(bookFilesById(bookFile));
assertTrue(validMaps.isEmpty());
}
private BookFileEntity createBookFile(String hash) {
BookFileEntity bookFile = new BookFileEntity();
bookFile.setId(42L);
bookFile.setBookType(BookFileType.EPUB);
bookFile.setCurrentHash(hash);
return bookFile;
}
private KoboSpanPositionMap spanMap() {
return new KoboSpanPositionMap(List.of(
new KoboSpanPositionMap.Chapter("OPS/chapter1.xhtml", "OPS/chapter1.xhtml", 0, 0f, 1f,
List.of(new KoboSpanPositionMap.Span("kobo.1.1", 0.2f)))
));
}
private Map<Long, BookFileEntity> bookFilesById(BookFileEntity bookFile) {
return Map.of(bookFile.getId(), bookFile);
}
private File tempKepubFile() throws Exception {
File file = File.createTempFile("kobo-span-map", ".kepub.epub");
file.deleteOnExit();
return file;
}
}
@@ -6,6 +6,7 @@ import org.booklore.model.dto.Book;
import org.booklore.model.dto.BookLoreUser; import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.progress.EpubProgress; import org.booklore.model.dto.progress.EpubProgress;
import org.booklore.model.dto.progress.PdfProgress; import org.booklore.model.dto.progress.PdfProgress;
import org.booklore.model.dto.request.BookFileProgress;
import org.booklore.model.dto.request.ReadProgressRequest; import org.booklore.model.dto.request.ReadProgressRequest;
import org.booklore.model.dto.response.BookStatusUpdateResponse; import org.booklore.model.dto.response.BookStatusUpdateResponse;
import org.booklore.model.entity.*; import org.booklore.model.entity.*;
@@ -153,12 +154,16 @@ class ReadingProgressServiceTest {
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity(); UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setBookFile(bookFile); fileProgress.setBookFile(bookFile);
fileProgress.setPositionData("new-cfi"); fileProgress.setPositionData("new-cfi");
fileProgress.setPositionHref("OPS/chapter3.xhtml");
fileProgress.setContentSourceProgressPercent(18.6f);
fileProgress.setProgressPercent(50.0f); fileProgress.setProgressPercent(50.0f);
fileProgress.setLastReadTime(Instant.now()); fileProgress.setLastReadTime(Instant.now());
readingProgressService.enrichBookWithProgress(book, progress, fileProgress); readingProgressService.enrichBookWithProgress(book, progress, fileProgress);
assertEquals("new-cfi", book.getEpubProgress().getCfi()); assertEquals("new-cfi", book.getEpubProgress().getCfi());
assertEquals("OPS/chapter3.xhtml", book.getEpubProgress().getHref());
assertEquals(18.6f, book.getEpubProgress().getContentSourceProgressPercent());
assertEquals(50.0f, book.getEpubProgress().getPercentage()); assertEquals(50.0f, book.getEpubProgress().getPercentage());
} }
@@ -200,6 +205,49 @@ class ReadingProgressServiceTest {
assertEquals(100f, progress.getEpubProgressPercent()); assertEquals(100f, progress.getEpubProgressPercent());
} }
@Test
void updateReadProgress_fileProgress_shouldSaveContentSourceProgress() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
BookFileEntity primaryFile = new BookFileEntity();
primaryFile.setId(1L);
primaryFile.setBook(book);
primaryFile.setBookType(BookFileType.EPUB);
book.setBookFiles(List.of(primaryFile));
BookLoreUser user = mock(BookLoreUser.class);
when(user.getId()).thenReturn(2L);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book));
when(bookFileRepository.findById(1L)).thenReturn(Optional.of(primaryFile));
BookLoreUserEntity userEntity = new BookLoreUserEntity();
userEntity.setId(2L);
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
UserBookProgressEntity progress = new UserBookProgressEntity();
when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress));
when(userBookFileProgressRepository.findByUserIdAndBookFileId(2L, 1L)).thenReturn(Optional.empty());
ReadProgressRequest req = new ReadProgressRequest();
req.setBookId(bookId);
req.setFileProgress(new BookFileProgress(
1L,
"epubcfi(/6/8!/4/2/6/1:15)",
"OPS/chapter3.xhtml",
55f,
"epubcfi(/6/8!/4/2/6/1:10)",
18.6f));
readingProgressService.updateReadProgress(req);
verify(userBookFileProgressRepository).save(argThat(savedFileProgress ->
savedFileProgress.getContentSourceProgressPercent() != null
&& savedFileProgress.getContentSourceProgressPercent().equals(18.6f)
&& "OPS/chapter3.xhtml".equals(savedFileProgress.getPositionHref())));
}
@Test @Test
void updateReadProgress_pdf_shouldSaveProgress() { void updateReadProgress_pdf_shouldSaveProgress() {
long bookId = 1L; long bookId = 1L;
@@ -182,6 +182,18 @@ class EpubCfiServiceTest {
assertNotNull(result); assertNotNull(result);
assertNotNull(result.getXpointer()); assertNotNull(result.getXpointer());
} }
@Test
void convertCfiToXPointer_roundTripsNestedParagraphLocation() {
String originalXPointer = "/body/DocFragment[1]/body/div[1]/p[2]/text().10";
String cfi = service.convertXPointerToCfi(testEpubFile, originalXPointer);
XPointerResult result = service.convertCfiToXPointer(testEpubFile, cfi);
assertNotNull(result);
assertNotNull(result.getXpointer());
assertTrue(result.getXpointer().contains("/p[2]/text().10"), result.getXpointer());
}
} }
@Nested @Nested
@@ -241,6 +253,31 @@ class EpubCfiServiceTest {
} }
} }
@Nested
class ResolveCfiLocationTests {
@Test
void resolveCfiLocation_textOffsetsReturnMatchingHrefAndIncreasingProgress() {
String earlyCfi = service.convertXPointerToCfi(testEpubFile, "/body/DocFragment[1]/body/div[1]/p[1]/text().0");
String laterCfi = service.convertXPointerToCfi(testEpubFile, "/body/DocFragment[1]/body/div[1]/p[2]/text().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() > 0f);
assertTrue(earlyLocation.contentSourceProgressPercent() < laterLocation.contentSourceProgressPercent());
}
@Test
void resolveCfiLocation_invalidCfiReturnsEmpty() {
assertTrue(service.resolveCfiLocation(testEpubFile, "invalid").isEmpty());
}
}
@Nested @Nested
class ValidationTests { class ValidationTests {
@@ -60,7 +60,9 @@ export interface Book extends FileInfo {
} }
export interface EpubProgress { export interface EpubProgress {
cfi: string; cfi?: string | null;
href?: string;
contentSourceProgressPercent?: number | null;
percentage: number; percentage: number;
} }
@@ -74,6 +74,7 @@ import {ViewEvent} from './core/view-manager.service';
}) })
export class EbookReaderComponent implements OnInit { export class EbookReaderComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
private static readonly MAX_CHAPTER_PROGRESS_PERCENT = 99.9;
private loaderService = inject(ReaderLoaderService); private loaderService = inject(ReaderLoaderService);
private styleService = inject(ReaderStyleService); private styleService = inject(ReaderStyleService);
private bookService = inject(BookService); private bookService = inject(BookService);
@@ -101,6 +102,7 @@ export class EbookReaderComponent implements OnInit {
private visibilityManager!: ReaderHeaderFooterVisibilityManager; private visibilityManager!: ReaderHeaderFooterVisibilityManager;
private relocateTimeout?: ReturnType<typeof setTimeout>; private relocateTimeout?: ReturnType<typeof setTimeout>;
private sectionFractionsTimeout?: ReturnType<typeof setTimeout>; private sectionFractionsTimeout?: ReturnType<typeof setTimeout>;
private pendingInitialChapterRestore: { href: string; contentSourceProgressPercent: number } | null = null;
isLoading = signal(true); isLoading = signal(true);
showQuickSettings = signal(false); showQuickSettings = signal(false);
@@ -251,6 +253,8 @@ export class EbookReaderComponent implements OnInit {
this.hasLoadedOnce = true; this.hasLoadedOnce = true;
if (book.epubProgress?.cfi) { if (book.epubProgress?.cfi) {
return this.viewManager.goTo(book.epubProgress.cfi); return this.viewManager.goTo(book.epubProgress.cfi);
} else if (book.epubProgress?.href) {
return this.viewManager.goTo(book.epubProgress.href);
} else if (book.epubProgress?.percentage && book.epubProgress.percentage > 0) { } else if (book.epubProgress?.percentage && book.epubProgress.percentage > 0) {
return this.viewManager.goToFraction(book.epubProgress.percentage / 100); return this.viewManager.goToFraction(book.epubProgress.percentage / 100);
} else { } else {
@@ -287,7 +291,6 @@ export class EbookReaderComponent implements OnInit {
this.viewManager.createView(container); this.viewManager.createView(container);
return of(undefined); return of(undefined);
} }
private loadBookBlob(): Observable<void> { private loadBookBlob(): Observable<void> {
return this.bookFileService.getFileContent(this.bookId, this.altBookType).pipe( return this.bookFileService.getFileContent(this.bookId, this.altBookType).pipe(
switchMap(fileBlob => { switchMap(fileBlob => {
@@ -309,6 +312,14 @@ export class EbookReaderComponent implements OnInit {
this.updateSectionFractions(); this.updateSectionFractions();
break; break;
case 'relocate': case 'relocate':
if (this.handlePendingInitialChapterRestore(event.detail)) {
if (this.sectionFractionsTimeout) clearTimeout(this.sectionFractionsTimeout);
this.sectionFractionsTimeout = setTimeout(() => {
this.updateSectionFractions();
}, 500);
break;
}
if (this.relocateTimeout) clearTimeout(this.relocateTimeout); if (this.relocateTimeout) clearTimeout(this.relocateTimeout);
this.relocateTimeout = setTimeout(() => { this.relocateTimeout = setTimeout(() => {
this.progressService.handleRelocateEvent(event.detail); this.progressService.handleRelocateEvent(event.detail);
@@ -382,6 +393,98 @@ export class EbookReaderComponent implements OnInit {
this.sectionFractions.set(this.viewManager.getSectionFractions()); this.sectionFractions.set(this.viewManager.getSectionFractions());
} }
private restoreSavedPosition(book: Book): Observable<void> {
const progress = book.epubProgress;
if (progress?.cfi) {
return this.viewManager.goTo(progress.cfi);
}
if (progress?.href) {
const chapterProgress = progress.contentSourceProgressPercent;
if (typeof chapterProgress === 'number' && Number.isFinite(chapterProgress) && chapterProgress > 0) {
this.pendingInitialChapterRestore = {
href: this.normalizeHref(progress.href),
contentSourceProgressPercent: chapterProgress
};
} else {
this.pendingInitialChapterRestore = null;
}
return this.viewManager.goTo(progress.href);
}
this.pendingInitialChapterRestore = null;
if (progress?.percentage && progress.percentage > 0) {
return this.viewManager.goToFraction(progress.percentage / 100);
}
return this.viewManager.goTo(0);
}
private handlePendingInitialChapterRestore(detail: RelocateProgressData): boolean {
if (!this.pendingInitialChapterRestore) {
return false;
}
const currentHref = this.normalizeHref(detail.pageItem?.href ?? detail.tocItem?.href ?? null);
if (!currentHref || !this.hrefsMatch(currentHref, this.pendingInitialChapterRestore.href)) {
return false;
}
const targetFraction = this.resolveChapterFraction(
detail.section?.current,
this.pendingInitialChapterRestore.contentSourceProgressPercent
);
if (targetFraction === null) {
return false;
}
if (typeof detail.fraction === 'number' && Math.abs(detail.fraction - targetFraction) < 0.0001) {
this.pendingInitialChapterRestore = null;
return false;
}
this.pendingInitialChapterRestore = null;
this.viewManager.goToFraction(targetFraction)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
return true;
}
private resolveChapterFraction(sectionIndex: number | undefined, chapterProgressPercent: number): number | null {
if (sectionIndex === undefined) {
return null;
}
const sectionFractions = this.viewManager.getSectionFractions();
const start = sectionFractions[sectionIndex];
const end = sectionFractions[sectionIndex + 1];
if (start === undefined || end === undefined || end <= start) {
return null;
}
const normalizedProgress = Math.min(
Math.max(chapterProgressPercent, 0),
EbookReaderComponent.MAX_CHAPTER_PROGRESS_PERCENT
) / 100;
return start + ((end - start) * normalizedProgress);
}
private normalizeHref(href: string | null | undefined): string {
return (href ?? '').split('#')[0].replace(/^(\.\/|\/)+/, '');
}
private hrefsMatch(leftHref: string, rightHref: string): boolean {
return leftHref === rightHref
|| leftHref.endsWith(`/${rightHref}`)
|| rightHref.endsWith(`/${leftHref}`);
}
private updateBookmarkIndicator(): void { private updateBookmarkIndicator(): void {
const currentCfi = this.progressService.currentCfi; const currentCfi = this.progressService.currentCfi;
const isBookmarked = currentCfi const isBookmarked = currentCfi
@@ -60,6 +60,16 @@
<br> <br>
<strong>{{ t('kobo.twoWaySyncNote') }}</strong> <strong>{{ t('kobo.twoWaySyncNote') }}</strong>
</p> </p>
@if (syncForm.controls.twoWayProgressSync.value && !koboSettings.convertToKepub) {
<p class="setting-warning" role="status" aria-live="polite" aria-atomic="true">
<i class="pi pi-exclamation-triangle" aria-hidden="true"></i>
@if (isAdmin) {
{{ t('kobo.twoWaySyncKepubWarningAdmin') }}
} @else {
{{ t('kobo.twoWaySyncKepubWarning') }}
}
</p>
}
</div> </div>
</div> </div>
} }
@@ -118,6 +118,12 @@
line-height: 1.5; line-height: 1.5;
margin: 0; margin: 0;
} }
.setting-warning {
@include settings.settings-warning-notice;
margin-top: 0.75rem;
}
} }
.setting-control { .setting-control {
@@ -91,10 +91,10 @@ describe('KoboSyncSettingsComponent', () => {
const component = fixture.componentInstance; const component = fixture.componentInstance;
TestBed.flushEffects(); TestBed.flushEffects();
expect(component.koboSettings.convertToKepub).toBe(false); expect(component.koboSettings.convertToKepub).toBe(true);
appSettingsState.set(buildAppSettings({ appSettingsState.set(buildAppSettings({
convertToKepub: true, convertToKepub: false,
conversionLimitInMb: 42, conversionLimitInMb: 42,
convertCbxToEpub: true, convertCbxToEpub: true,
conversionImageCompressionPercentage: 73, conversionImageCompressionPercentage: 73,
@@ -106,7 +106,7 @@ describe('KoboSyncSettingsComponent', () => {
TestBed.flushEffects(); TestBed.flushEffects();
expect(component.koboSettings).toEqual({ expect(component.koboSettings).toEqual({
convertToKepub: true, convertToKepub: false,
conversionLimitInMb: 42, conversionLimitInMb: 42,
convertCbxToEpub: true, convertCbxToEpub: true,
conversionImageCompressionPercentage: 73, conversionImageCompressionPercentage: 73,
@@ -58,7 +58,7 @@ export class KoboSyncSettingsComponent implements OnInit {
}); });
koboSettings: KoboSettings = { koboSettings: KoboSettings = {
convertToKepub: false, convertToKepub: true,
conversionLimitInMb: 100, conversionLimitInMb: 100,
convertCbxToEpub: false, convertCbxToEpub: false,
conversionImageCompressionPercentage: 85, conversionImageCompressionPercentage: 85,
@@ -110,6 +110,16 @@ export class KoboSyncSettingsComponent implements OnInit {
protected hasHydratedKoboAdmin = false; protected hasHydratedKoboAdmin = false;
private readonly syncKepubSettingEffect = effect(() => {
const user = this.userService.currentUser();
const settings = this.appSettingsService.appSettings();
if (!user?.permissions.canSyncKobo || !settings) {
return;
}
this.koboSettings.convertToKepub = settings.koboSettings?.convertToKepub ?? true;
});
private readonly syncAdminSettingsEffect = effect(() => { private readonly syncAdminSettingsEffect = effect(() => {
const user = this.userService.currentUser(); const user = this.userService.currentUser();
const settings = this.appSettingsService.appSettings(); const settings = this.appSettingsService.appSettings();
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "", "twoWaySyncLabel": "",
"twoWaySyncDesc": "", "twoWaySyncDesc": "",
"twoWaySyncNote": "", "twoWaySyncNote": "",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "", "twoWaySyncEnabled": "",
"twoWaySyncDisabled": "", "twoWaySyncDisabled": "",
"autoAddEnabled": "", "autoAddEnabled": "",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Bidirektionale Lesefortschrittssynchronisierung", "twoWaySyncLabel": "Bidirektionale Lesefortschrittssynchronisierung",
"twoWaySyncDesc": "Aktivieren Sie die bidirektionale Synchronisierung zwischen Grimmorys Web-Reader und Ihrem Kobo-Gerät. Der Lesefortschritt auf beiden Plattformen wird gegenseitig übernommen.", "twoWaySyncDesc": "Aktivieren Sie die bidirektionale Synchronisierung zwischen Grimmorys Web-Reader und Ihrem Kobo-Gerät. Der Lesefortschritt auf beiden Plattformen wird gegenseitig übernommen.",
"twoWaySyncNote": "Hinweis: Aufgrund unterschiedlicher Positionsformate ist die Synchronisierungsgenauigkeit bestmöglich. In den meisten Fällen ist der Fortschritt auf Kapitelebene genau.", "twoWaySyncNote": "Hinweis: Aufgrund unterschiedlicher Positionsformate ist die Synchronisierungsgenauigkeit bestmöglich. In den meisten Fällen ist der Fortschritt auf Kapitelebene genau.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Bidirektionale Fortschrittssynchronisierung aktiviert", "twoWaySyncEnabled": "Bidirektionale Fortschrittssynchronisierung aktiviert",
"twoWaySyncDisabled": "Bidirektionale Fortschrittssynchronisierung deaktiviert", "twoWaySyncDisabled": "Bidirektionale Fortschrittssynchronisierung deaktiviert",
"autoAddEnabled": "Neue Bücher werden automatisch zum Kobo-Regal hinzugefügt", "autoAddEnabled": "Neue Bücher werden automatisch zum Kobo-Regal hinzugefügt",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Two-Way Reading Progress Sync", "twoWaySyncLabel": "Two-Way Reading Progress Sync",
"twoWaySyncDesc": "Enable bidirectional sync between Grimmory's web reader and your Kobo device. Reading progress made on either platform will be reflected on the other.", "twoWaySyncDesc": "Enable bidirectional sync between Grimmory's web reader and your Kobo device. Reading progress made on either platform will be reflected on the other.",
"twoWaySyncNote": "Note: Due to different position formats, sync accuracy is best-effort. In most cases progress will be accurate to the chapter level.", "twoWaySyncNote": "Note: Due to different position formats, sync accuracy is best-effort. In most cases progress will be accurate to the chapter level.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Two-way progress sync enabled", "twoWaySyncEnabled": "Two-way progress sync enabled",
"twoWaySyncDisabled": "Two-way progress sync disabled", "twoWaySyncDisabled": "Two-way progress sync disabled",
"autoAddEnabled": "New books will be automatically added to Kobo shelf", "autoAddEnabled": "New books will be automatically added to Kobo shelf",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Sincronización bidireccional del progreso de lectura", "twoWaySyncLabel": "Sincronización bidireccional del progreso de lectura",
"twoWaySyncDesc": "Habilita la sincronización bidireccional entre el lector web de Grimmory y tu dispositivo Kobo. El progreso de lectura realizado en cualquiera de las plataformas se reflejará en la otra.", "twoWaySyncDesc": "Habilita la sincronización bidireccional entre el lector web de Grimmory y tu dispositivo Kobo. El progreso de lectura realizado en cualquiera de las plataformas se reflejará en la otra.",
"twoWaySyncNote": "Nota: Debido a los diferentes formatos de posición, la precisión de la sincronización es aproximada. En la mayoría de los casos, el progreso será preciso a nivel de capítulo.", "twoWaySyncNote": "Nota: Debido a los diferentes formatos de posición, la precisión de la sincronización es aproximada. En la mayoría de los casos, el progreso será preciso a nivel de capítulo.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Sincronización bidireccional de progreso habilitada", "twoWaySyncEnabled": "Sincronización bidireccional de progreso habilitada",
"twoWaySyncDisabled": "Sincronización bidireccional de progreso deshabilitada", "twoWaySyncDisabled": "Sincronización bidireccional de progreso deshabilitada",
"autoAddEnabled": "Los libros nuevos se añadirán automáticamente al estante Kobo", "autoAddEnabled": "Los libros nuevos se añadirán automáticamente al estante Kobo",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Synchronisation bidirectionnelle de la progression", "twoWaySyncLabel": "Synchronisation bidirectionnelle de la progression",
"twoWaySyncDesc": "Activez la synchronisation bidirectionnelle entre le lecteur web de Grimmory et votre appareil Kobo. La progression de lecture effectuée sur l'une ou l'autre plateforme sera reflétée sur l'autre.", "twoWaySyncDesc": "Activez la synchronisation bidirectionnelle entre le lecteur web de Grimmory et votre appareil Kobo. La progression de lecture effectuée sur l'une ou l'autre plateforme sera reflétée sur l'autre.",
"twoWaySyncNote": "Note : En raison de formats de position différents, la précision de la synchronisation est approximative. Dans la plupart des cas, la progression sera précise au niveau du chapitre.", "twoWaySyncNote": "Note : En raison de formats de position différents, la précision de la synchronisation est approximative. Dans la plupart des cas, la progression sera précise au niveau du chapitre.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Synchronisation bidirectionnelle de la progression activée", "twoWaySyncEnabled": "Synchronisation bidirectionnelle de la progression activée",
"twoWaySyncDisabled": "Synchronisation bidirectionnelle de la progression désactivée", "twoWaySyncDisabled": "Synchronisation bidirectionnelle de la progression désactivée",
"autoAddEnabled": "Les nouveaux livres seront automatiquement ajoutés à l'étagère Kobo", "autoAddEnabled": "Les nouveaux livres seront automatiquement ajoutés à l'étagère Kobo",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Dvosmjerna sinkronizacija napretka čitanja", "twoWaySyncLabel": "Dvosmjerna sinkronizacija napretka čitanja",
"twoWaySyncDesc": "Omogući dvosmjernu sinkronizaciju između Grimmory web čitača i vašeg Kobo uređaja. Napredak čitanja na bilo kojoj platformi odrazit će se na drugoj.", "twoWaySyncDesc": "Omogući dvosmjernu sinkronizaciju između Grimmory web čitača i vašeg Kobo uređaja. Napredak čitanja na bilo kojoj platformi odrazit će se na drugoj.",
"twoWaySyncNote": "Napomena: Zbog različitih formata pozicije, točnost sinkronizacije je na razini najboljeg napora. U većini slučajeva napredak će biti točan na razini poglavlja.", "twoWaySyncNote": "Napomena: Zbog različitih formata pozicije, točnost sinkronizacije je na razini najboljeg napora. U većini slučajeva napredak će biti točan na razini poglavlja.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Dvosmjerna sinkronizacija napretka omogućena", "twoWaySyncEnabled": "Dvosmjerna sinkronizacija napretka omogućena",
"twoWaySyncDisabled": "Dvosmjerna sinkronizacija napretka onemogućena", "twoWaySyncDisabled": "Dvosmjerna sinkronizacija napretka onemogućena",
"autoAddEnabled": "Nove knjige će se automatski dodavati na Kobo policu", "autoAddEnabled": "Nove knjige će se automatski dodavati na Kobo policu",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "", "twoWaySyncLabel": "",
"twoWaySyncDesc": "", "twoWaySyncDesc": "",
"twoWaySyncNote": "", "twoWaySyncNote": "",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "", "twoWaySyncEnabled": "",
"twoWaySyncDisabled": "", "twoWaySyncDisabled": "",
"autoAddEnabled": "", "autoAddEnabled": "",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "", "twoWaySyncLabel": "",
"twoWaySyncDesc": "", "twoWaySyncDesc": "",
"twoWaySyncNote": "", "twoWaySyncNote": "",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "", "twoWaySyncEnabled": "",
"twoWaySyncDisabled": "", "twoWaySyncDisabled": "",
"autoAddEnabled": "", "autoAddEnabled": "",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Sincronizzazione bidirezionale progresso di lettura", "twoWaySyncLabel": "Sincronizzazione bidirezionale progresso di lettura",
"twoWaySyncDesc": "Abilita la sincronizzazione bidirezionale tra il lettore web di Grimmory e il tuo dispositivo Kobo. Il progresso di lettura effettuato su una delle piattaforme verrà riflesso sull'altra.", "twoWaySyncDesc": "Abilita la sincronizzazione bidirezionale tra il lettore web di Grimmory e il tuo dispositivo Kobo. Il progresso di lettura effettuato su una delle piattaforme verrà riflesso sull'altra.",
"twoWaySyncNote": "Nota: A causa dei diversi formati di posizione, la precisione della sincronizzazione è basata sul miglior risultato possibile. Nella maggior parte dei casi il progresso sarà preciso a livello di capitolo.", "twoWaySyncNote": "Nota: A causa dei diversi formati di posizione, la precisione della sincronizzazione è basata sul miglior risultato possibile. Nella maggior parte dei casi il progresso sarà preciso a livello di capitolo.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Sincronizzazione bidirezionale del progresso abilitata", "twoWaySyncEnabled": "Sincronizzazione bidirezionale del progresso abilitata",
"twoWaySyncDisabled": "Sincronizzazione bidirezionale del progresso disabilitata", "twoWaySyncDisabled": "Sincronizzazione bidirezionale del progresso disabilitata",
"autoAddEnabled": "I nuovi libri verranno automaticamente aggiunti allo scaffale Kobo", "autoAddEnabled": "I nuovi libri verranno automaticamente aggiunti allo scaffale Kobo",
+4 -2
View File
@@ -62,8 +62,8 @@
"adminSettings": "管理者設定", "adminSettings": "管理者設定",
"adminSettingsDesc": "このサーバーのすべてのユーザーに影響する高度なKobo同期設定を構成します。", "adminSettingsDesc": "このサーバーのすべてのユーザーに影響する高度なKobo同期設定を構成します。",
"convertKepub": "KEPUBに変換", "convertKepub": "KEPUBに変換",
"convertKepubPros": "KEPUB形式により、より良いタイポグラフィ、読書統計、高速なページめくりなどのKobo拡張機能が有効になります。", "convertKepubPros": "KEPUB format enables enhanced Kobo features like better typography, reading stats, and faster page turns. Required for reading progress sync to work.",
"convertKepubCons": "変換には追加の処理時間がかかり、複雑なレイアウトでは失敗する場合があります。以下のサイズ制限を超える本は自動的に変換をスキップします。", "convertKepubCons": "Conversion adds processing time during download. Books over the size limit below will skip conversion and sync as regular EPUB without progress tracking.",
"conversionSizeLimit": "変換サイズ制限: {{value}} MB", "conversionSizeLimit": "変換サイズ制限: {{value}} MB",
"conversionSizeLimitDesc": "大きなファイル(100MB以上)は変換タイムアウトやサーバー負荷を引き起こす可能性があります。制限を低くすると同期が高速になりますが、大きな本の変換がスキップされる場合があります。", "conversionSizeLimitDesc": "大きなファイル(100MB以上)は変換タイムアウトやサーバー負荷を引き起こす可能性があります。制限を低くすると同期が高速になりますが、大きな本の変換がスキップされる場合があります。",
"conversionSizeLimitRec": "ほとんどのライブラリでは50~100MB。非常に大きな本はこの設定に関係なく通常のEPUBとして同期されます。", "conversionSizeLimitRec": "ほとんどのライブラリでは50~100MB。非常に大きな本はこの設定に関係なく通常のEPUBとして同期されます。",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "双方向読書進捗同期", "twoWaySyncLabel": "双方向読書進捗同期",
"twoWaySyncDesc": "GrimmoryのWebリーダーとKoboデバイス間の双方向同期を有効にします。どちらのプラットフォームでの読書進捗も、もう一方に反映されます。", "twoWaySyncDesc": "GrimmoryのWebリーダーとKoboデバイス間の双方向同期を有効にします。どちらのプラットフォームでの読書進捗も、もう一方に反映されます。",
"twoWaySyncNote": "注意:位置形式が異なるため、同期精度はベストエフォートです。ほとんどの場合、チャプターレベルで正確になります。", "twoWaySyncNote": "注意:位置形式が異なるため、同期精度はベストエフォートです。ほとんどの場合、チャプターレベルで正確になります。",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "双方向進捗同期が有効になりました", "twoWaySyncEnabled": "双方向進捗同期が有効になりました",
"twoWaySyncDisabled": "双方向進捗同期が無効になりました", "twoWaySyncDisabled": "双方向進捗同期が無効になりました",
"autoAddEnabled": "新しい本はKoboシェルフに自動的に追加されます", "autoAddEnabled": "新しい本はKoboシェルフに自動的に追加されます",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "", "twoWaySyncLabel": "",
"twoWaySyncDesc": "", "twoWaySyncDesc": "",
"twoWaySyncNote": "", "twoWaySyncNote": "",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "", "twoWaySyncEnabled": "",
"twoWaySyncDisabled": "", "twoWaySyncDisabled": "",
"autoAddEnabled": "", "autoAddEnabled": "",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Dwukierunkowa synchronizacja postępu czytania", "twoWaySyncLabel": "Dwukierunkowa synchronizacja postępu czytania",
"twoWaySyncDesc": "Włącz dwukierunkową synchronizację między czytnikiem internetowym Grimmory a urządzeniem Kobo. Postęp czytania z jednej platformy będzie widoczny na drugiej.", "twoWaySyncDesc": "Włącz dwukierunkową synchronizację między czytnikiem internetowym Grimmory a urządzeniem Kobo. Postęp czytania z jednej platformy będzie widoczny na drugiej.",
"twoWaySyncNote": "Uwaga: Ze względu na różne formaty pozycji, dokładność synchronizacji jest w najlepszym przypadku przybliżona. W większości przypadków postęp będzie dokładny na poziomie rozdziałów.", "twoWaySyncNote": "Uwaga: Ze względu na różne formaty pozycji, dokładność synchronizacji jest w najlepszym przypadku przybliżona. W większości przypadków postęp będzie dokładny na poziomie rozdziałów.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Dwukierunkowa synchronizacja postępu włączona", "twoWaySyncEnabled": "Dwukierunkowa synchronizacja postępu włączona",
"twoWaySyncDisabled": "Dwukierunkowa synchronizacja postępu wyłączona", "twoWaySyncDisabled": "Dwukierunkowa synchronizacja postępu wyłączona",
"autoAddEnabled": "Nowe książki będą automatycznie dodawane do półki Kobo", "autoAddEnabled": "Nowe książki będą automatycznie dodawane do półki Kobo",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Sincronização Bidirecional de Progresso de Leitura", "twoWaySyncLabel": "Sincronização Bidirecional de Progresso de Leitura",
"twoWaySyncDesc": "Ative a sincronização bidirecional entre o leitor web do Grimmory e o seu dispositivo Kobo. O progresso de leitura feito em qualquer plataforma será refletido na outra.", "twoWaySyncDesc": "Ative a sincronização bidirecional entre o leitor web do Grimmory e o seu dispositivo Kobo. O progresso de leitura feito em qualquer plataforma será refletido na outra.",
"twoWaySyncNote": "Nota: Devido a formatos de posição diferentes, a precisão da sincronização é aproximada. Na maioria dos casos, o progresso será preciso ao nível de capítulo.", "twoWaySyncNote": "Nota: Devido a formatos de posição diferentes, a precisão da sincronização é aproximada. Na maioria dos casos, o progresso será preciso ao nível de capítulo.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Sincronização bidirecional de progresso ativada", "twoWaySyncEnabled": "Sincronização bidirecional de progresso ativada",
"twoWaySyncDisabled": "Sincronização bidirecional de progresso desativada", "twoWaySyncDisabled": "Sincronização bidirecional de progresso desativada",
"autoAddEnabled": "Novos livros serão adicionados automaticamente à prateleira Kobo", "autoAddEnabled": "Novos livros serão adicionados automaticamente à prateleira Kobo",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Двунаправленная синхронизация прогресса чтения", "twoWaySyncLabel": "Двунаправленная синхронизация прогресса чтения",
"twoWaySyncDesc": "Включить двунаправленную синхронизацию между веб-читалкой Grimmory и Вашим устройством Kobo. Прогресс чтения на любой из платформ будет отражаться на другой.", "twoWaySyncDesc": "Включить двунаправленную синхронизацию между веб-читалкой Grimmory и Вашим устройством Kobo. Прогресс чтения на любой из платформ будет отражаться на другой.",
"twoWaySyncNote": "Примечание: из-за различий форматов позиции точность синхронизации обеспечивается на уровне «лучших усилий». В большинстве случаев прогресс будет точен на уровне главы.", "twoWaySyncNote": "Примечание: из-за различий форматов позиции точность синхронизации обеспечивается на уровне «лучших усилий». В большинстве случаев прогресс будет точен на уровне главы.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Двунаправленная синхронизация прогресса включена", "twoWaySyncEnabled": "Двунаправленная синхронизация прогресса включена",
"twoWaySyncDisabled": "Двунаправленная синхронизация прогресса отключена", "twoWaySyncDisabled": "Двунаправленная синхронизация прогресса отключена",
"autoAddEnabled": "Новые книги будут автоматически добавляться на полку Kobo", "autoAddEnabled": "Новые книги будут автоматически добавляться на полку Kobo",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "", "twoWaySyncLabel": "",
"twoWaySyncDesc": "", "twoWaySyncDesc": "",
"twoWaySyncNote": "", "twoWaySyncNote": "",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "", "twoWaySyncEnabled": "",
"twoWaySyncDisabled": "", "twoWaySyncDisabled": "",
"autoAddEnabled": "", "autoAddEnabled": "",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Dvosmerna sinhronizacija napredka branja", "twoWaySyncLabel": "Dvosmerna sinhronizacija napredka branja",
"twoWaySyncDesc": "Omogoči dvosmerno sinhronizacijo med spletnim bralnikom Grimmory in tvojo napravo Kobo. Napredek na kateri koli platformi se bo odrazil na drugi.", "twoWaySyncDesc": "Omogoči dvosmerno sinhronizacijo med spletnim bralnikom Grimmory in tvojo napravo Kobo. Napredek na kateri koli platformi se bo odrazil na drugi.",
"twoWaySyncNote": "Opomba: Zaradi različnih formatov lokacij je natančnost sinhronizacije po principu \"najboljšega truda\". V večini primerov bo napredek natančen na nivoju poglavja.", "twoWaySyncNote": "Opomba: Zaradi različnih formatov lokacij je natančnost sinhronizacije po principu \"najboljšega truda\". V večini primerov bo napredek natančen na nivoju poglavja.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Dvosmerna sinhronizacija napredka omogočena", "twoWaySyncEnabled": "Dvosmerna sinhronizacija napredka omogočena",
"twoWaySyncDisabled": "Dvosmerna sinhronizacija napredka onemogočena", "twoWaySyncDisabled": "Dvosmerna sinhronizacija napredka onemogočena",
"autoAddEnabled": "Nove knjige bodo samodejno dodane na polico Kobo", "autoAddEnabled": "Nove knjige bodo samodejno dodane na polico Kobo",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Dubbelriktad läsframstegssynk", "twoWaySyncLabel": "Dubbelriktad läsframstegssynk",
"twoWaySyncDesc": "Aktivera dubbelriktad synk mellan Grimmorys webbläsare och din Kobo-enhet. Läsframsteg gjorda på endera plattformen reflekteras på den andra.", "twoWaySyncDesc": "Aktivera dubbelriktad synk mellan Grimmorys webbläsare och din Kobo-enhet. Läsframsteg gjorda på endera plattformen reflekteras på den andra.",
"twoWaySyncNote": "Obs: På grund av olika positionsformat är synknoggrannheten bäst-ansträngning. I de flesta fall är framstegen korrekta på kapitelnivå.", "twoWaySyncNote": "Obs: På grund av olika positionsformat är synknoggrannheten bäst-ansträngning. I de flesta fall är framstegen korrekta på kapitelnivå.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Dubbelriktad framstegssynk aktiverad", "twoWaySyncEnabled": "Dubbelriktad framstegssynk aktiverad",
"twoWaySyncDisabled": "Dubbelriktad framstegssynk inaktiverad", "twoWaySyncDisabled": "Dubbelriktad framstegssynk inaktiverad",
"autoAddEnabled": "Nya böcker läggs automatiskt till på Kobo-hyllan", "autoAddEnabled": "Nya böcker läggs automatiskt till på Kobo-hyllan",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "Двостороння синхронізація прогресу читання", "twoWaySyncLabel": "Двостороння синхронізація прогресу читання",
"twoWaySyncDesc": "Увімкніть двосторонню синхронізацію між веб-рідером Grimmory та вашим пристроєм Kobo. Прогрес читання, зроблений на будь-якій платформі, буде відображений на іншій.", "twoWaySyncDesc": "Увімкніть двосторонню синхронізацію між веб-рідером Grimmory та вашим пристроєм Kobo. Прогрес читання, зроблений на будь-якій платформі, буде відображений на іншій.",
"twoWaySyncNote": "Примітка: через різні формати позицій точність синхронізації є найкращим можливим наближенням. У більшості випадків прогрес буде точним до рівня розділу.", "twoWaySyncNote": "Примітка: через різні формати позицій точність синхронізації є найкращим можливим наближенням. У більшості випадків прогрес буде точним до рівня розділу.",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "Двосторонню синхронізацію прогресу увімкнено", "twoWaySyncEnabled": "Двосторонню синхронізацію прогресу увімкнено",
"twoWaySyncDisabled": "Двосторонню синхронізацію прогресу вимкнено", "twoWaySyncDisabled": "Двосторонню синхронізацію прогресу вимкнено",
"autoAddEnabled": "Нові книги автоматично додаватимуться на полицю Kobo", "autoAddEnabled": "Нові книги автоматично додаватимуться на полицю Kobo",
@@ -97,6 +97,8 @@
"twoWaySyncLabel": "双向阅读进度同步", "twoWaySyncLabel": "双向阅读进度同步",
"twoWaySyncDesc": "启用 Grimmory 网页阅读器与 Kobo 设备之间的双向同步。在任一平台上的阅读进度都将反映到另一个平台。", "twoWaySyncDesc": "启用 Grimmory 网页阅读器与 Kobo 设备之间的双向同步。在任一平台上的阅读进度都将反映到另一个平台。",
"twoWaySyncNote": "注意:由于位置格式不同,同步精度是尽力而为的。大多数情况下进度将精确到章节级别。", "twoWaySyncNote": "注意:由于位置格式不同,同步精度是尽力而为的。大多数情况下进度将精确到章节级别。",
"twoWaySyncKepubWarning": "KEPUB conversion is currently disabled. Two-way progress sync requires KEPUB conversion to be enabled by an administrator.",
"twoWaySyncKepubWarningAdmin": "KEPUB conversion is currently disabled. Enable it in the Administrator Settings below for two-way progress sync to work.",
"twoWaySyncEnabled": "双向进度同步已启用", "twoWaySyncEnabled": "双向进度同步已启用",
"twoWaySyncDisabled": "双向进度同步已禁用", "twoWaySyncDisabled": "双向进度同步已禁用",
"autoAddEnabled": "新图书将自动添加到 Kobo 书架", "autoAddEnabled": "新图书将自动添加到 Kobo 书架",