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
@NoArgsConstructor
public class EpubProgress {
@NotNull
String cfi;
String href;
Float contentSourceProgressPercent;
@NotNull
Float percentage;
String ttsPositionCfi;
@@ -7,5 +7,6 @@ public record BookFileProgress(
String positionData,
String positionHref,
@NotNull Float progressPercent,
String ttsPositionCfi) {
String ttsPositionCfi,
Float contentSourceProgressPercent) {
}
@@ -14,7 +14,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor(onConstructor_ = @JsonCreator)
public class KoboSettings {
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
private boolean convertToKepub = false;
private boolean convertToKepub = true;
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
private int conversionLimitInMb = 100;
@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")
private Float progressPercent;
@Column(name = "content_source_progress_percent")
private Float contentSourceProgressPercent;
@Column(name = "tts_position_cfi", length = 1000)
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
);
@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
@Transactional
@Query("""
@@ -311,7 +311,7 @@ public class SettingPersistenceHelper {
public KoboSettings getDefaultKoboSettings() {
return KoboSettings.builder()
.convertToKepub(false)
.convertToKepub(true)
.conversionLimitInMb(100)
.convertCbxToEpub(false)
.conversionLimitInMbForCbx(100)
@@ -13,6 +13,7 @@ import org.booklore.repository.BookRepository;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.kobo.CbxConversionService;
import org.booklore.service.kobo.KepubConversionService;
import org.booklore.service.kobo.KoboSpanMapService;
import org.booklore.util.FileUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
@@ -45,6 +46,7 @@ public class BookDownloadService {
private final BookFileRepository bookFileRepository;
private final KepubConversionService kepubConversionService;
private final CbxConversionService cbxConversionService;
private final KoboSpanMapService koboSpanMapService;
private final AppSettingService appSettingService;
public ResponseEntity<Resource> downloadBook(Long bookId) {
@@ -258,7 +260,7 @@ public class BookDownloadService {
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;
int compressionPercentage = koboSettings.getConversionImageCompressionPercentage();
@@ -280,6 +282,11 @@ public class BookDownloadService {
if (convertEpubToKepub) {
fileToSend = kepubConversionService.convertEpubToKepub(inputFile, tempDir.toFile(),
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);
@@ -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.MagicShelfRepository;
import org.booklore.repository.ShelfRepository;
import org.booklore.repository.UserBookFileProgressRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.book.BookQueryService;
@@ -43,6 +44,7 @@ public class KoboEntitlementService {
private final AppSettingService appSettingService;
private final KoboCompatibilityService koboCompatibilityService;
private final UserBookProgressRepository progressRepository;
private final UserBookFileProgressRepository fileProgressRepository;
private final KoboReadingStateRepository readingStateRepository;
private final KoboReadingStateMapper readingStateMapper;
private final AuthenticationService authenticationService;
@@ -51,6 +53,7 @@ public class KoboEntitlementService {
private final MagicShelfRepository magicShelfRepository;
private final MagicShelfBookService magicShelfBookService;
private final KoboSettingsService koboSettingsService;
private final KoboSpanMapService koboSpanMapService;
public List<NewEntitlement> generateNewEntitlements(Set<Long> bookIds, String token) {
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
@@ -108,9 +111,40 @@ public class KoboEntitlementService {
public List<ChangedReadingState> generateChangedReadingStates(List<UserBookProgressEntity> progressEntries) {
OffsetDateTime now = getCurrentUtc();
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()
.map(progress -> buildChangedReadingState(progress, timestamp, now))
.map(progress -> buildChangedReadingState(
progress,
fileProgressByFileId.get(syncedEpubFileIdsByBookId.get(progress.getBook().getId())),
timestamp,
now,
spanMapsByFileId))
.toList();
}
@@ -180,12 +214,16 @@ public class KoboEntitlementService {
.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());
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
KoboReadingState.CurrentBookmark bookmark = (progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
? readingStateBuilder.buildBookmarkFromProgress(progress, now)
? readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress, now, preloadedMaps)
: readingStateBuilder.buildEmptyBookmark(now);
KoboReadingState readingState = KoboReadingState.builder()
@@ -218,14 +256,15 @@ public class KoboEntitlementService {
.orElse(null);
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();
KoboReadingState.CurrentBookmark webReaderBookmark = twoWaySync
? userProgress
.filter(progress -> progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null)
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now))
.filter(readingStateBuilder::shouldUseWebReaderProgress)
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress, now))
.orElse(null)
: null;
@@ -235,7 +274,7 @@ public class KoboEntitlementService {
? existingState.getCurrentBookmark()
: userProgress
.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));
KoboReadingState.StatusInfo statusInfo = userProgress
@@ -257,6 +296,14 @@ public class KoboEntitlementService {
.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) {
OffsetDateTime now = getCurrentUtc();
OffsetDateTime createdOn = getCreatedOn(book);
@@ -333,14 +380,12 @@ public class KoboEntitlementService {
boolean isEpubFile = primaryFile.getBookType() == BookFileType.EPUB;
boolean isCbxFile = primaryFile.getBookType() == BookFileType.CBX;
if (koboSettings != null) {
if (isEpubFile && primaryFile.isFixedLayout()) {
bookFormat = KoboBookFormat.EPUB3FL;
} else if (isEpubFile && koboSettings.isConvertToKepub()) {
bookFormat = KoboBookFormat.KEPUB;
} else if (isCbxFile && koboSettings.isConvertCbxToEpub()) {
bookFormat = KoboBookFormat.EPUB3;
}
if (isEpubFile && primaryFile.isFixedLayout()) {
bookFormat = KoboBookFormat.EPUB3FL;
} else if (isEpubFile && koboSettings != null && koboSettings.isConvertToKepub()) {
bookFormat = KoboBookFormat.KEPUB;
} else if (koboSettings != null && isCbxFile && koboSettings.isConvertCbxToEpub()) {
bookFormat = KoboBookFormat.EPUB3;
}
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;
if (prevSnapshot.isPresent()) {
int maxRemaining = 5;
int maxRemaining = 100;
List<KoboSnapshotBookEntity> removedAll = new ArrayList<>();
List<KoboSnapshotBookEntity> changedAll = new ArrayList<>();
@@ -123,7 +123,7 @@ public class KoboLibrarySyncService {
entitlements.addAll(entitlementService.generateTags());
}
} else {
int maxRemaining = 5;
int maxRemaining = 100;
List<KoboSnapshotBookEntity> snapshotBookEntities = new ArrayList<>();
while (maxRemaining > 0) {
Page<KoboSnapshotBookEntity> page = koboLibrarySnapshotService.getUnsyncedBooks(currSnapshot.getId(), PageRequest.of(0, maxRemaining));
@@ -230,7 +230,7 @@ public class KoboLibrarySyncService {
}
if (koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()
&& progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null) {
&& progress.getEpubProgressPercent() != null) {
Instant sentTime = progress.getKoboProgressSentTime();
Instant lastReadTime = progress.getLastReadTime();
if (lastReadTime != null && (sentTime == null || lastReadTime.isAfter(sentTime))) {
@@ -2,21 +2,30 @@ package org.booklore.service.kobo;
import lombok.RequiredArgsConstructor;
import org.booklore.model.dto.kobo.KoboReadingState;
import org.booklore.model.entity.UserBookFileProgressEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.KoboReadStatus;
import org.booklore.model.enums.ReadStatus;
import org.springframework.stereotype.Component;
import org.booklore.model.dto.kobo.KoboSpanPositionMap;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Optional;
@Component
@RequiredArgsConstructor
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 KoboBookmarkLocationResolver bookmarkLocationResolver;
public KoboReadingState.CurrentBookmark buildEmptyBookmark(OffsetDateTime timestamp) {
return KoboReadingState.CurrentBookmark.builder()
@@ -24,35 +33,80 @@ public class KoboReadingStateBuilder {
.build();
}
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress) {
return buildBookmarkFromProgress(progress, null);
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress) {
return buildBookmarkFromProgress(progress, fileProgress, null, null);
}
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) {
if (isWebReaderNewer(progress)) {
return buildBookmarkFromWebReaderProgress(progress, defaultTime);
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress,
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) {
return koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()
&& progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null;
public boolean shouldUseWebReaderProgress(UserBookProgressEntity progress) {
if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
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())
.map(this::formatTimestamp)
.or(() -> Optional.ofNullable(defaultTime).map(OffsetDateTime::toString))
.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()
.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)
.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())
.map(koboLocation -> KoboReadingState.CurrentBookmark.Location.builder()
.value(koboLocation)
@@ -70,13 +124,19 @@ public class KoboReadingStateBuilder {
.progressPercent(Optional.ofNullable(progress.getKoboProgressPercent())
.map(Math::round)
.orElse(null))
.contentSourceProgressPercent(Optional.ofNullable(fileProgress)
.map(UserBookFileProgressEntity::getContentSourceProgressPercent)
.map(Math::round)
.orElse(null))
.location(location)
.lastModified(lastModified)
.build();
}
public KoboReadingState buildReadingStateFromProgress(String entitlementId, UserBookProgressEntity progress) {
KoboReadingState.CurrentBookmark bookmark = buildBookmarkFromProgress(progress);
public KoboReadingState buildReadingStateFromProgress(String entitlementId,
UserBookProgressEntity progress,
UserBookFileProgressEntity fileProgress) {
KoboReadingState.CurrentBookmark bookmark = buildBookmarkFromProgress(progress, fileProgress);
String lastModified = bookmark.getLastModified();
KoboReadingState.StatusInfo statusInfo = buildStatusInfoFromProgress(progress, lastModified);
@@ -118,6 +178,6 @@ public class KoboReadingStateBuilder {
}
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.response.kobo.KoboReadingStateResponse;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.KoboReadingStateEntity;
import org.booklore.model.entity.UserBookFileProgressEntity;
@@ -117,9 +118,8 @@ public class KoboReadingStateService {
syncKoboProgressToUserBookProgress(savedState, userId);
return savedEntity;
return savedState;
})
.map(mapper::toDto)
.collect(Collectors.toList());
}
@@ -155,19 +155,11 @@ public class KoboReadingStateService {
}
try {
Long bookId = Long.parseLong(entitlementId);
UserBookFileProgressEntity fileProgress = findSyncedEpubFileProgress(userId, bookId).orElse(null);
progressRepository.findByUserIdAndBookId(userId, bookId)
.filter(progress -> progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null)
.ifPresent(progress -> {
KoboReadingState.CurrentBookmark existing = state.getCurrentBookmark();
KoboReadingState.CurrentBookmark webReaderBookmark = readingStateBuilder.buildBookmarkFromProgress(progress);
if (existing != null) {
existing.setProgressPercent(webReaderBookmark.getProgressPercent());
existing.setLastModified(webReaderBookmark.getLastModified());
} else {
state.setCurrentBookmark(webReaderBookmark);
}
});
.filter(readingStateBuilder::shouldUseWebReaderProgress)
.ifPresent(progress -> state.setCurrentBookmark(
readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress)));
} catch (NumberFormatException e) {
// Not a valid book ID, skip overlay
}
@@ -181,7 +173,10 @@ public class KoboReadingStateService {
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
return progressRepository.findByUserIdAndBookId(user.getId(), bookId)
.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) {
log.warn("Invalid entitlement ID format when constructing reading state: {}", entitlementId);
return Optional.empty();
@@ -213,7 +208,7 @@ public class KoboReadingStateService {
return newProgress;
});
Float prevousKoboProgressPercent = progress.getKoboProgressPercent();
Float previousKoboProgressPercent = progress.getKoboProgressPercent();
ReadStatus previousReadStatus = progress.getReadStatus();
KoboReadingState.CurrentBookmark bookmark = readingState.getCurrentBookmark();
@@ -231,23 +226,31 @@ public class KoboReadingStateService {
}
Instant now = Instant.now();
progress.setKoboProgressReceivedTime(now);
boolean koboApplied = crossPopulateEpubFieldsFromKobo(progress, bookmark, book, userId, now);
if (koboApplied) {
progress.setLastReadTime(now);
Instant bookmarkTime = bookmark != null ? parseTimestamp(bookmark.getLastModified()) : null;
Instant effectiveBookmarkTime = bookmarkTime != null ? bookmarkTime : now;
Optional<UserBookFileProgressEntity> existingFileProgress = findSyncedEpubFileProgress(userId, book);
boolean webReaderIsNewer = isWebReaderNewerThanBookmark(existingFileProgress.orElse(null), bookmarkTime);
if (bookmark != null && (bookmark.getProgressPercent() != null || bookmark.getLocation() != null)) {
progress.setKoboProgressReceivedTime(effectiveBookmarkTime);
}
if (progress.getKoboProgressPercent() != null) {
updateReadStatusFromKoboProgress(progress, now);
boolean koboApplied = crossPopulateEpubFieldsFromKobo(progress, bookmark, book,
existingFileProgress.orElse(null), bookmarkTime, effectiveBookmarkTime);
if (koboApplied) {
progress.setLastReadTime(effectiveBookmarkTime);
}
if (progress.getKoboProgressPercent() != null && !webReaderIsNewer) {
updateReadStatusFromKoboProgress(progress, effectiveBookmarkTime);
}
progressRepository.save(progress);
// 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
if (progress.getKoboProgressPercent() != null
&& (!progress.getKoboProgressPercent().equals(prevousKoboProgressPercent)
if (!webReaderIsNewer
&& progress.getKoboProgressPercent() != null
&& (!progress.getKoboProgressPercent().equals(previousKoboProgressPercent)
|| progress.getReadStatus() != previousReadStatus)) {
hardcoverSyncService.syncProgressToHardcover(book.getId(), progress.getKoboProgressPercent(), userId);
}
@@ -257,8 +260,11 @@ public class KoboReadingStateService {
}
private boolean crossPopulateEpubFieldsFromKobo(UserBookProgressEntity progress,
KoboReadingState.CurrentBookmark bookmark,
BookEntity book, Long userId, Instant now) {
KoboReadingState.CurrentBookmark bookmark,
BookEntity book,
UserBookFileProgressEntity existingFileProgress,
Instant bookmarkTime,
Instant effectiveBookmarkTime) {
if (bookmark == null || bookmark.getProgressPercent() == null) {
return false;
}
@@ -267,40 +273,65 @@ public class KoboReadingStateService {
return false;
}
UserBookFileProgressEntity fileProgress = book.getPrimaryBookFile() != null
? fileProgressRepository.findByUserIdAndBookFileId(userId, book.getPrimaryBookFile().getId()).orElse(null)
: null;
Instant bookmarkTime = parseTimestamp(bookmark.getLastModified());
boolean webReaderIsNewer = fileProgress != null
&& fileProgress.getLastReadTime() != null
boolean webReaderIsNewer = existingFileProgress != null
&& existingFileProgress.getLastReadTime() != null
&& bookmarkTime != null
&& fileProgress.getLastReadTime().isAfter(bookmarkTime);
&& existingFileProgress.getLastReadTime().isAfter(bookmarkTime);
if (webReaderIsNewer) {
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());
KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation();
if (location != null && location.getSource() != null) {
progress.setEpubProgressHref(location.getSource());
}
progress.setEpubProgress(null);
progress.setEpubProgressHref(location != null ? location.getSource() : null);
if (fileProgress != null) {
fileProgress.setProgressPercent(bookmark.getProgressPercent().floatValue());
if (location != null && location.getSource() != null) {
fileProgress.setPositionHref(location.getSource());
}
fileProgress.setContentSourceProgressPercent(bookmark.getContentSourceProgressPercent() != null
? bookmark.getContentSourceProgressPercent().floatValue()
: null);
fileProgress.setPositionData(null);
fileProgress.setLastReadTime(now);
fileProgress.setPositionHref(location != null ? location.getSource() : null);
fileProgress.setLastReadTime(effectiveBookmarkTime);
fileProgressRepository.save(fileProgress);
}
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) {
if (readingStates == null || readingStates.isEmpty()) {
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()
.cfi(fileProgress.getPositionData())
.href(fileProgress.getPositionHref())
.contentSourceProgressPercent(roundToOneDecimal(fileProgress.getContentSourceProgressPercent()))
.percentage(roundToOneDecimal(fileProgress.getProgressPercent()))
.ttsPositionCfi(fileProgress.getTtsPositionCfi())
.build());
@@ -303,6 +304,7 @@ public class ReadingProgressService {
entity.setPositionHref(fileProgress.positionHref());
entity.setProgressPercent(fileProgress.progressPercent());
entity.setTtsPositionCfi(fileProgress.ttsPositionCfi());
entity.setContentSourceProgressPercent(fileProgress.contentSourceProgressPercent());
entity.setLastReadTime(now);
userBookFileProgressRepository.save(entity);
@@ -317,6 +319,7 @@ public class ReadingProgressService {
entity.setUser(user);
entity.setBookFile(bookFile);
entity.setLastReadTime(now);
entity.setContentSourceProgressPercent(null);
switch (bookFile.getBookType()) {
case PDF -> {
@@ -9,17 +9,29 @@ import org.grimmory.epub4j.cfi.CfiConverter;
import org.grimmory.epub4j.cfi.XPointerResult;
import org.jsoup.Jsoup;
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 java.io.File;
import java.io.IOException;
import java.nio.file.Path;
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
@Service
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;
public EpubCfiService() {
@@ -30,9 +42,10 @@ public class EpubCfiService {
}
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);
return converter.cfiToXPointer(cfi);
return converter.cfiToXPointer(normalizedCfi);
}
public XPointerResult convertCfiToXPointer(Path epubPath, String cfi) {
@@ -74,11 +87,47 @@ public class EpubCfiService {
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) {
try {
int spineIndex = CfiConverter.extractSpineIndex(cfi);
String normalizedCfi = normalizeContentDocumentCfi(cfi);
int spineIndex = CfiConverter.extractSpineIndex(normalizedCfi);
CfiConverter converter = createConverter(epubFile, spineIndex);
return converter.validateCfi(cfi);
return converter.validateCfi(normalizedCfi);
} catch (Exception e) {
log.debug("CFI validation failed: {}", e.getMessage());
return false;
@@ -118,7 +167,7 @@ public class EpubCfiService {
return documentCache.get(cacheKey, key -> {
log.debug("Cache miss for epub spine: {} index {}", epubFile.getName(), spineIndex);
String html = EpubContentReader.getSpineItemContent(epubFile, spineIndex);
return Jsoup.parse(html);
return Jsoup.parse(html, "", Parser.htmlParser().setTrackPosition(true));
});
}
@@ -143,4 +192,120 @@ public class EpubCfiService {
public void clearCache() {
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) {
}
}