fix(kobo): fix progress sync graph error (#858)

This commit is contained in:
Alex
2026-04-25 14:31:45 +01:00
committed by GitHub
parent bdd54a4565
commit 59fcfb1689
7 changed files with 167 additions and 7 deletions
@@ -15,6 +15,7 @@ import java.util.Optional;
@Repository
public interface UserBookFileProgressRepository extends JpaRepository<UserBookFileProgressEntity, Long> {
@EntityGraph(attributePaths = {"bookFile", "bookFile.book", "bookFile.book.libraryPath", "bookFile.book.library"})
Optional<UserBookFileProgressEntity> findByUserIdAndBookFileId(Long userId, Long bookFileId);
@Query("""
@@ -52,7 +53,7 @@ public interface UserBookFileProgressRepository extends JpaRepository<UserBookFi
@Param("bookId") Long bookId
);
@EntityGraph(attributePaths = {"bookFile", "bookFile.book"})
@EntityGraph(attributePaths = {"bookFile", "bookFile.book", "bookFile.book.libraryPath", "bookFile.book.library"})
@Query("""
SELECT ubfp FROM UserBookFileProgressEntity ubfp
WHERE ubfp.user.id = :userId
@@ -63,7 +64,7 @@ public interface UserBookFileProgressRepository extends JpaRepository<UserBookFi
@Param("bookIds") Iterable<Long> bookIds
);
@EntityGraph(attributePaths = {"bookFile", "bookFile.book"})
@EntityGraph(attributePaths = {"bookFile", "bookFile.book", "bookFile.book.libraryPath", "bookFile.book.library"})
@Query("""
SELECT ubfp FROM UserBookFileProgressEntity ubfp
WHERE ubfp.user.id = :userId
@@ -7,6 +7,7 @@ import org.booklore.model.dto.RatingDistributionDto;
import org.booklore.model.dto.StatusDistributionDto;
import org.booklore.model.entity.UserBookProgressEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
@@ -25,10 +26,22 @@ public interface UserBookProgressRepository extends JpaRepository<UserBookProgre
Optional<UserBookProgressEntity> findByUserIdAndBookId(Long userId, Long bookId);
@EntityGraph(attributePaths = {"book", "book.bookFiles", "book.library", "book.libraryPath"})
@Query("""
SELECT DISTINCT ubp FROM UserBookProgressEntity ubp
WHERE ubp.user.id = :userId
AND ubp.book.id = :bookId
""")
Optional<UserBookProgressEntity> findByUserIdAndBookIdForKoboSync(
@Param("userId") Long userId,
@Param("bookId") Long bookId
);
List<UserBookProgressEntity> findByUserIdAndBookIdIn(Long userId, Set<Long> bookIds);
@EntityGraph(attributePaths = {"book", "book.bookFiles", "book.library", "book.libraryPath"})
@Query("""
SELECT ubp FROM UserBookProgressEntity ubp
SELECT DISTINCT ubp FROM UserBookProgressEntity ubp
WHERE ubp.user.id = :userId
AND ubp.book.id IN (
SELECT ksb.bookId FROM KoboSnapshotBookEntity ksb
@@ -256,7 +256,7 @@ public class KoboEntitlementService {
.orElse(null);
Optional<UserBookProgressEntity> userProgress = progressRepository
.findByUserIdAndBookId(userId, book.getId());
.findByUserIdAndBookIdForKoboSync(userId, book.getId());
UserBookFileProgressEntity fileProgress = findSyncedEpubFileProgress(userId, book).orElse(null);
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
@@ -156,7 +156,7 @@ public class KoboReadingStateService {
try {
Long bookId = Long.parseLong(entitlementId);
UserBookFileProgressEntity fileProgress = findSyncedEpubFileProgress(userId, bookId).orElse(null);
progressRepository.findByUserIdAndBookId(userId, bookId)
progressRepository.findByUserIdAndBookIdForKoboSync(userId, bookId)
.filter(readingStateBuilder::shouldUseWebReaderProgress)
.ifPresent(progress -> state.setCurrentBookmark(
readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress)));
@@ -171,7 +171,7 @@ public class KoboReadingStateService {
BookLoreUser user = authenticationService.getAuthenticatedUser();
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
return progressRepository.findByUserIdAndBookId(user.getId(), bookId)
return progressRepository.findByUserIdAndBookIdForKoboSync(user.getId(), bookId)
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
.map(progress -> readingStateBuilder.buildReadingStateFromProgress(
entitlementId,
@@ -311,7 +311,7 @@ public class KoboReadingStateService {
}
private Optional<UserBookFileProgressEntity> findSyncedEpubFileProgress(Long userId, Long bookId) {
return bookRepository.findById(bookId)
return bookRepository.findByIdWithBookFiles(bookId)
.flatMap(book -> findSyncedEpubFileProgress(userId, book));
}
@@ -7,6 +7,7 @@ import org.booklore.model.entity.*;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.booklore.service.task.TaskCronService;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.Assertions;
@@ -23,6 +24,7 @@ import org.springframework.test.context.TestPropertySource;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
@@ -66,6 +68,9 @@ class HibernateRegressionTest {
@Autowired
private BookRepository bookRepository;
@Autowired
private UserBookProgressRepository userBookProgressRepository;
@PersistenceContext
private EntityManager entityManager;
@@ -90,6 +95,137 @@ class HibernateRegressionTest {
assertThat(bookRepository).isNotNull();
}
@Nested
class KoboSyncProgressGraph {
@Test
void findAllBooksNeedingKoboSync_loadsBookFilesForDetachedUse() {
KoboProgressFixture fixture = createKoboProgressFixture();
entityManager.flush();
entityManager.clear();
List<UserBookProgressEntity> result = userBookProgressRepository.findAllBooksNeedingKoboSync(
fixture.userId(),
fixture.snapshotId()
);
assertThat(result).hasSize(1);
UserBookProgressEntity progress = result.getFirst();
entityManager.clear();
BookFileEntity primaryFile = progress.getBook().getPrimaryBookFile();
assertThat(primaryFile).isNotNull();
assertThat(primaryFile.getBookType()).isEqualTo(BookFileType.EPUB);
}
@Test
void findByUserIdAndBookIdForKoboSync_loadsBookFilesForDetachedUse() {
KoboProgressFixture fixture = createKoboProgressFixture();
entityManager.flush();
entityManager.clear();
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookIdForKoboSync(fixture.userId(), fixture.bookId())
.orElseThrow();
entityManager.clear();
BookFileEntity primaryFile = progress.getBook().getPrimaryBookFile();
assertThat(primaryFile).isNotNull();
assertThat(primaryFile.getCurrentHash()).isEqualTo("kobo-hash-" + fixture.bookId());
}
@Test
void findByIdWithBookFiles_loadsBookFilesForDetachedUse() {
KoboProgressFixture fixture = createKoboProgressFixture();
entityManager.flush();
entityManager.clear();
BookEntity book = bookRepository.findByIdWithBookFiles(fixture.bookId()).orElseThrow();
entityManager.clear();
BookFileEntity primaryFile = book.getPrimaryBookFile();
assertThat(primaryFile).isNotNull();
assertThat(primaryFile.getCurrentHash()).isEqualTo("kobo-hash-" + fixture.bookId());
}
private KoboProgressFixture createKoboProgressFixture() {
String suffix = UUID.randomUUID().toString();
LibraryEntity library = LibraryEntity.builder()
.name("Kobo Graph Library " + suffix)
.icon("book")
.watch(false)
.formatPriority(new ArrayList<>(List.of(BookFileType.EPUB)))
.build();
entityManager.persist(library);
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
.library(library)
.path("/kobo/books/" + suffix)
.build();
entityManager.persist(libraryPath);
BookEntity book = BookEntity.builder()
.library(library)
.libraryPath(libraryPath)
.addedOn(Instant.now())
.deleted(false)
.build();
entityManager.persist(book);
entityManager.flush();
BookFileEntity bookFile = BookFileEntity.builder()
.book(book)
.fileName("book.epub")
.fileSubPath(".")
.isBookFormat(true)
.bookType(BookFileType.EPUB)
.fileSizeKb(256L)
.currentHash("kobo-hash-" + book.getId())
.build();
book.getBookFiles().add(bookFile);
entityManager.persist(bookFile);
BookLoreUserEntity user = BookLoreUserEntity.builder()
.username("kobo-user-" + suffix)
.passwordHash("password")
.isDefaultPassword(false)
.name("Kobo User")
.build();
entityManager.persist(user);
UserBookProgressEntity progress = UserBookProgressEntity.builder()
.user(user)
.book(book)
.epubProgress("epubcfi(/6/2!/4/2/2:1)")
.epubProgressPercent(42f)
.lastReadTime(Instant.now())
.build();
entityManager.persist(progress);
KoboLibrarySnapshotEntity snapshot = KoboLibrarySnapshotEntity.builder()
.id("snapshot-" + suffix)
.userId(user.getId())
.createdDate(LocalDateTime.now())
.build();
entityManager.persist(snapshot);
KoboSnapshotBookEntity snapshotBook = KoboSnapshotBookEntity.builder()
.snapshot(snapshot)
.bookId(book.getId())
.fileHash(bookFile.getCurrentHash())
.synced(false)
.build();
entityManager.persist(snapshotBook);
return new KoboProgressFixture(user.getId(), book.getId(), snapshot.getId());
}
private record KoboProgressFixture(Long userId, Long bookId, String snapshotId) {
}
}
@Nested
class LibraryPathBackReference {
@@ -126,6 +126,10 @@ class KoboEntitlementServiceTest {
user = BookLoreUser.builder().id(1L).permissions(permissions).build();
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(koboSpanMapService.getValidMaps(anyMap())).thenReturn(Map.of());
when(progressRepository.findByUserIdAndBookIdForKoboSync(anyLong(), anyLong()))
.thenAnswer(invocation -> progressRepository.findByUserIdAndBookId(
invocation.getArgument(0),
invocation.getArgument(1)));
}
@Test
@@ -105,6 +105,12 @@ class KoboReadingStateServiceTest {
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(testSettings);
lenient().when(progressRepository.findByUserIdAndBookIdForKoboSync(anyLong(), anyLong()))
.thenAnswer(invocation -> progressRepository.findByUserIdAndBookId(
invocation.getArgument(0),
invocation.getArgument(1)));
lenient().when(bookRepository.findByIdWithBookFiles(anyLong()))
.thenAnswer(invocation -> bookRepository.findById(invocation.getArgument(0)));
lenient().when(repository
.findFirstByEntitlementIdAndUserIdIsNullOrderByPriorityTimestampDescLastModifiedStringDescIdDesc(
anyString()))