fix(kobo-sync): use KoboSpan for progress sync (#253)
This commit is contained in:
@@ -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("""
|
||||
|
||||
+1
-1
@@ -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) {
|
||||
}
|
||||
}
|
||||
|
||||
+2
@@ -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);
|
||||
|
||||
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);
|
||||
|
||||
@@ -92,7 +92,7 @@ class AppBookServiceProgressTest {
|
||||
mockBookWithLibrary(bookId, libraryId);
|
||||
|
||||
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);
|
||||
|
||||
@@ -118,7 +118,7 @@ class AppBookServiceProgressTest {
|
||||
mockBookWithLibrary(bookId, libraryId);
|
||||
|
||||
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));
|
||||
verify(bookService, never()).updateReadProgress(any());
|
||||
@@ -130,7 +130,7 @@ class AppBookServiceProgressTest {
|
||||
mockBookWithLibrary(bookId, libraryId);
|
||||
|
||||
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);
|
||||
|
||||
@@ -147,7 +147,7 @@ class AppBookServiceProgressTest {
|
||||
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.empty());
|
||||
|
||||
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));
|
||||
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.kobo.*;
|
||||
import org.booklore.model.entity.KoboReadingStateEntity;
|
||||
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.booklore.repository.KoboReadingStateRepository;
|
||||
import org.booklore.repository.UserBookFileProgressRepository;
|
||||
import org.booklore.repository.UserBookProgressRepository;
|
||||
import org.booklore.service.kobo.KoboEntitlementService;
|
||||
import org.booklore.service.kobo.KoboReadingStateBuilder;
|
||||
import org.booklore.service.kobo.KoboSettingsService;
|
||||
import org.booklore.service.kobo.KoboSpanMapService;
|
||||
import org.booklore.service.opds.MagicShelfBookService;
|
||||
import org.booklore.util.kobo.KoboUrlBuilder;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -55,6 +58,7 @@ import java.time.ZoneOffset;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -93,6 +97,9 @@ class KoboEntitlementServiceTest {
|
||||
@Mock
|
||||
private UserBookProgressRepository progressRepository;
|
||||
|
||||
@Mock
|
||||
private UserBookFileProgressRepository fileProgressRepository;
|
||||
|
||||
@Mock
|
||||
private KoboReadingStateRepository readingStateRepository;
|
||||
|
||||
@@ -105,6 +112,9 @@ class KoboEntitlementServiceTest {
|
||||
@Mock
|
||||
private KoboSettingsService koboSettingsService;
|
||||
|
||||
@Mock
|
||||
private KoboSpanMapService koboSpanMapService;
|
||||
|
||||
@InjectMocks
|
||||
private KoboEntitlementService koboEntitlementService;
|
||||
|
||||
@@ -113,7 +123,9 @@ class KoboEntitlementServiceTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
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
|
||||
@@ -180,6 +192,28 @@ class KoboEntitlementServiceTest {
|
||||
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) {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(id);
|
||||
@@ -204,7 +238,6 @@ class KoboEntitlementServiceTest {
|
||||
KoboSettings koboSettings = KoboSettings.builder()
|
||||
.convertCbxToEpub(true)
|
||||
.conversionLimitInMbForCbx(50)
|
||||
.convertToKepub(false)
|
||||
.conversionLimitInMb(50)
|
||||
.build();
|
||||
appSettings.setKoboSettings(koboSettings);
|
||||
@@ -506,6 +539,127 @@ class KoboEntitlementServiceTest {
|
||||
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
|
||||
@DisplayName("Should handle empty book IDs")
|
||||
void generateNewEntitlements_emptyIds() {
|
||||
@@ -563,6 +717,11 @@ class KoboEntitlementServiceTest {
|
||||
void generateChangedReadingStates_fromProgress() {
|
||||
BookEntity book = new BookEntity();
|
||||
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();
|
||||
progress.setBook(book);
|
||||
@@ -570,12 +729,19 @@ class KoboEntitlementServiceTest {
|
||||
progress.setReadStatus(ReadStatus.READING);
|
||||
|
||||
KoboSyncSettings settings = new KoboSyncSettings();
|
||||
settings.setTwoWayProgressSync(true);
|
||||
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()
|
||||
.progressPercent(50)
|
||||
.contentSourceProgressPercent(20)
|
||||
.build();
|
||||
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), any(OffsetDateTime.class)))
|
||||
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), eq(fileProgress), any(OffsetDateTime.class), anyMap()))
|
||||
.thenReturn(bookmark);
|
||||
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
|
||||
.thenReturn(KoboReadingState.StatusInfo.builder()
|
||||
@@ -590,9 +756,68 @@ class KoboEntitlementServiceTest {
|
||||
KoboReadingState state = result.getFirst().getChangedReadingState().getReadingState();
|
||||
assertEquals("1", state.getEntitlementId());
|
||||
assertNotNull(state.getCurrentBookmark());
|
||||
assertEquals(20, state.getCurrentBookmark().getContentSourceProgressPercent());
|
||||
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
|
||||
@DisplayName("Should use empty bookmark when no progress data exists")
|
||||
void generateChangedReadingStates_emptyBookmark() {
|
||||
@@ -637,7 +862,7 @@ class KoboEntitlementServiceTest {
|
||||
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(70)
|
||||
.build();
|
||||
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), any(OffsetDateTime.class)))
|
||||
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), isNull(), any(OffsetDateTime.class), anyMap()))
|
||||
.thenReturn(bookmark);
|
||||
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
|
||||
.thenReturn(KoboReadingState.StatusInfo.builder()
|
||||
@@ -682,4 +907,4 @@ class KoboEntitlementServiceTest {
|
||||
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.kobo.KoboReadingState;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
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.booklore.service.kobo.KoboBookmarkLocationResolver;
|
||||
import org.booklore.service.kobo.KoboReadingStateBuilder;
|
||||
import org.booklore.service.kobo.KoboSettingsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -27,6 +29,7 @@ import java.time.ZoneOffset;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@DisplayName("KoboReadingStateBuilder Tests")
|
||||
@@ -37,6 +40,9 @@ class KoboReadingStateBuilderTest {
|
||||
@Mock
|
||||
private KoboSettingsService koboSettingsService;
|
||||
|
||||
@Mock
|
||||
private KoboBookmarkLocationResolver bookmarkLocationResolver;
|
||||
|
||||
private KoboReadingStateBuilder builder;
|
||||
|
||||
@BeforeEach
|
||||
@@ -44,7 +50,8 @@ class KoboReadingStateBuilderTest {
|
||||
KoboSyncSettings settings = new KoboSyncSettings();
|
||||
settings.setTwoWayProgressSync(true);
|
||||
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
|
||||
@@ -186,19 +193,19 @@ class KoboReadingStateBuilderTest {
|
||||
void buildBookmarkFromProgress_WithLocation() {
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setKoboProgressPercent(75.5f);
|
||||
progress.setKoboLocation("epubcfi(/6/4[chap01ref]!/4/2/1:3)");
|
||||
progress.setKoboLocationType("EpubCfi");
|
||||
progress.setKoboLocationSource("Kobo");
|
||||
progress.setKoboLocation("kobo.12.18");
|
||||
progress.setKoboLocationType("KoboSpan");
|
||||
progress.setKoboLocationSource("OEBPS/chapter3.xhtml");
|
||||
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);
|
||||
assertEquals(76, bookmark.getProgressPercent()); // Rounded
|
||||
assertNotNull(bookmark.getLocation());
|
||||
assertEquals("epubcfi(/6/4[chap01ref]!/4/2/1:3)", bookmark.getLocation().getValue());
|
||||
assertEquals("EpubCfi", bookmark.getLocation().getType());
|
||||
assertEquals("Kobo", bookmark.getLocation().getSource());
|
||||
assertEquals("kobo.12.18", bookmark.getLocation().getValue());
|
||||
assertEquals("KoboSpan", bookmark.getLocation().getType());
|
||||
assertEquals("OEBPS/chapter3.xhtml", bookmark.getLocation().getSource());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -209,13 +216,161 @@ class KoboReadingStateBuilderTest {
|
||||
progress.setKoboLocation(null);
|
||||
progress.setKoboProgressReceivedTime(Instant.now());
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress);
|
||||
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, (UserBookFileProgressEntity) null);
|
||||
|
||||
assertNotNull(bookmark);
|
||||
assertEquals(50, bookmark.getProgressPercent());
|
||||
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
|
||||
@DisplayName("Should use default time when progress received time is null")
|
||||
void buildBookmarkFromProgress_UseDefaultTime() {
|
||||
@@ -224,7 +379,7 @@ class KoboReadingStateBuilderTest {
|
||||
progress.setKoboProgressReceivedTime(null);
|
||||
|
||||
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);
|
||||
assertEquals(defaultTime.toString(), bookmark.getLastModified());
|
||||
@@ -237,7 +392,7 @@ class KoboReadingStateBuilderTest {
|
||||
progress.setKoboProgressPercent(33.7f);
|
||||
progress.setKoboProgressReceivedTime(Instant.now());
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress);
|
||||
KoboReadingState.CurrentBookmark bookmark = builder.buildBookmarkFromProgress(progress, (UserBookFileProgressEntity) null);
|
||||
|
||||
assertEquals(34, bookmark.getProgressPercent()); // Rounded up
|
||||
}
|
||||
@@ -256,13 +411,13 @@ class KoboReadingStateBuilderTest {
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setBook(book);
|
||||
progress.setKoboProgressPercent(75f);
|
||||
progress.setKoboLocation("epubcfi(/6/4!)");
|
||||
progress.setKoboLocationType("EpubCfi");
|
||||
progress.setKoboLocationSource("Kobo");
|
||||
progress.setKoboLocation("kobo.1.1");
|
||||
progress.setKoboLocationType("KoboSpan");
|
||||
progress.setKoboLocationSource("OEBPS/CoverImage.xhtml");
|
||||
progress.setKoboProgressReceivedTime(Instant.parse("2025-11-26T10:00:00Z"));
|
||||
progress.setReadStatus(ReadStatus.READING);
|
||||
|
||||
KoboReadingState state = builder.buildReadingStateFromProgress("100", progress);
|
||||
KoboReadingState state = builder.buildReadingStateFromProgress("100", progress, null);
|
||||
|
||||
assertNotNull(state);
|
||||
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.KoboReadingStateEntity;
|
||||
import org.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.model.enums.KoboReadStatus;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.repository.BookRepository;
|
||||
@@ -112,6 +113,15 @@ class KoboReadingStateServiceTest {
|
||||
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
|
||||
@DisplayName("Should not overwrite existing finished date when syncing completed book")
|
||||
void testSyncKoboProgressToUserBookProgress_PreserveExistingFinishedDate() {
|
||||
@@ -248,9 +258,9 @@ class KoboReadingStateServiceTest {
|
||||
String entitlementId = "100";
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setKoboProgressPercent(75.5f);
|
||||
progress.setKoboLocation("epubcfi(/6/4[chap01ref]!/4/2/1:3)");
|
||||
progress.setKoboLocationType("EpubCfi");
|
||||
progress.setKoboLocationSource("Kobo");
|
||||
progress.setKoboLocation("kobo.12.18");
|
||||
progress.setKoboLocationType("KoboSpan");
|
||||
progress.setKoboLocationSource("OEBPS/chapter3.xhtml");
|
||||
progress.setKoboProgressReceivedTime(Instant.now());
|
||||
|
||||
KoboReadingState expectedState = KoboReadingState.builder()
|
||||
@@ -258,9 +268,9 @@ class KoboReadingStateServiceTest {
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(75)
|
||||
.location(KoboReadingState.CurrentBookmark.Location.builder()
|
||||
.value("epubcfi(/6/4[chap01ref]!/4/2/1:3)")
|
||||
.type("EpubCfi")
|
||||
.source("Kobo")
|
||||
.value("kobo.12.18")
|
||||
.type("KoboSpan")
|
||||
.source("OEBPS/chapter3.xhtml")
|
||||
.build())
|
||||
.build())
|
||||
.build();
|
||||
@@ -268,25 +278,26 @@ class KoboReadingStateServiceTest {
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
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);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
|
||||
|
||||
KoboReadingState state = result.getFirst();
|
||||
assertEquals(entitlementId, state.getEntitlementId());
|
||||
assertNotNull(state.getCurrentBookmark());
|
||||
assertEquals(75, state.getCurrentBookmark().getProgressPercent());
|
||||
assertNotNull(state.getCurrentBookmark().getLocation());
|
||||
assertEquals("epubcfi(/6/4[chap01ref]!/4/2/1:3)", state.getCurrentBookmark().getLocation().getValue());
|
||||
assertEquals("EpubCfi", state.getCurrentBookmark().getLocation().getType());
|
||||
assertEquals("Kobo", state.getCurrentBookmark().getLocation().getSource());
|
||||
|
||||
assertEquals("kobo.12.18", state.getCurrentBookmark().getLocation().getValue());
|
||||
assertEquals("KoboSpan", state.getCurrentBookmark().getLocation().getType());
|
||||
assertEquals("OEBPS/chapter3.xhtml", state.getCurrentBookmark().getLocation().getSource());
|
||||
|
||||
verify(repository).findByEntitlementIdAndUserId(entitlementId, 1L);
|
||||
verify(progressRepository, atLeastOnce()).findByUserIdAndBookId(1L, 100L);
|
||||
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress);
|
||||
verify(readingStateBuilder).buildReadingStateFromProgress(eq(entitlementId), eq(progress), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -369,7 +380,7 @@ class KoboReadingStateServiceTest {
|
||||
|
||||
UserBookProgressEntity savedProgress = progressCaptor.getValue();
|
||||
assertNull(savedProgress.getKoboProgressPercent());
|
||||
assertNotNull(savedProgress.getKoboProgressReceivedTime());
|
||||
assertNull(savedProgress.getKoboProgressReceivedTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -556,6 +567,7 @@ class KoboReadingStateServiceTest {
|
||||
void testGetReadingState_overlayWebReaderBookmark() {
|
||||
testSettings.setTwoWayProgressSync(true);
|
||||
String entitlementId = "100";
|
||||
BookFileEntity primaryFile = setPrimaryEpub(10L);
|
||||
|
||||
KoboReadingState existingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
@@ -563,9 +575,9 @@ class KoboReadingStateServiceTest {
|
||||
.progressPercent(30)
|
||||
.contentSourceProgressPercent(45)
|
||||
.location(KoboReadingState.CurrentBookmark.Location.builder()
|
||||
.value("epubcfi(/6/10)")
|
||||
.type("EpubCfi")
|
||||
.source("Kobo")
|
||||
.value("kobo.1.1")
|
||||
.type("KoboSpan")
|
||||
.source("OEBPS/CoverImage.xhtml")
|
||||
.build())
|
||||
.lastModified("2025-01-01T00:00:00Z")
|
||||
.build())
|
||||
@@ -580,21 +592,23 @@ class KoboReadingStateServiceTest {
|
||||
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));
|
||||
when(fileProgressRepository.findByUserIdAndBookFileId(1L, primaryFile.getId())).thenReturn(Optional.empty());
|
||||
|
||||
KoboReadingState.CurrentBookmark webBookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(65)
|
||||
.lastModified("2025-06-01T10:00:00Z")
|
||||
.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);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
KoboReadingState.CurrentBookmark bookmark = result.getFirst().getCurrentBookmark();
|
||||
assertEquals(65, bookmark.getProgressPercent());
|
||||
assertEquals(45, bookmark.getContentSourceProgressPercent());
|
||||
assertNotNull(bookmark.getLocation());
|
||||
assertEquals("epubcfi(/6/10)", bookmark.getLocation().getValue());
|
||||
assertNull(bookmark.getContentSourceProgressPercent());
|
||||
assertNull(bookmark.getLocation());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -619,30 +633,142 @@ class KoboReadingStateServiceTest {
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(30, result.getFirst().getCurrentBookmark().getProgressPercent());
|
||||
verify(readingStateBuilder, never()).buildBookmarkFromProgress(any());
|
||||
verify(readingStateBuilder, never()).buildBookmarkFromProgress(any(), any());
|
||||
}
|
||||
|
||||
@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() {
|
||||
testSettings.setTwoWayProgressSync(true);
|
||||
String entitlementId = "100";
|
||||
|
||||
BookFileEntity primaryFile = BookFileEntity.builder().id(10L).build();
|
||||
testBook.setBookFiles(List.of(primaryFile));
|
||||
BookFileEntity primaryFile = setPrimaryEpub(10L);
|
||||
|
||||
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
|
||||
existingProgress.setUser(testUserEntity);
|
||||
existingProgress.setBook(testBook);
|
||||
|
||||
KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder()
|
||||
.value("epubcfi(/6/8)")
|
||||
.type("EpubCfi")
|
||||
.source("chapter3.xhtml")
|
||||
.value("kobo.12.18")
|
||||
.type("KoboSpan")
|
||||
.source("OEBPS/chapter3.xhtml")
|
||||
.build();
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(55)
|
||||
.contentSourceProgressPercent(23)
|
||||
.location(location)
|
||||
.lastModified("2025-06-15T12:00:00Z")
|
||||
.build();
|
||||
@@ -660,17 +786,30 @@ class KoboReadingStateServiceTest {
|
||||
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, 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);
|
||||
when(progressRepository.save(captor.capture())).thenReturn(existingProgress);
|
||||
ArgumentCaptor<UserBookFileProgressEntity> fileProgressCaptor =
|
||||
ArgumentCaptor.forClass(UserBookFileProgressEntity.class);
|
||||
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
UserBookProgressEntity saved = captor.getValue();
|
||||
assertEquals(55f, saved.getEpubProgressPercent());
|
||||
assertEquals("chapter3.xhtml", saved.getEpubProgressHref());
|
||||
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
|
||||
@@ -711,14 +850,135 @@ class KoboReadingStateServiceTest {
|
||||
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
|
||||
@DisplayName("Should not cross-populate when web reader has newer progress")
|
||||
void testSyncKoboProgress_skipCrossPopulateWhenWebReaderNewer() {
|
||||
testSettings.setTwoWayProgressSync(true);
|
||||
String entitlementId = "100";
|
||||
|
||||
BookFileEntity primaryFile = BookFileEntity.builder().id(10L).build();
|
||||
testBook.setBookFiles(List.of(primaryFile));
|
||||
BookFileEntity primaryFile = setPrimaryEpub(10L);
|
||||
|
||||
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
|
||||
fileProgress.setLastReadTime(Instant.now().plusSeconds(3600));
|
||||
@@ -728,6 +988,7 @@ class KoboReadingStateServiceTest {
|
||||
existingProgress.setBook(testBook);
|
||||
existingProgress.setEpubProgressPercent(80f);
|
||||
existingProgress.setEpubProgress("epubcfi(/6/20)");
|
||||
existingProgress.setReadStatus(ReadStatus.READING);
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
@@ -755,6 +1016,9 @@ class KoboReadingStateServiceTest {
|
||||
UserBookProgressEntity saved = captor.getValue();
|
||||
assertEquals(80f, saved.getEpubProgressPercent());
|
||||
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
|
||||
@@ -778,18 +1042,24 @@ class KoboReadingStateServiceTest {
|
||||
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
|
||||
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()
|
||||
.progressPercent(60)
|
||||
.lastModified("2025-06-01T10:00:00Z")
|
||||
.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);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress);
|
||||
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress, fileProgress);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -809,7 +1079,7 @@ class KoboReadingStateServiceTest {
|
||||
List<KoboReadingState> result = service.getReadingState(entitlementId);
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
verify(readingStateBuilder, never()).buildReadingStateFromProgress(any(), any());
|
||||
verify(readingStateBuilder, never()).buildReadingStateFromProgress(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -818,9 +1088,9 @@ class KoboReadingStateServiceTest {
|
||||
String entitlementId = "100";
|
||||
|
||||
KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder()
|
||||
.value("epubcfi(/6/4[chap01ref]!/4/2/1:3)")
|
||||
.type("EpubCfi")
|
||||
.source("Kobo")
|
||||
.value("kobo.12.18")
|
||||
.type("KoboSpan")
|
||||
.source("OEBPS/chapter3.xhtml")
|
||||
.build();
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
@@ -846,9 +1116,9 @@ class KoboReadingStateServiceTest {
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
UserBookProgressEntity saved = captor.getValue();
|
||||
assertEquals("epubcfi(/6/4[chap01ref]!/4/2/1:3)", saved.getKoboLocation());
|
||||
assertEquals("EpubCfi", saved.getKoboLocationType());
|
||||
assertEquals("Kobo", saved.getKoboLocationSource());
|
||||
assertEquals("kobo.12.18", saved.getKoboLocation());
|
||||
assertEquals("KoboSpan", saved.getKoboLocationType());
|
||||
assertEquals("OEBPS/chapter3.xhtml", saved.getKoboLocationSource());
|
||||
assertEquals(42f, saved.getKoboProgressPercent());
|
||||
}
|
||||
|
||||
|
||||
+242
@@ -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
|
||||
void setUp() {
|
||||
koboSettings = KoboSettings.builder()
|
||||
.convertToKepub(false)
|
||||
.conversionLimitInMb(100)
|
||||
.convertCbxToEpub(false)
|
||||
.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));
|
||||
}
|
||||
|
||||
@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
|
||||
@DisplayName("Should not sync web reader progress when toggle OFF")
|
||||
void needsProgressSync_toggleOff() {
|
||||
@@ -286,7 +301,7 @@ class KoboLibrarySyncServiceTest {
|
||||
if (needsKoboProgressSync(progress)) return true;
|
||||
|
||||
if (testSettings.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))) {
|
||||
|
||||
+193
@@ -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.progress.EpubProgress;
|
||||
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.response.BookStatusUpdateResponse;
|
||||
import org.booklore.model.entity.*;
|
||||
@@ -153,12 +154,16 @@ class ReadingProgressServiceTest {
|
||||
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
|
||||
fileProgress.setBookFile(bookFile);
|
||||
fileProgress.setPositionData("new-cfi");
|
||||
fileProgress.setPositionHref("OPS/chapter3.xhtml");
|
||||
fileProgress.setContentSourceProgressPercent(18.6f);
|
||||
fileProgress.setProgressPercent(50.0f);
|
||||
fileProgress.setLastReadTime(Instant.now());
|
||||
|
||||
readingProgressService.enrichBookWithProgress(book, progress, fileProgress);
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -200,6 +205,49 @@ class ReadingProgressServiceTest {
|
||||
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
|
||||
void updateReadProgress_pdf_shouldSaveProgress() {
|
||||
long bookId = 1L;
|
||||
|
||||
@@ -182,6 +182,18 @@ class EpubCfiServiceTest {
|
||||
assertNotNull(result);
|
||||
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
|
||||
@@ -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
|
||||
class ValidationTests {
|
||||
|
||||
|
||||
Reference in New Issue
Block a user