Add bidirectional Kobo reading progress sync (#2791)
* Add bidirectional Kobo reading progress sync * Gate all two-way sync paths behind the toggle * Add comprehensive unit tests for Kobo services --------- Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
@@ -14,4 +14,5 @@ public class KoboSyncSettings {
|
||||
private boolean autoAddToShelf;
|
||||
private String hardcoverApiKey;
|
||||
private boolean hardcoverSyncEnabled;
|
||||
private boolean twoWayProgressSync;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ public class KoboReadingState {
|
||||
public static class StatusInfo {
|
||||
private String lastModified;
|
||||
private KoboReadStatus status;
|
||||
private int timesStartedReading;
|
||||
private Integer timesStartedReading;
|
||||
private String lastTimeStartedReading;
|
||||
private String lastTimeFinished;
|
||||
}
|
||||
|
||||
@@ -44,4 +44,8 @@ public class KoboUserSettingsEntity {
|
||||
@Column(name = "hardcover_sync_enabled")
|
||||
@Builder.Default
|
||||
private boolean hardcoverSyncEnabled = false;
|
||||
|
||||
@Column(name = "two_way_progress_sync")
|
||||
@Builder.Default
|
||||
private boolean twoWayProgressSync = false;
|
||||
}
|
||||
|
||||
@@ -46,6 +46,10 @@ public interface UserBookProgressRepository extends JpaRepository<UserBookProgre
|
||||
ubp.koboProgressSentTime IS NULL
|
||||
OR ubp.koboProgressReceivedTime > ubp.koboProgressSentTime
|
||||
))
|
||||
OR
|
||||
(ubp.epubProgressPercent IS NOT NULL
|
||||
AND ubp.epubProgress IS NOT NULL
|
||||
AND (ubp.koboProgressSentTime IS NULL OR ubp.lastReadTime > ubp.koboProgressSentTime))
|
||||
)
|
||||
""")
|
||||
List<UserBookProgressEntity> findAllBooksNeedingKoboSync(
|
||||
|
||||
@@ -47,6 +47,7 @@ public class KoboEntitlementService {
|
||||
private final ShelfRepository shelfRepository;
|
||||
private final MagicShelfRepository magicShelfRepository;
|
||||
private final MagicShelfBookService magicShelfBookService;
|
||||
private final KoboSettingsService koboSettingsService;
|
||||
|
||||
public List<NewEntitlement> generateNewEntitlements(Set<Long> bookIds, String token) {
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
@@ -178,7 +179,8 @@ public class KoboEntitlementService {
|
||||
private ChangedReadingState buildChangedReadingState(UserBookProgressEntity progress, String timestamp, OffsetDateTime now) {
|
||||
String entitlementId = String.valueOf(progress.getBook().getId());
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = progress.getKoboProgressPercent() != null
|
||||
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
|
||||
KoboReadingState.CurrentBookmark bookmark = (progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
|
||||
? readingStateBuilder.buildBookmarkFromProgress(progress, now)
|
||||
: readingStateBuilder.buildEmptyBookmark(now);
|
||||
|
||||
@@ -214,10 +216,21 @@ public class KoboEntitlementService {
|
||||
Optional<UserBookProgressEntity> userProgress = progressRepository
|
||||
.findByUserIdAndBookId(authenticationService.getAuthenticatedUser().getId(), book.getId());
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = existingState != null && existingState.getCurrentBookmark() != 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))
|
||||
.orElse(null)
|
||||
: null;
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = webReaderBookmark != null
|
||||
? webReaderBookmark
|
||||
: existingState != null && existingState.getCurrentBookmark() != null
|
||||
? existingState.getCurrentBookmark()
|
||||
: userProgress
|
||||
.filter(progress -> progress.getKoboProgressPercent() != null)
|
||||
.filter(progress -> progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
|
||||
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now))
|
||||
.orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now));
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ public class KoboLibrarySyncService {
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final KoboServerProxy koboServerProxy;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final KoboSettingsService koboSettingsService;
|
||||
|
||||
@Transactional
|
||||
public ResponseEntity<?> syncLibrary(BookLoreUser user, String token) {
|
||||
@@ -162,6 +163,12 @@ public class KoboLibrarySyncService {
|
||||
List<UserBookProgressEntity> booksNeedingSync =
|
||||
userBookProgressRepository.findAllBooksNeedingKoboSync(userId, snapshotId);
|
||||
|
||||
if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
|
||||
booksNeedingSync = booksNeedingSync.stream()
|
||||
.filter(p -> needsStatusSync(p) || needsKoboProgressSync(p))
|
||||
.toList();
|
||||
}
|
||||
|
||||
if (booksNeedingSync.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
@@ -192,12 +199,26 @@ public class KoboLibrarySyncService {
|
||||
return sentTime == null || modifiedTime.isAfter(sentTime);
|
||||
}
|
||||
|
||||
private boolean needsProgressSync(UserBookProgressEntity progress) {
|
||||
Instant receivedTime = progress.getKoboProgressReceivedTime();
|
||||
if (receivedTime == null) {
|
||||
return false;
|
||||
}
|
||||
private boolean needsKoboProgressSync(UserBookProgressEntity progress) {
|
||||
Instant sentTime = progress.getKoboProgressSentTime();
|
||||
return sentTime == null || receivedTime.isAfter(sentTime);
|
||||
Instant receivedTime = progress.getKoboProgressReceivedTime();
|
||||
return receivedTime != null && (sentTime == null || receivedTime.isAfter(sentTime));
|
||||
}
|
||||
|
||||
private boolean needsProgressSync(UserBookProgressEntity progress) {
|
||||
if (needsKoboProgressSync(progress)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()
|
||||
&& progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null) {
|
||||
Instant sentTime = progress.getKoboProgressSentTime();
|
||||
Instant lastReadTime = progress.getLastReadTime();
|
||||
if (lastReadTime != null && (sentTime == null || lastReadTime.isAfter(sentTime))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.booklore.service.kobo;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.model.dto.kobo.KoboReadingState;
|
||||
import org.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.booklore.model.enums.KoboReadStatus;
|
||||
@@ -12,8 +13,11 @@ import java.time.ZoneOffset;
|
||||
import java.util.Optional;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class KoboReadingStateBuilder {
|
||||
|
||||
private final KoboSettingsService koboSettingsService;
|
||||
|
||||
public KoboReadingState.CurrentBookmark buildEmptyBookmark(OffsetDateTime timestamp) {
|
||||
return KoboReadingState.CurrentBookmark.builder()
|
||||
.lastModified(timestamp.toString())
|
||||
@@ -25,6 +29,30 @@ public class KoboReadingStateBuilder {
|
||||
}
|
||||
|
||||
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) {
|
||||
if (isWebReaderNewer(progress)) {
|
||||
return buildBookmarkFromWebReaderProgress(progress, defaultTime);
|
||||
}
|
||||
return buildBookmarkFromKoboProgress(progress, defaultTime);
|
||||
}
|
||||
|
||||
private boolean isWebReaderNewer(UserBookProgressEntity progress) {
|
||||
return koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()
|
||||
&& progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null;
|
||||
}
|
||||
|
||||
private KoboReadingState.CurrentBookmark buildBookmarkFromWebReaderProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) {
|
||||
String lastModified = Optional.ofNullable(progress.getLastReadTime())
|
||||
.map(this::formatTimestamp)
|
||||
.or(() -> Optional.ofNullable(defaultTime).map(OffsetDateTime::toString))
|
||||
.orElse(null);
|
||||
|
||||
return KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(Math.round(progress.getEpubProgressPercent()))
|
||||
.lastModified(lastModified)
|
||||
.build();
|
||||
}
|
||||
|
||||
private KoboReadingState.CurrentBookmark buildBookmarkFromKoboProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) {
|
||||
KoboReadingState.CurrentBookmark.Location location = Optional.ofNullable(progress.getKoboLocation())
|
||||
.map(koboLocation -> KoboReadingState.CurrentBookmark.Location.builder()
|
||||
.value(koboLocation)
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
package org.booklore.service.kobo;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.mapper.KoboReadingStateMapper;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
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.*;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.KoboReadingStateEntity;
|
||||
import org.booklore.model.entity.UserBookFileProgressEntity;
|
||||
import org.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.KoboReadingStateRepository;
|
||||
import org.booklore.repository.UserBookFileProgressRepository;
|
||||
import org.booklore.repository.UserBookProgressRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.booklore.repository.*;
|
||||
import org.booklore.service.hardcover.HardcoverSyncService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -80,7 +80,7 @@ public class KoboReadingStateService {
|
||||
private List<KoboReadingState> saveAll(List<KoboReadingState> dtos) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Long userId = user.getId();
|
||||
|
||||
|
||||
return dtos.stream()
|
||||
.map(dto -> {
|
||||
String entitlementId = mapper.cleanString(dto.getEntitlementId());
|
||||
@@ -114,9 +114,9 @@ public class KoboReadingStateService {
|
||||
|
||||
KoboReadingStateEntity savedEntity = repository.save(entity);
|
||||
KoboReadingState savedState = mapper.toDto(savedEntity);
|
||||
|
||||
|
||||
syncKoboProgressToUserBookProgress(savedState, userId);
|
||||
|
||||
|
||||
return savedEntity;
|
||||
})
|
||||
.map(mapper::toDto)
|
||||
@@ -139,6 +139,8 @@ public class KoboReadingStateService {
|
||||
.map(mapper::toDto))
|
||||
.or(() -> constructReadingStateFromProgress(entitlementId));
|
||||
|
||||
readingState.ifPresent(state -> overlayWebReaderBookmark(state, entitlementId, userId));
|
||||
|
||||
return readingState
|
||||
.map(state -> {
|
||||
normalizeResponseTimestamps(state);
|
||||
@@ -146,21 +148,46 @@ public class KoboReadingStateService {
|
||||
})
|
||||
.orElse(List.of());
|
||||
}
|
||||
|
||||
|
||||
private void overlayWebReaderBookmark(KoboReadingState state, String entitlementId, Long userId) {
|
||||
if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Long bookId = Long.parseLong(entitlementId);
|
||||
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);
|
||||
}
|
||||
});
|
||||
} catch (NumberFormatException e) {
|
||||
// Not a valid book ID, skip overlay
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<KoboReadingState> constructReadingStateFromProgress(String entitlementId) {
|
||||
try {
|
||||
Long bookId = Long.parseLong(entitlementId);
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
|
||||
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
|
||||
return progressRepository.findByUserIdAndBookId(user.getId(), bookId)
|
||||
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null)
|
||||
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
|
||||
.map(progress -> readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress));
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("Invalid entitlement ID format when constructing reading state: {}", entitlementId);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void syncKoboProgressToUserBookProgress(KoboReadingState readingState, Long userId) {
|
||||
try {
|
||||
Long bookId = Long.parseLong(readingState.getEntitlementId());
|
||||
@@ -197,9 +224,6 @@ public class KoboReadingStateService {
|
||||
|
||||
KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation();
|
||||
if (location != null) {
|
||||
log.debug("Kobo location data: value={}, type={}, source={} (length={})",
|
||||
location.getValue(), location.getType(), location.getSource(),
|
||||
location.getSource() != null ? location.getSource().length() : 0);
|
||||
progress.setKoboLocation(location.getValue());
|
||||
progress.setKoboLocationType(location.getType());
|
||||
progress.setKoboLocationSource(location.getSource());
|
||||
@@ -208,7 +232,11 @@ public class KoboReadingStateService {
|
||||
|
||||
Instant now = Instant.now();
|
||||
progress.setKoboProgressReceivedTime(now);
|
||||
progress.setLastReadTime(now);
|
||||
|
||||
boolean koboApplied = crossPopulateEpubFieldsFromKobo(progress, bookmark, book, userId, now);
|
||||
if (koboApplied) {
|
||||
progress.setLastReadTime(now);
|
||||
}
|
||||
|
||||
if (progress.getKoboProgressPercent() != null) {
|
||||
updateReadStatusFromKoboProgress(progress, now);
|
||||
@@ -216,16 +244,11 @@ public class KoboReadingStateService {
|
||||
|
||||
progressRepository.save(progress);
|
||||
|
||||
// Also save to file-level progress table (dual-write)
|
||||
saveToFileProgress(userOpt.get(), book, progress);
|
||||
|
||||
log.debug("Synced Kobo progress: bookId={}, progress={}%", bookId, progress.getKoboProgressPercent());
|
||||
|
||||
// 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)
|
||||
|| progress.getReadStatus() != previousReadStatus)) {
|
||||
|| progress.getReadStatus() != previousReadStatus)) {
|
||||
hardcoverSyncService.syncProgressToHardcover(book.getId(), progress.getKoboProgressPercent(), userId);
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
@@ -233,6 +256,51 @@ public class KoboReadingStateService {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean crossPopulateEpubFieldsFromKobo(UserBookProgressEntity progress,
|
||||
KoboReadingState.CurrentBookmark bookmark,
|
||||
BookEntity book, Long userId, Instant now) {
|
||||
if (bookmark == null || bookmark.getProgressPercent() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
|
||||
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
|
||||
&& bookmarkTime != null
|
||||
&& fileProgress.getLastReadTime().isAfter(bookmarkTime);
|
||||
|
||||
if (webReaderIsNewer) {
|
||||
return false;
|
||||
}
|
||||
|
||||
progress.setEpubProgressPercent(bookmark.getProgressPercent().floatValue());
|
||||
KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation();
|
||||
if (location != null && location.getSource() != null) {
|
||||
progress.setEpubProgressHref(location.getSource());
|
||||
}
|
||||
progress.setEpubProgress(null);
|
||||
|
||||
if (fileProgress != null) {
|
||||
fileProgress.setProgressPercent(bookmark.getProgressPercent().floatValue());
|
||||
if (location != null && location.getSource() != null) {
|
||||
fileProgress.setPositionHref(location.getSource());
|
||||
}
|
||||
fileProgress.setPositionData(null);
|
||||
fileProgress.setLastReadTime(now);
|
||||
fileProgressRepository.save(fileProgress);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void normalizePutTimestamps(List<KoboReadingState> readingStates) {
|
||||
if (readingStates == null || readingStates.isEmpty()) {
|
||||
return;
|
||||
@@ -429,26 +497,6 @@ public class KoboReadingStateService {
|
||||
return value == null || value.trim().isEmpty() || "null".equalsIgnoreCase(value.trim());
|
||||
}
|
||||
|
||||
private void saveToFileProgress(BookLoreUserEntity user, BookEntity book, UserBookProgressEntity progress) {
|
||||
try {
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
UserBookFileProgressEntity fileProgress = fileProgressRepository
|
||||
.findByUserIdAndBookFileId(user.getId(), primaryFile.getId())
|
||||
.orElseGet(UserBookFileProgressEntity::new);
|
||||
|
||||
fileProgress.setUser(user);
|
||||
fileProgress.setBookFile(primaryFile);
|
||||
fileProgress.setLastReadTime(progress.getLastReadTime());
|
||||
|
||||
// For Kobo, we store the progress percent (Kobo doesn't provide position data)
|
||||
fileProgress.setProgressPercent(progress.getKoboProgressPercent());
|
||||
|
||||
fileProgressRepository.save(fileProgress);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to save file-level progress for book {}: {}", book.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void updateReadStatusFromKoboProgress(UserBookProgressEntity userProgress, Instant now) {
|
||||
if (shouldPreserveCurrentStatus(userProgress, now)) {
|
||||
return;
|
||||
@@ -479,15 +527,15 @@ public class KoboReadingStateService {
|
||||
|
||||
return now.isBefore(statusSentTime.plusSeconds(STATUS_SYNC_BUFFER_SECONDS));
|
||||
}
|
||||
|
||||
|
||||
private ReadStatus deriveStatusFromProgress(double progressPercent) {
|
||||
KoboSyncSettings settings = koboSettingsService.getCurrentUserSettings();
|
||||
|
||||
float finishedThreshold = settings.getProgressMarkAsFinishedThreshold() != null
|
||||
|
||||
float finishedThreshold = settings.getProgressMarkAsFinishedThreshold() != null
|
||||
? settings.getProgressMarkAsFinishedThreshold() : 99f;
|
||||
float readingThreshold = settings.getProgressMarkAsReadingThreshold() != null
|
||||
float readingThreshold = settings.getProgressMarkAsReadingThreshold() != null
|
||||
? settings.getProgressMarkAsReadingThreshold() : 1f;
|
||||
|
||||
|
||||
if (progressPercent >= finishedThreshold) return ReadStatus.READ;
|
||||
if (progressPercent >= readingThreshold) return ReadStatus.READING;
|
||||
return ReadStatus.UNREAD;
|
||||
|
||||
@@ -84,6 +84,7 @@ public class KoboSettingsService {
|
||||
}
|
||||
|
||||
entity.setAutoAddToShelf(settings.isAutoAddToShelf());
|
||||
entity.setTwoWayProgressSync(settings.isTwoWayProgressSync());
|
||||
|
||||
repository.save(entity);
|
||||
return mapToDto(entity, hardcoverSyncSettingsService.getSettingsForUserId(user.getId()));
|
||||
@@ -130,6 +131,7 @@ public class KoboSettingsService {
|
||||
dto.setProgressMarkAsReadingThreshold(entity.getProgressMarkAsReadingThreshold());
|
||||
dto.setProgressMarkAsFinishedThreshold(entity.getProgressMarkAsFinishedThreshold());
|
||||
dto.setAutoAddToShelf(entity.isAutoAddToShelf());
|
||||
dto.setTwoWayProgressSync(entity.isTwoWayProgressSync());
|
||||
if (hardcoverSettings != null) {
|
||||
dto.setHardcoverApiKey(hardcoverSettings.getHardcoverApiKey());
|
||||
dto.setHardcoverSyncEnabled(hardcoverSettings.isHardcoverSyncEnabled());
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
ALTER TABLE kobo_user_settings ADD COLUMN IF NOT EXISTS two_way_progress_sync BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
@@ -21,19 +21,36 @@ import org.booklore.repository.ShelfRepository;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.service.book.BookQueryService;
|
||||
import org.booklore.service.kobo.KoboCompatibilityService;
|
||||
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.UserBookProgressEntity;
|
||||
import org.booklore.model.enums.KoboReadStatus;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.repository.KoboReadingStateRepository;
|
||||
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.opds.MagicShelfBookService;
|
||||
import org.booklore.util.kobo.KoboUrlBuilder;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
@@ -45,6 +62,7 @@ import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class KoboEntitlementServiceTest {
|
||||
|
||||
@Mock
|
||||
@@ -71,6 +89,21 @@ class KoboEntitlementServiceTest {
|
||||
@Mock
|
||||
private MagicShelfBookService magicShelfBookService;
|
||||
|
||||
@Mock
|
||||
private UserBookProgressRepository progressRepository;
|
||||
|
||||
@Mock
|
||||
private KoboReadingStateRepository readingStateRepository;
|
||||
|
||||
@Mock
|
||||
private KoboReadingStateMapper readingStateMapper;
|
||||
|
||||
@Mock
|
||||
private KoboReadingStateBuilder readingStateBuilder;
|
||||
|
||||
@Mock
|
||||
private KoboSettingsService koboSettingsService;
|
||||
|
||||
@InjectMocks
|
||||
private KoboEntitlementService koboEntitlementService;
|
||||
|
||||
@@ -406,4 +439,226 @@ class KoboEntitlementServiceTest {
|
||||
return book;
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Generate New Entitlements")
|
||||
class GenerateNewEntitlements {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should generate new entitlements for supported books")
|
||||
void generateNewEntitlements_supportedBooks() {
|
||||
BookEntity book = createEpubBookEntity(1L);
|
||||
book.setAddedOn(Instant.parse("2025-01-01T00:00:00Z"));
|
||||
|
||||
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(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(progressRepository.findByUserIdAndBookId(any(), eq(1L))).thenReturn(Optional.empty());
|
||||
when(readingStateRepository.findByEntitlementIdAndUserId(anyString(), any())).thenReturn(Optional.empty());
|
||||
when(readingStateRepository.findFirstByEntitlementIdAndUserIdIsNullOrderByPriorityTimestampDescLastModifiedStringDescIdDesc(anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
KoboSyncSettings settings = new KoboSyncSettings();
|
||||
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
|
||||
when(readingStateBuilder.buildEmptyBookmark(any(OffsetDateTime.class)))
|
||||
.thenReturn(KoboReadingState.CurrentBookmark.builder().build());
|
||||
|
||||
List<NewEntitlement> result = koboEntitlementService.generateNewEntitlements(Set.of(1L), "token1");
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertNotNull(result.getFirst().getNewEntitlement());
|
||||
assertNotNull(result.getFirst().getNewEntitlement().getBookMetadata());
|
||||
assertEquals("Test EPUB Book 1", result.getFirst().getNewEntitlement().getBookMetadata().getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should filter out unsupported books")
|
||||
void generateNewEntitlements_filterUnsupported() {
|
||||
BookEntity book = createEpubBookEntity(1L);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
|
||||
when(koboCompatibilityService.isBookSupportedForKobo(book)).thenReturn(false);
|
||||
|
||||
List<NewEntitlement> result = koboEntitlementService.generateNewEntitlements(Set.of(1L), "token1");
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle empty book IDs")
|
||||
void generateNewEntitlements_emptyIds() {
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of())).thenReturn(List.of());
|
||||
|
||||
List<NewEntitlement> result = koboEntitlementService.generateNewEntitlements(Set.of(), "token1");
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Generate Changed Entitlements")
|
||||
class GenerateChangedEntitlements {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should generate removed entitlements with minimal metadata")
|
||||
void generateChangedEntitlements_removed() {
|
||||
BookEntity book = createEpubBookEntity(1L);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
|
||||
when(koboCompatibilityService.isBookSupportedForKobo(book)).thenReturn(true);
|
||||
|
||||
List<? extends Entitlement> result = koboEntitlementService.generateChangedEntitlements(Set.of(1L), "token1", true);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertTrue(result.getFirst() instanceof ChangedEntitlement);
|
||||
ChangedEntitlement changed = (ChangedEntitlement) result.getFirst();
|
||||
assertTrue(changed.getChangedEntitlement().getBookEntitlement().getRemoved());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should generate changed product metadata for non-removed EPUB books")
|
||||
void generateChangedEntitlements_changed() {
|
||||
BookEntity book = createEpubBookEntity(1L);
|
||||
|
||||
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());
|
||||
|
||||
List<? extends Entitlement> result = koboEntitlementService.generateChangedEntitlements(Set.of(1L), "token1", false);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertTrue(result.getFirst() instanceof ChangedProductMetadata);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Generate Changed Reading States")
|
||||
class GenerateChangedReadingStates {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should generate changed reading states from progress entries")
|
||||
void generateChangedReadingStates_fromProgress() {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(1L);
|
||||
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setBook(book);
|
||||
progress.setKoboProgressPercent(50f);
|
||||
progress.setReadStatus(ReadStatus.READING);
|
||||
|
||||
KoboSyncSettings settings = new KoboSyncSettings();
|
||||
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(50)
|
||||
.build();
|
||||
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), any(OffsetDateTime.class)))
|
||||
.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());
|
||||
assertNotNull(result.getFirst().getChangedReadingState());
|
||||
KoboReadingState state = result.getFirst().getChangedReadingState().getReadingState();
|
||||
assertEquals("1", state.getEntitlementId());
|
||||
assertNotNull(state.getCurrentBookmark());
|
||||
assertNotNull(state.getStatusInfo());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should use empty bookmark when no progress data exists")
|
||||
void generateChangedReadingStates_emptyBookmark() {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(1L);
|
||||
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setBook(book);
|
||||
progress.setReadStatus(ReadStatus.UNREAD);
|
||||
|
||||
KoboSyncSettings settings = new KoboSyncSettings();
|
||||
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
|
||||
|
||||
KoboReadingState.CurrentBookmark emptyBookmark = KoboReadingState.CurrentBookmark.builder().build();
|
||||
when(readingStateBuilder.buildEmptyBookmark(any(OffsetDateTime.class))).thenReturn(emptyBookmark);
|
||||
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
|
||||
.thenReturn(KoboReadingState.StatusInfo.builder()
|
||||
.status(KoboReadStatus.READY_TO_READ)
|
||||
.timesStartedReading(0)
|
||||
.build());
|
||||
|
||||
List<ChangedReadingState> result = koboEntitlementService.generateChangedReadingStates(List.of(progress));
|
||||
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should include epub progress in bookmark when two-way sync ON")
|
||||
void generateChangedReadingStates_twoWaySync() {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(1L);
|
||||
|
||||
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);
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(70)
|
||||
.build();
|
||||
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), any(OffsetDateTime.class)))
|
||||
.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(70, result.getFirst().getChangedReadingState().getReadingState()
|
||||
.getCurrentBookmark().getProgressPercent());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should NOT include epub progress in bookmark when two-way sync OFF")
|
||||
void generateChangedReadingStates_twoWaySyncOff() {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(1L);
|
||||
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setBook(book);
|
||||
progress.setKoboProgressPercent(null);
|
||||
progress.setEpubProgressPercent(70f);
|
||||
progress.setReadStatus(ReadStatus.READING);
|
||||
|
||||
KoboSyncSettings settings = new KoboSyncSettings();
|
||||
settings.setTwoWayProgressSync(false);
|
||||
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
|
||||
|
||||
KoboReadingState.CurrentBookmark emptyBookmark = KoboReadingState.CurrentBookmark.builder().build();
|
||||
when(readingStateBuilder.buildEmptyBookmark(any(OffsetDateTime.class))).thenReturn(emptyBookmark);
|
||||
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());
|
||||
verify(readingStateBuilder).buildEmptyBookmark(any(OffsetDateTime.class));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,25 @@
|
||||
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.UserBookProgressEntity;
|
||||
import org.booklore.model.enums.KoboReadStatus;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.service.kobo.KoboReadingStateBuilder;
|
||||
import org.booklore.service.kobo.KoboSettingsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.OffsetDateTime;
|
||||
@@ -20,15 +27,24 @@ import java.time.ZoneOffset;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@DisplayName("KoboReadingStateBuilder Tests")
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class KoboReadingStateBuilderTest {
|
||||
|
||||
@Mock
|
||||
private KoboSettingsService koboSettingsService;
|
||||
|
||||
private KoboReadingStateBuilder builder;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
builder = new KoboReadingStateBuilder();
|
||||
KoboSyncSettings settings = new KoboSyncSettings();
|
||||
settings.setTwoWayProgressSync(true);
|
||||
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
|
||||
builder = new KoboReadingStateBuilder(koboSettingsService);
|
||||
}
|
||||
|
||||
@Nested
|
||||
|
||||
@@ -31,6 +31,10 @@ import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import org.booklore.model.entity.BookFileEntity;
|
||||
import org.booklore.model.entity.UserBookFileProgressEntity;
|
||||
import org.booklore.repository.UserBookFileProgressRepository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -69,6 +73,9 @@ class KoboReadingStateServiceTest {
|
||||
@Mock
|
||||
private HardcoverSyncService hardcoverSyncService;
|
||||
|
||||
@Mock
|
||||
private UserBookFileProgressRepository fileProgressRepository;
|
||||
|
||||
@InjectMocks
|
||||
private KoboReadingStateService service;
|
||||
|
||||
@@ -278,7 +285,7 @@ class KoboReadingStateServiceTest {
|
||||
assertEquals("Kobo", state.getCurrentBookmark().getLocation().getSource());
|
||||
|
||||
verify(repository).findByEntitlementIdAndUserId(entitlementId, 1L);
|
||||
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
|
||||
verify(progressRepository, atLeastOnce()).findByUserIdAndBookId(1L, 100L);
|
||||
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress);
|
||||
}
|
||||
|
||||
@@ -328,13 +335,13 @@ class KoboReadingStateServiceTest {
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(entity));
|
||||
when(mapper.toDto(entity)).thenReturn(existingState);
|
||||
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.empty());
|
||||
|
||||
List<KoboReadingState> result = service.getReadingState(entitlementId);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(entitlementId, result.getFirst().getEntitlementId());
|
||||
verify(progressRepository, never()).findByUserIdAndBookId(anyLong(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -523,4 +530,453 @@ class KoboReadingStateServiceTest {
|
||||
assertEquals(existingStatus.getStatus(), savedStatus.getStatus());
|
||||
assertEquals(timestamp, saved.getLastModifiedString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should delete reading state for authenticated user")
|
||||
void testDeleteReadingState() {
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(repository.findByEntitlementIdAndUserId("100", 1L)).thenReturn(Optional.of(entity));
|
||||
|
||||
service.deleteReadingState(100L);
|
||||
|
||||
verify(repository).delete(entity);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not throw when deleting non-existent reading state")
|
||||
void testDeleteReadingState_notFound() {
|
||||
when(repository.findByEntitlementIdAndUserId("100", 1L)).thenReturn(Optional.empty());
|
||||
|
||||
assertDoesNotThrow(() -> service.deleteReadingState(100L));
|
||||
verify(repository, never()).delete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should overlay web reader bookmark when two-way sync is ON and web reader data exists")
|
||||
void testGetReadingState_overlayWebReaderBookmark() {
|
||||
testSettings.setTwoWayProgressSync(true);
|
||||
String entitlementId = "100";
|
||||
|
||||
KoboReadingState existingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(30)
|
||||
.contentSourceProgressPercent(45)
|
||||
.location(KoboReadingState.CurrentBookmark.Location.builder()
|
||||
.value("epubcfi(/6/10)")
|
||||
.type("EpubCfi")
|
||||
.source("Kobo")
|
||||
.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));
|
||||
|
||||
KoboReadingState.CurrentBookmark webBookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(65)
|
||||
.lastModified("2025-06-01T10:00:00Z")
|
||||
.build();
|
||||
when(readingStateBuilder.buildBookmarkFromProgress(progress)).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());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should NOT overlay web reader bookmark when two-way sync is OFF")
|
||||
void testGetReadingState_noOverlayWhenToggleOff() {
|
||||
testSettings.setTwoWayProgressSync(false);
|
||||
String entitlementId = "100";
|
||||
|
||||
KoboReadingState existingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(30)
|
||||
.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);
|
||||
|
||||
List<KoboReadingState> result = service.getReadingState(entitlementId);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(30, result.getFirst().getCurrentBookmark().getProgressPercent());
|
||||
verify(readingStateBuilder, never()).buildBookmarkFromProgress(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should cross-populate 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));
|
||||
|
||||
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")
|
||||
.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(fileProgressRepository.findByUserIdAndBookFileId(1L, 10L)).thenReturn(Optional.empty());
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(captor.capture())).thenReturn(existingProgress);
|
||||
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
UserBookProgressEntity saved = captor.getValue();
|
||||
assertEquals(55f, saved.getEpubProgressPercent());
|
||||
assertEquals("chapter3.xhtml", saved.getEpubProgressHref());
|
||||
assertNull(saved.getEpubProgress());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should NOT cross-populate epub fields when two-way sync is OFF")
|
||||
void testSyncKoboProgress_noCrossPopulateWhenToggleOff() {
|
||||
testSettings.setTwoWayProgressSync(false);
|
||||
String entitlementId = "100";
|
||||
|
||||
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
|
||||
existingProgress.setUser(testUserEntity);
|
||||
existingProgress.setBook(testBook);
|
||||
existingProgress.setEpubProgressPercent(40f);
|
||||
existingProgress.setEpubProgress("epubcfi(/6/4)");
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(70)
|
||||
.build())
|
||||
.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));
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(captor.capture())).thenReturn(existingProgress);
|
||||
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
UserBookProgressEntity saved = captor.getValue();
|
||||
assertEquals(40f, saved.getEpubProgressPercent());
|
||||
assertEquals("epubcfi(/6/4)", saved.getEpubProgress());
|
||||
}
|
||||
|
||||
@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));
|
||||
|
||||
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
|
||||
fileProgress.setLastReadTime(Instant.now().plusSeconds(3600));
|
||||
|
||||
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
|
||||
existingProgress.setUser(testUserEntity);
|
||||
existingProgress.setBook(testBook);
|
||||
existingProgress.setEpubProgressPercent(80f);
|
||||
existingProgress.setEpubProgress("epubcfi(/6/20)");
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(50)
|
||||
.lastModified("2025-01-01T00:00:00Z")
|
||||
.build())
|
||||
.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, 10L)).thenReturn(Optional.of(fileProgress));
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(captor.capture())).thenReturn(existingProgress);
|
||||
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
UserBookProgressEntity saved = captor.getValue();
|
||||
assertEquals(80f, saved.getEpubProgressPercent());
|
||||
assertEquals("epubcfi(/6/20)", saved.getEpubProgress());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should construct reading state from web reader progress when toggle ON and no Kobo data")
|
||||
void testGetReadingState_constructFromWebReaderProgress_whenToggleOn() {
|
||||
testSettings.setTwoWayProgressSync(true);
|
||||
String entitlementId = "100";
|
||||
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setKoboProgressPercent(null);
|
||||
progress.setKoboLocation(null);
|
||||
progress.setEpubProgressPercent(60f);
|
||||
progress.setEpubProgress("epubcfi(/6/12)");
|
||||
|
||||
KoboReadingState expectedState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(60)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
|
||||
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
|
||||
when(readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress)).thenReturn(expectedState);
|
||||
|
||||
KoboReadingState.CurrentBookmark webBookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(60)
|
||||
.lastModified("2025-06-01T10:00:00Z")
|
||||
.build();
|
||||
when(readingStateBuilder.buildBookmarkFromProgress(progress)).thenReturn(webBookmark);
|
||||
|
||||
List<KoboReadingState> result = service.getReadingState(entitlementId);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should NOT construct reading state from web reader progress when toggle OFF")
|
||||
void testGetReadingState_noConstructFromWebReaderProgress_whenToggleOff() {
|
||||
testSettings.setTwoWayProgressSync(false);
|
||||
String entitlementId = "100";
|
||||
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setKoboProgressPercent(null);
|
||||
progress.setKoboLocation(null);
|
||||
progress.setEpubProgressPercent(60f);
|
||||
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
|
||||
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
|
||||
|
||||
List<KoboReadingState> result = service.getReadingState(entitlementId);
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
verify(readingStateBuilder, never()).buildReadingStateFromProgress(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should sync location data from Kobo bookmark")
|
||||
void testSyncKoboProgress_locationData() {
|
||||
String entitlementId = "100";
|
||||
|
||||
KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder()
|
||||
.value("epubcfi(/6/4[chap01ref]!/4/2/1:3)")
|
||||
.type("EpubCfi")
|
||||
.source("Kobo")
|
||||
.build();
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(42)
|
||||
.location(location)
|
||||
.build())
|
||||
.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.empty());
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(captor.capture())).thenReturn(new UserBookProgressEntity());
|
||||
|
||||
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(42f, saved.getKoboProgressPercent());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should set finished date when progress reaches threshold for new book")
|
||||
void testSyncKoboProgress_setsFinishedDate() {
|
||||
testSettings.setProgressMarkAsFinishedThreshold(99f);
|
||||
String entitlementId = "100";
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(100)
|
||||
.build())
|
||||
.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.empty());
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(captor.capture())).thenReturn(new UserBookProgressEntity());
|
||||
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
UserBookProgressEntity saved = captor.getValue();
|
||||
assertEquals(ReadStatus.READ, saved.getReadStatus());
|
||||
assertNotNull(saved.getDateFinished());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should use configurable thresholds for status derivation")
|
||||
void testSyncKoboProgress_configurableThresholds() {
|
||||
testSettings.setProgressMarkAsReadingThreshold(10f);
|
||||
testSettings.setProgressMarkAsFinishedThreshold(95f);
|
||||
String entitlementId = "100";
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(5)
|
||||
.build())
|
||||
.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.empty());
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(captor.capture())).thenReturn(new UserBookProgressEntity());
|
||||
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
assertEquals(ReadStatus.UNREAD, captor.getValue().getReadStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should trigger Hardcover sync when progress changes")
|
||||
void testSyncKoboProgress_triggersHardcover() {
|
||||
String entitlementId = "100";
|
||||
|
||||
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
|
||||
existingProgress.setUser(testUserEntity);
|
||||
existingProgress.setBook(testBook);
|
||||
existingProgress.setKoboProgressPercent(30f);
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(50)
|
||||
.build())
|
||||
.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));
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(captor.capture())).thenReturn(existingProgress);
|
||||
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
verify(hardcoverSyncService).syncProgressToHardcover(eq(100L), eq(50f), eq(1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle multiple reading states in a single save call")
|
||||
void testSaveReadingState_multipleStates() {
|
||||
KoboReadingState state1 = KoboReadingState.builder()
|
||||
.entitlementId("100")
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder().progressPercent(25).build())
|
||||
.build();
|
||||
KoboReadingState state2 = KoboReadingState.builder()
|
||||
.entitlementId("200")
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder().progressPercent(75).build())
|
||||
.build();
|
||||
|
||||
BookEntity book2 = new BookEntity();
|
||||
book2.setId(200L);
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(mapper.toEntity(any())).thenReturn(entity);
|
||||
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(state1, state2);
|
||||
when(repository.findByEntitlementIdAndUserId(anyString(), eq(1L))).thenReturn(Optional.empty());
|
||||
when(repository.save(any())).thenReturn(entity);
|
||||
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
|
||||
when(bookRepository.findById(200L)).thenReturn(Optional.of(book2));
|
||||
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
|
||||
when(progressRepository.findByUserIdAndBookId(eq(1L), anyLong())).thenReturn(Optional.empty());
|
||||
when(progressRepository.save(any())).thenReturn(new UserBookProgressEntity());
|
||||
|
||||
assertDoesNotThrow(() -> service.saveReadingState(List.of(state1, state2)));
|
||||
|
||||
verify(progressRepository, times(2)).save(any());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package org.booklore.service.kobo;
|
||||
|
||||
import org.booklore.model.dto.kobo.KoboAuthentication;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@DisplayName("KoboDeviceAuthService Tests")
|
||||
class KoboDeviceAuthServiceTest {
|
||||
|
||||
private KoboDeviceAuthService service;
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
objectMapper = JsonMapper.builder().build();
|
||||
service = new KoboDeviceAuthService(objectMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should authenticate device with valid UserKey")
|
||||
void authenticateDevice_validUserKey() {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("UserKey", "test-user-key-123");
|
||||
|
||||
ResponseEntity<KoboAuthentication> response = service.authenticateDevice(body);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
KoboAuthentication auth = response.getBody();
|
||||
assertNotNull(auth);
|
||||
assertEquals("test-user-key-123", auth.getUserKey());
|
||||
assertNotNull(auth.getAccessToken());
|
||||
assertNotNull(auth.getRefreshToken());
|
||||
assertNotNull(auth.getTrackingId());
|
||||
assertEquals(24, auth.getAccessToken().length());
|
||||
assertEquals(24, auth.getRefreshToken().length());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should generate unique tokens per request")
|
||||
void authenticateDevice_uniqueTokens() {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("UserKey", "user1");
|
||||
|
||||
KoboAuthentication first = service.authenticateDevice(body).getBody();
|
||||
KoboAuthentication second = service.authenticateDevice(body).getBody();
|
||||
|
||||
assertNotEquals(first.getAccessToken(), second.getAccessToken());
|
||||
assertNotEquals(first.getRefreshToken(), second.getRefreshToken());
|
||||
assertNotEquals(first.getTrackingId(), second.getTrackingId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should throw when request body is null")
|
||||
void authenticateDevice_nullBody() {
|
||||
assertThrows(IllegalArgumentException.class, () -> service.authenticateDevice(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should throw when UserKey is missing")
|
||||
void authenticateDevice_missingUserKey() {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("SomeOtherField", "value");
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> service.authenticateDevice(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should set correct Content-Type header")
|
||||
void authenticateDevice_contentTypeHeader() {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("UserKey", "user1");
|
||||
|
||||
ResponseEntity<KoboAuthentication> response = service.authenticateDevice(body);
|
||||
|
||||
assertTrue(response.getHeaders().getFirst("Content-Type").contains("application/json"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should set Content-Length header")
|
||||
void authenticateDevice_contentLengthHeader() {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("UserKey", "user1");
|
||||
|
||||
ResponseEntity<KoboAuthentication> response = service.authenticateDevice(body);
|
||||
|
||||
String contentLength = response.getHeaders().getFirst("Content-Length");
|
||||
assertNotNull(contentLength);
|
||||
assertTrue(Integer.parseInt(contentLength) > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should serialize KoboAuthentication to JSON bytes")
|
||||
void toJsonBytes_validAuth() {
|
||||
KoboAuthentication auth = KoboAuthentication.builder()
|
||||
.accessToken("abc123")
|
||||
.refreshToken("def456")
|
||||
.trackingId("track-1")
|
||||
.userKey("user-key")
|
||||
.build();
|
||||
|
||||
byte[] bytes = service.toJsonBytes(auth);
|
||||
|
||||
assertNotNull(bytes);
|
||||
assertTrue(bytes.length > 0);
|
||||
String json = new String(bytes);
|
||||
assertTrue(json.contains("abc123"));
|
||||
assertTrue(json.contains("user-key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should preserve UserKey value exactly as received")
|
||||
void authenticateDevice_preservesUserKey() {
|
||||
String userKey = "special-chars_123.ABC@domain";
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("UserKey", userKey);
|
||||
|
||||
KoboAuthentication auth = service.authenticateDevice(body).getBody();
|
||||
|
||||
assertEquals(userKey, auth.getUserKey());
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
package org.booklore.service.kobo;
|
||||
|
||||
import org.booklore.model.dto.kobo.KoboResources;
|
||||
import org.booklore.util.kobo.KoboUrlBuilder;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@DisplayName("KoboInitializationService Tests")
|
||||
class KoboInitializationServiceTest {
|
||||
|
||||
@Mock
|
||||
private KoboServerProxy koboServerProxy;
|
||||
|
||||
@Mock
|
||||
private KoboResourcesComponent koboResourcesComponent;
|
||||
|
||||
@Mock
|
||||
private KoboUrlBuilder koboUrlBuilder;
|
||||
|
||||
@InjectMocks
|
||||
private KoboInitializationService service;
|
||||
|
||||
private final ObjectMapper objectMapper = JsonMapper.builder().build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(koboUrlBuilder.baseBuilder()).thenReturn(UriComponentsBuilder.fromUriString("http://localhost:8080"));
|
||||
when(koboUrlBuilder.imageUrlTemplate("test-token")).thenReturn("http://localhost:8080/kobo/test-token/image/{ImageId}/{Width}/{Height}/false/image.jpg");
|
||||
when(koboUrlBuilder.imageUrlQualityTemplate("test-token")).thenReturn("http://localhost:8080/kobo/test-token/image/{ImageId}/{Width}/{Height}/{Quality}/{IsGreyscale}/image.jpg");
|
||||
when(koboUrlBuilder.librarySyncUrl("test-token")).thenReturn("http://localhost:8080/kobo/test-token/v1/library/sync");
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("When Kobo proxy returns Resources")
|
||||
class WithProxyResources {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should use Resources from Kobo proxy response")
|
||||
void initialize_usesProxyResources() throws Exception {
|
||||
ObjectNode resources = objectMapper.createObjectNode();
|
||||
resources.put("library_sync", "https://storeapi.kobo.com/v1/library/sync");
|
||||
resources.put("image_host", "https://cdn.kobo.com/book-images/");
|
||||
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.set("Resources", resources);
|
||||
|
||||
when(koboServerProxy.proxyCurrentRequest(null, false))
|
||||
.thenReturn(ResponseEntity.ok(body));
|
||||
|
||||
ResponseEntity<KoboResources> response = service.initialize("test-token");
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
assertNotNull(response.getBody());
|
||||
JsonNode result = response.getBody().getResources();
|
||||
assertEquals("http://localhost:8080/kobo/test-token/v1/library/sync", result.get("library_sync").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should override image_host with local base URL")
|
||||
void initialize_overridesImageHost() throws Exception {
|
||||
ObjectNode resources = objectMapper.createObjectNode();
|
||||
resources.put("image_host", "https://cdn.kobo.com/book-images/");
|
||||
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.set("Resources", resources);
|
||||
|
||||
when(koboServerProxy.proxyCurrentRequest(null, false))
|
||||
.thenReturn(ResponseEntity.ok(body));
|
||||
|
||||
ResponseEntity<KoboResources> response = service.initialize("test-token");
|
||||
|
||||
JsonNode result = response.getBody().getResources();
|
||||
assertEquals("http://localhost:8080", result.get("image_host").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should override image_url_template with local URL")
|
||||
void initialize_overridesImageUrlTemplate() throws Exception {
|
||||
ObjectNode resources = objectMapper.createObjectNode();
|
||||
resources.put("image_url_template", "https://cdn.kobo.com/book-images/{ImageId}/{Width}/{Height}/false/image.jpg");
|
||||
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.set("Resources", resources);
|
||||
|
||||
when(koboServerProxy.proxyCurrentRequest(null, false))
|
||||
.thenReturn(ResponseEntity.ok(body));
|
||||
|
||||
ResponseEntity<KoboResources> response = service.initialize("test-token");
|
||||
|
||||
JsonNode result = response.getBody().getResources();
|
||||
assertTrue(result.get("image_url_template").asText().contains("localhost:8080"));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("When Kobo proxy fails or returns no Resources")
|
||||
class WithoutProxyResources {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should fall back to local resources when proxy returns null body")
|
||||
void initialize_fallsBackOnNullBody() throws Exception {
|
||||
when(koboServerProxy.proxyCurrentRequest(null, false))
|
||||
.thenReturn(ResponseEntity.ok(null));
|
||||
|
||||
ObjectNode fallbackResources = objectMapper.createObjectNode();
|
||||
fallbackResources.put("library_sync", "https://storeapi.kobo.com/v1/library/sync");
|
||||
when(koboResourcesComponent.getResources()).thenReturn(fallbackResources);
|
||||
|
||||
ResponseEntity<KoboResources> response = service.initialize("test-token");
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
verify(koboResourcesComponent).getResources();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should fall back to local resources when proxy throws exception")
|
||||
void initialize_fallsBackOnProxyException() throws Exception {
|
||||
when(koboServerProxy.proxyCurrentRequest(null, false))
|
||||
.thenThrow(new RuntimeException("Connection refused"));
|
||||
|
||||
ObjectNode fallbackResources = objectMapper.createObjectNode();
|
||||
fallbackResources.put("library_sync", "https://storeapi.kobo.com/v1/library/sync");
|
||||
when(koboResourcesComponent.getResources()).thenReturn(fallbackResources);
|
||||
|
||||
ResponseEntity<KoboResources> response = service.initialize("test-token");
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
verify(koboResourcesComponent).getResources();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should fall back when proxy response has no Resources key")
|
||||
void initialize_fallsBackOnMissingResourcesKey() throws Exception {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("SomeOtherKey", "value");
|
||||
|
||||
when(koboServerProxy.proxyCurrentRequest(null, false))
|
||||
.thenReturn(ResponseEntity.ok(body));
|
||||
|
||||
ObjectNode fallbackResources = objectMapper.createObjectNode();
|
||||
fallbackResources.put("library_sync", "https://storeapi.kobo.com/v1/library/sync");
|
||||
when(koboResourcesComponent.getResources()).thenReturn(fallbackResources);
|
||||
|
||||
ResponseEntity<KoboResources> response = service.initialize("test-token");
|
||||
|
||||
verify(koboResourcesComponent).getResources();
|
||||
assertEquals("http://localhost:8080/kobo/test-token/v1/library/sync",
|
||||
response.getBody().getResources().get("library_sync").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should fall back when proxy returns null response")
|
||||
void initialize_fallsBackOnNullResponse() throws Exception {
|
||||
when(koboServerProxy.proxyCurrentRequest(null, false)).thenReturn(null);
|
||||
|
||||
ObjectNode fallbackResources = objectMapper.createObjectNode();
|
||||
fallbackResources.put("library_sync", "https://storeapi.kobo.com/v1/library/sync");
|
||||
when(koboResourcesComponent.getResources()).thenReturn(fallbackResources);
|
||||
|
||||
ResponseEntity<KoboResources> response = service.initialize("test-token");
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
verify(koboResourcesComponent).getResources();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Response Headers")
|
||||
class ResponseHeaders {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should include x-kobo-apitoken header")
|
||||
void initialize_includesApiTokenHeader() throws Exception {
|
||||
ObjectNode resources = objectMapper.createObjectNode();
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.set("Resources", resources);
|
||||
|
||||
when(koboServerProxy.proxyCurrentRequest(null, false))
|
||||
.thenReturn(ResponseEntity.ok(body));
|
||||
|
||||
ResponseEntity<KoboResources> response = service.initialize("test-token");
|
||||
|
||||
assertEquals("e30=", response.getHeaders().getFirst("x-kobo-apitoken"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package org.booklore.service.kobo;
|
||||
|
||||
import org.booklore.model.dto.KoboSyncSettings;
|
||||
import org.booklore.model.dto.kobo.ChangedReadingState;
|
||||
import org.booklore.model.dto.kobo.KoboReadingState;
|
||||
import org.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.repository.KoboDeletedBookProgressRepository;
|
||||
import org.booklore.repository.UserBookProgressRepository;
|
||||
import org.booklore.util.kobo.BookloreSyncTokenGenerator;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
@DisplayName("KoboLibrarySyncService Tests")
|
||||
class KoboLibrarySyncServiceTest {
|
||||
|
||||
@Mock
|
||||
private BookloreSyncTokenGenerator tokenGenerator;
|
||||
@Mock
|
||||
private KoboLibrarySnapshotService koboLibrarySnapshotService;
|
||||
@Mock
|
||||
private KoboEntitlementService entitlementService;
|
||||
@Mock
|
||||
private KoboDeletedBookProgressRepository koboDeletedBookProgressRepository;
|
||||
@Mock
|
||||
private UserBookProgressRepository userBookProgressRepository;
|
||||
@Mock
|
||||
private KoboServerProxy koboServerProxy;
|
||||
@Mock
|
||||
private ObjectMapper objectMapper;
|
||||
@Mock
|
||||
private KoboSettingsService koboSettingsService;
|
||||
|
||||
@InjectMocks
|
||||
private KoboLibrarySyncService service;
|
||||
|
||||
private KoboSyncSettings testSettings;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
testSettings = new KoboSyncSettings();
|
||||
testSettings.setTwoWayProgressSync(false);
|
||||
when(koboSettingsService.getCurrentUserSettings()).thenReturn(testSettings);
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Sync Filtering - Two-Way Toggle Gating")
|
||||
class TwoWaySyncFiltering {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should filter out web-reader-only entries when two-way sync is OFF")
|
||||
void filterWebReaderOnlyEntries_whenToggleOff() {
|
||||
testSettings.setTwoWayProgressSync(false);
|
||||
|
||||
UserBookProgressEntity webReaderOnly = createProgress(1L);
|
||||
webReaderOnly.setEpubProgress("epubcfi(/6/4)");
|
||||
webReaderOnly.setEpubProgressPercent(50f);
|
||||
webReaderOnly.setLastReadTime(Instant.now());
|
||||
webReaderOnly.setKoboProgressPercent(null);
|
||||
webReaderOnly.setKoboProgressReceivedTime(null);
|
||||
webReaderOnly.setReadStatusModifiedTime(null);
|
||||
|
||||
assertFalse(needsStatusSync(webReaderOnly));
|
||||
assertFalse(needsKoboProgressSync(webReaderOnly));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should include Kobo progress entries regardless of toggle state")
|
||||
void includeKoboProgressEntries_alwaysIncluded() {
|
||||
testSettings.setTwoWayProgressSync(false);
|
||||
|
||||
UserBookProgressEntity koboProgress = createProgress(1L);
|
||||
koboProgress.setKoboProgressPercent(75f);
|
||||
koboProgress.setKoboProgressReceivedTime(Instant.now());
|
||||
koboProgress.setKoboProgressSentTime(null);
|
||||
|
||||
assertTrue(needsKoboProgressSync(koboProgress));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should include status sync entries regardless of toggle state")
|
||||
void includeStatusEntries_alwaysIncluded() {
|
||||
testSettings.setTwoWayProgressSync(false);
|
||||
|
||||
UserBookProgressEntity statusProgress = createProgress(1L);
|
||||
statusProgress.setReadStatus(ReadStatus.READ);
|
||||
statusProgress.setReadStatusModifiedTime(Instant.now());
|
||||
statusProgress.setKoboStatusSentTime(null);
|
||||
|
||||
assertTrue(needsStatusSync(statusProgress));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not filter web-reader entries when two-way sync is ON")
|
||||
void includeWebReaderEntries_whenToggleOn() {
|
||||
testSettings.setTwoWayProgressSync(true);
|
||||
|
||||
UserBookProgressEntity webReaderProgress = createProgress(1L);
|
||||
webReaderProgress.setEpubProgress("epubcfi(/6/4)");
|
||||
webReaderProgress.setEpubProgressPercent(50f);
|
||||
webReaderProgress.setLastReadTime(Instant.now());
|
||||
|
||||
assertNotNull(webReaderProgress.getEpubProgressPercent());
|
||||
assertNotNull(webReaderProgress.getLastReadTime());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Progress Sync Detection")
|
||||
class ProgressSyncDetection {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should detect unsynced Kobo progress when never sent")
|
||||
void needsKoboProgressSync_neverSent() {
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setKoboProgressReceivedTime(Instant.now());
|
||||
progress.setKoboProgressSentTime(null);
|
||||
|
||||
assertTrue(needsKoboProgressSync(progress));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should detect unsynced Kobo progress when received after sent")
|
||||
void needsKoboProgressSync_receivedAfterSent() {
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setKoboProgressReceivedTime(Instant.now());
|
||||
progress.setKoboProgressSentTime(Instant.now().minusSeconds(60));
|
||||
|
||||
assertTrue(needsKoboProgressSync(progress));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not detect sync needed when sent after received")
|
||||
void needsKoboProgressSync_alreadySynced() {
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setKoboProgressReceivedTime(Instant.now().minusSeconds(60));
|
||||
progress.setKoboProgressSentTime(Instant.now());
|
||||
|
||||
assertFalse(needsKoboProgressSync(progress));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not detect sync needed when no progress received")
|
||||
void needsKoboProgressSync_noProgressReceived() {
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setKoboProgressReceivedTime(null);
|
||||
|
||||
assertFalse(needsKoboProgressSync(progress));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Status Sync Detection")
|
||||
class StatusSyncDetection {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should detect unsynced status when never sent")
|
||||
void needsStatusSync_neverSent() {
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setReadStatusModifiedTime(Instant.now());
|
||||
progress.setKoboStatusSentTime(null);
|
||||
|
||||
assertTrue(needsStatusSync(progress));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should detect unsynced status when modified after sent")
|
||||
void needsStatusSync_modifiedAfterSent() {
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setReadStatusModifiedTime(Instant.now());
|
||||
progress.setKoboStatusSentTime(Instant.now().minusSeconds(60));
|
||||
|
||||
assertTrue(needsStatusSync(progress));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not detect status sync when already sent")
|
||||
void needsStatusSync_alreadySynced() {
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setReadStatusModifiedTime(Instant.now().minusSeconds(60));
|
||||
progress.setKoboStatusSentTime(Instant.now());
|
||||
|
||||
assertFalse(needsStatusSync(progress));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not detect status sync when no modification time")
|
||||
void needsStatusSync_noModificationTime() {
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setReadStatusModifiedTime(null);
|
||||
|
||||
assertFalse(needsStatusSync(progress));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Web Reader Progress Sync (Two-Way)")
|
||||
class WebReaderProgressSync {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should detect web reader progress needing sync when toggle ON and lastReadTime after sent")
|
||||
void needsProgressSync_webReaderNewer() {
|
||||
testSettings.setTwoWayProgressSync(true);
|
||||
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setEpubProgress("epubcfi(/6/4)");
|
||||
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() {
|
||||
testSettings.setTwoWayProgressSync(false);
|
||||
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setEpubProgress("epubcfi(/6/4)");
|
||||
progress.setEpubProgressPercent(65f);
|
||||
progress.setLastReadTime(Instant.now());
|
||||
progress.setKoboProgressSentTime(Instant.now().minusSeconds(60));
|
||||
progress.setKoboProgressReceivedTime(null);
|
||||
|
||||
assertFalse(needsProgressSync(progress));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not bounce Kobo progress back immediately")
|
||||
void needsProgressSync_preventBounce() {
|
||||
testSettings.setTwoWayProgressSync(true);
|
||||
|
||||
UserBookProgressEntity progress = createProgress(1L);
|
||||
progress.setEpubProgress("epubcfi(/6/4)");
|
||||
progress.setEpubProgressPercent(65f);
|
||||
progress.setLastReadTime(Instant.now().minusSeconds(120));
|
||||
progress.setKoboProgressSentTime(Instant.now().minusSeconds(60));
|
||||
progress.setKoboProgressReceivedTime(Instant.now());
|
||||
|
||||
assertFalse(needsProgressSyncWebReader(progress));
|
||||
}
|
||||
}
|
||||
|
||||
private UserBookProgressEntity createProgress(Long bookId) {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(bookId);
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setBook(book);
|
||||
return progress;
|
||||
}
|
||||
|
||||
private boolean needsStatusSync(UserBookProgressEntity progress) {
|
||||
Instant modifiedTime = progress.getReadStatusModifiedTime();
|
||||
if (modifiedTime == null) return false;
|
||||
Instant sentTime = progress.getKoboStatusSentTime();
|
||||
return sentTime == null || modifiedTime.isAfter(sentTime);
|
||||
}
|
||||
|
||||
private boolean needsKoboProgressSync(UserBookProgressEntity progress) {
|
||||
Instant sentTime = progress.getKoboProgressSentTime();
|
||||
Instant receivedTime = progress.getKoboProgressReceivedTime();
|
||||
return receivedTime != null && (sentTime == null || receivedTime.isAfter(sentTime));
|
||||
}
|
||||
|
||||
private boolean needsProgressSync(UserBookProgressEntity progress) {
|
||||
if (needsKoboProgressSync(progress)) return true;
|
||||
|
||||
if (testSettings.isTwoWayProgressSync()
|
||||
&& progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null) {
|
||||
Instant sentTime = progress.getKoboProgressSentTime();
|
||||
Instant lastReadTime = progress.getLastReadTime();
|
||||
if (lastReadTime != null && (sentTime == null || lastReadTime.isAfter(sentTime))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean needsProgressSyncWebReader(UserBookProgressEntity progress) {
|
||||
if (!testSettings.isTwoWayProgressSync()) return false;
|
||||
if (progress.getEpubProgress() == null || progress.getEpubProgressPercent() == null) return false;
|
||||
|
||||
Instant lastReadTime = progress.getLastReadTime();
|
||||
Instant sentTime = progress.getKoboProgressSentTime();
|
||||
Instant receivedTime = progress.getKoboProgressReceivedTime();
|
||||
|
||||
if (lastReadTime == null) return false;
|
||||
if (sentTime != null && !lastReadTime.isAfter(sentTime)) return false;
|
||||
return receivedTime == null || lastReadTime.isAfter(receivedTime);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package org.booklore.service.kobo;
|
||||
|
||||
import org.booklore.service.book.BookService;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@DisplayName("KoboThumbnailService Tests")
|
||||
class KoboThumbnailServiceTest {
|
||||
|
||||
@Mock
|
||||
private BookService bookService;
|
||||
|
||||
@InjectMocks
|
||||
private KoboThumbnailService thumbnailService;
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return thumbnail with JPEG content type when image exists")
|
||||
void getThumbnail_existingImage() {
|
||||
String coverHash = "abc123hash";
|
||||
Resource image = new ByteArrayResource(new byte[]{1, 2, 3}) {
|
||||
@Override
|
||||
public boolean exists() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
when(bookService.getBookCover(coverHash)).thenReturn(image);
|
||||
|
||||
ResponseEntity<Resource> response = thumbnailService.getThumbnail(coverHash);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
assertEquals("image/jpeg", response.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE));
|
||||
assertNotNull(response.getBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return 404 when image is null")
|
||||
void getThumbnail_nullImage() {
|
||||
when(bookService.getBookCover("nonexistent")).thenReturn(null);
|
||||
|
||||
ResponseEntity<Resource> response = thumbnailService.getThumbnail("nonexistent");
|
||||
|
||||
assertEquals(404, response.getStatusCode().value());
|
||||
assertNull(response.getBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return 404 when image does not exist")
|
||||
void getThumbnail_imageNotExists() {
|
||||
Resource image = mock(Resource.class);
|
||||
when(image.exists()).thenReturn(false);
|
||||
when(bookService.getBookCover("missing")).thenReturn(image);
|
||||
|
||||
ResponseEntity<Resource> response = thumbnailService.getThumbnail("missing");
|
||||
|
||||
assertEquals(404, response.getStatusCode().value());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should pass cover hash to book service")
|
||||
void getThumbnail_passesCorrectHash() {
|
||||
String coverHash = "unique-hash-456";
|
||||
when(bookService.getBookCover(coverHash)).thenReturn(null);
|
||||
|
||||
thumbnailService.getThumbnail(coverHash);
|
||||
|
||||
verify(bookService).getBookCover(coverHash);
|
||||
}
|
||||
}
|
||||
@@ -273,6 +273,8 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
|
||||
// Navigate to saved position if progress exists, otherwise go to first page
|
||||
if (book.epubProgress?.cfi) {
|
||||
return this.viewManager.goTo(book.epubProgress.cfi);
|
||||
} else if (book.epubProgress?.percentage && book.epubProgress.percentage > 0) {
|
||||
return this.viewManager.goToFraction(book.epubProgress.percentage / 100);
|
||||
} else {
|
||||
return this.viewManager.goTo(0);
|
||||
}
|
||||
|
||||
+33
-26
@@ -49,16 +49,18 @@
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">{{ t('kobo.autoAddLabel') }}</label>
|
||||
<label class="setting-label">{{ t('kobo.twoWaySyncLabel') }}</label>
|
||||
<p-toggle-switch
|
||||
id="autoAddToShelf"
|
||||
name="autoAddToShelf"
|
||||
[(ngModel)]="koboSyncSettings.autoAddToShelf"
|
||||
(ngModelChange)="onAutoAddToggle()">
|
||||
id="twoWayProgressSync"
|
||||
name="twoWayProgressSync"
|
||||
[(ngModel)]="koboSyncSettings.twoWayProgressSync"
|
||||
(ngModelChange)="onTwoWaySyncToggle()">
|
||||
</p-toggle-switch>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
{{ t('kobo.autoAddDesc') }}
|
||||
{{ t('kobo.twoWaySyncDesc') }}
|
||||
<br>
|
||||
<strong>{{ t('kobo.twoWaySyncNote') }}</strong>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -95,6 +97,14 @@
|
||||
(onClick)="toggleShowToken()"
|
||||
[disabled]="!koboSyncSettings.token">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-refresh"
|
||||
outlined="true"
|
||||
severity="warn"
|
||||
size="small"
|
||||
(onClick)="confirmRegenerateToken()"
|
||||
[disabled]="!credentialsSaved">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
@@ -103,26 +113,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">{{ t('kobo.tokenManagement') }}</label>
|
||||
<p-button
|
||||
icon="pi pi-refresh"
|
||||
outlined="true"
|
||||
severity="warn"
|
||||
size="small"
|
||||
[label]="t('kobo.regenerateToken')"
|
||||
(onClick)="confirmRegenerateToken()"
|
||||
[disabled]="!credentialsSaved">
|
||||
</p-button>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
{{ t('kobo.tokenManagementDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
@@ -170,6 +160,23 @@
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">{{ t('kobo.autoAddLabel') }}</label>
|
||||
<p-toggle-switch
|
||||
id="autoAddToShelf"
|
||||
name="autoAddToShelf"
|
||||
[(ngModel)]="koboSyncSettings.autoAddToShelf"
|
||||
(ngModelChange)="onAutoAddToggle()">
|
||||
</p-toggle-switch>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
{{ t('kobo.autoAddDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+10
-1
@@ -60,7 +60,8 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
|
||||
syncEnabled: false,
|
||||
progressMarkAsReadingThreshold: 1,
|
||||
progressMarkAsFinishedThreshold: 99,
|
||||
autoAddToShelf: true
|
||||
autoAddToShelf: true,
|
||||
twoWayProgressSync: false
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
@@ -121,6 +122,7 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
|
||||
this.koboSyncSettings.progressMarkAsReadingThreshold = settings.progressMarkAsReadingThreshold ?? 1;
|
||||
this.koboSyncSettings.progressMarkAsFinishedThreshold = settings.progressMarkAsFinishedThreshold ?? 99;
|
||||
this.koboSyncSettings.autoAddToShelf = settings.autoAddToShelf ?? false;
|
||||
this.koboSyncSettings.twoWayProgressSync = settings.twoWayProgressSync ?? false;
|
||||
this.credentialsSaved = !!settings.token;
|
||||
},
|
||||
error: () => {
|
||||
@@ -227,6 +229,13 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
|
||||
this.updateKoboSettings(message);
|
||||
}
|
||||
|
||||
onTwoWaySyncToggle() {
|
||||
const message = this.koboSyncSettings.twoWayProgressSync
|
||||
? this.t.translate('settingsDevice.kobo.twoWaySyncEnabled')
|
||||
: this.t.translate('settingsDevice.kobo.twoWaySyncDisabled');
|
||||
this.updateKoboSettings(message);
|
||||
}
|
||||
|
||||
private updateKoboSettings(successMessage: string) {
|
||||
this.koboService.updateSettings(this.koboSyncSettings).subscribe({
|
||||
next: () => {
|
||||
|
||||
+1
@@ -9,6 +9,7 @@ export interface KoboSyncSettings {
|
||||
progressMarkAsReadingThreshold?: number;
|
||||
progressMarkAsFinishedThreshold?: number;
|
||||
autoAddToShelf: boolean;
|
||||
twoWayProgressSync: boolean;
|
||||
hardcoverApiKey?: string;
|
||||
hardcoverSyncEnabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -94,6 +94,11 @@
|
||||
"syncEnabled": "Kobo sync enabled",
|
||||
"syncDisabled": "Kobo sync disabled",
|
||||
"progressUpdated": "Progress thresholds updated successfully",
|
||||
"twoWaySyncLabel": "Two-Way Reading Progress Sync",
|
||||
"twoWaySyncDesc": "Enable bidirectional sync between Booklore's web reader and your Kobo device. Reading progress made on either platform will be reflected on the other.",
|
||||
"twoWaySyncNote": "Note: Due to different position formats, sync accuracy is best-effort. In most cases progress will be accurate to the chapter level.",
|
||||
"twoWaySyncEnabled": "Two-way progress sync enabled",
|
||||
"twoWaySyncDisabled": "Two-way progress sync disabled",
|
||||
"autoAddEnabled": "New books will be automatically added to Kobo shelf",
|
||||
"autoAddDisabled": "Auto-add to Kobo shelf disabled",
|
||||
"pros": "Pros:",
|
||||
|
||||
@@ -94,6 +94,11 @@
|
||||
"syncEnabled": "Sincronización Kobo habilitada",
|
||||
"syncDisabled": "Sincronización Kobo deshabilitada",
|
||||
"progressUpdated": "Umbrales de progreso actualizados correctamente",
|
||||
"twoWaySyncLabel": "Sincronización bidireccional del progreso de lectura",
|
||||
"twoWaySyncDesc": "Habilita la sincronización bidireccional entre el lector web de Booklore y tu dispositivo Kobo. El progreso de lectura realizado en cualquiera de las plataformas se reflejará en la otra.",
|
||||
"twoWaySyncNote": "Nota: Debido a los diferentes formatos de posición, la precisión de la sincronización es aproximada. En la mayoría de los casos, el progreso será preciso a nivel de capítulo.",
|
||||
"twoWaySyncEnabled": "Sincronización bidireccional de progreso habilitada",
|
||||
"twoWaySyncDisabled": "Sincronización bidireccional de progreso deshabilitada",
|
||||
"autoAddEnabled": "Los libros nuevos se añadirán automáticamente al estante Kobo",
|
||||
"autoAddDisabled": "Auto-añadir al estante Kobo deshabilitado",
|
||||
"pros": "Ventajas:",
|
||||
|
||||
Reference in New Issue
Block a user