feat(kobo): sync personal ratings from kobo (#1165)

This commit is contained in:
James Ward
2026-05-09 19:10:20 -04:00
committed by GitHub
parent 60ffb09795
commit 7de39b8ef4
4 changed files with 276 additions and 0 deletions
@@ -46,6 +46,7 @@ public class KoboController {
private final KoboInitializationService koboInitializationService;
private final BookService bookService;
private final KoboReadingStateService koboReadingStateService;
private final KoboRatingService koboRatingService;
private final KoboEntitlementService koboEntitlementService;
private final KoboDeviceAuthService koboDeviceAuthService;
private final KoboLibrarySyncService koboLibrarySyncService;
@@ -253,6 +254,25 @@ public class KoboController {
}
@Operation(summary = "Update Rating", description = "Updates the personal rating for a book given the Kobo star rating.")
@ApiResponse(responseCode = "200", description = "Personal rating has been updated.")
@PostMapping("/v1/products/{bookId}/rating/{rating}")
public ResponseEntity<?> putRating(
@AuthenticationPrincipal BookLoreUser user,
@Parameter(description = "Book ID") @PathVariable String bookId,
@Parameter(description = "Book Rating") @PathVariable int rating
) {
if (StringUtils.isNumeric(bookId)) {
return koboRatingService.updatePersonalRating(user, Long.parseLong(bookId), rating);
}
if (isForwardingToKoboStore()) {
return koboServerProxy.proxyCurrentRequest();
}
return ResponseEntity.notFound().build();
}
@Operation(summary = "Catch-all for Kobo API", description = "Catch-all endpoint for unhandled Kobo API requests.")
@ApiResponse(responseCode = "200", description = "Request proxied successfully")
@RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.PATCH})
@@ -34,6 +34,7 @@ public class KoboInitializationService {
Map.entry("post_analytics_event", new String[]{"v1", "analytics", "event"}),
Map.entry("reading_state", new String[]{"v1", "library", "{Ids}", "state"}),
Map.entry("user_profile", new String[]{"v1", "user", "profile"}),
Map.entry("user_ratings", new String[]{"v1", "products", "{ProductId}", "rating", "{Rating}"}),
Map.entry("deals", new String[]{"v1", "deals"})
);
@@ -0,0 +1,82 @@
package org.booklore.service.kobo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.repository.BookRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@RequiredArgsConstructor
public class KoboRatingService {
private final BookRepository bookRepository;
private final UserBookProgressRepository userBookProgressRepository;
private boolean userHasAccess(BookLoreUser user, BookEntity book) {
if (user.getPermissions().isAdmin()) {
return true;
}
if (user.getAssignedLibraries() == null) {
return false;
}
Long libraryId = book.getLibrary().getId();
return user.getAssignedLibraries().stream()
.map(Library::getId)
.anyMatch(libraryId::equals);
}
private UserBookProgressEntity getUserBookProgress(BookLoreUser user, BookEntity book) {
return userBookProgressRepository
.findByUserIdAndBookId(user.getId(), book.getId())
.orElseGet(
() -> (
UserBookProgressEntity.builder()
.user(BookLoreUserEntity.builder().id(user.getId()).build())
.book(book)
.build()
)
);
}
@Transactional
public ResponseEntity<?> updatePersonalRating(BookLoreUser user, long bookId, int rating) {
if (user == null) {
// If the user is not allowed to access the book, it doesn't exist to them.
log.debug("User is not authenticated to rate book {}", bookId);
throw ApiError.BOOK_NOT_FOUND.createException(bookId);
}
BookEntity book = bookRepository.findById(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (!userHasAccess(user, book)) {
// If the user is not allowed to access the book, it doesn't exist to them.
log.info("User {} does not have access to rate book {}", user.getId(), bookId);
throw ApiError.BOOK_NOT_FOUND.createException(bookId);
}
UserBookProgressEntity progress = getUserBookProgress(user, book);
// Kobo rating is out of 5, but personal ratings are out of 10.
int personalRating = Math.clamp((long) rating * 2, 0, 10);
progress.setPersonalRating(personalRating);
userBookProgressRepository.save(progress);
return ResponseEntity.ok().build();
}
}
@@ -0,0 +1,173 @@
package org.booklore.service.kobo;
import org.booklore.exception.APIException;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.repository.BookRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.ResponseEntity;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class KoboRatingServiceTest {
@Mock
private BookRepository bookRepository;
@Mock
private UserBookProgressRepository userBookProgressRepository;
@Captor
ArgumentCaptor<UserBookProgressEntity> progressCaptor;
@InjectMocks
private KoboRatingService service;
private BookLoreUser getFakeUser(long userId, boolean isAdmin, List<Library> libraries) {
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(isAdmin);
return BookLoreUser.builder()
.id(userId)
.permissions(
permissions
)
.assignedLibraries(libraries)
.build();
}
private BookEntity getFakeBook(long bookId, long libraryId) {
LibraryEntity library = LibraryEntity.builder()
.id(libraryId)
.build();
return BookEntity.builder()
.id(bookId)
.library(library)
.build();
}
@Test
void updatePersonalRating_throwsForNullUser() {
assertThrows(APIException.class, () -> service.updatePersonalRating(null, 123L, 0));
}
@Test
void updatePersonalRating_throwsForNoAccessUser() {
BookLoreUser user = getFakeUser(1L, false, List.of());
when(bookRepository.findById(123L)).thenReturn(Optional.of(getFakeBook(123L, 2L)));
assertThrows(APIException.class, () -> service.updatePersonalRating(user, 123L, 0));
}
@Test
void updatePersonalRating_throwsForWrongLibraryUser() {
BookLoreUser user = getFakeUser(1L, false, List.of(Library.builder().id(1L).build()));
when(bookRepository.findById(123L)).thenReturn(Optional.of(getFakeBook(123L, 2L)));
assertThrows(APIException.class, () -> service.updatePersonalRating(user, 123L, 0));
}
@Test
void updatePersonalRating_allowsAdmin() {
BookLoreUser user = getFakeUser(1L, true, List.of());
when(bookRepository.findById(123L)).thenReturn(Optional.of(getFakeBook(123L, 2L)));
ResponseEntity<?> response = service.updatePersonalRating(user, 123L, 0);
assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
void updatePersonalRating_allowsLibrary() {
BookLoreUser user = getFakeUser(1L, false, List.of(Library.builder().id(2L).build()));
when(bookRepository.findById(123L)).thenReturn(Optional.of(getFakeBook(123L, 2L)));
ResponseEntity<?> response = service.updatePersonalRating(user, 123L, 0);
assertTrue(response.getStatusCode().is2xxSuccessful());
}
@Test
void updatePersonalRating_sideEffectSavesUserProgress() {
BookLoreUser user = getFakeUser(1L, true, List.of());
when(bookRepository.findById(123L)).thenReturn(Optional.of(getFakeBook(123L, 2L)));
service.updatePersonalRating(user, 123L, 0);
verify(userBookProgressRepository).save(progressCaptor.capture());
UserBookProgressEntity progress = progressCaptor.getValue();
assertEquals(1L, progress.getUser().getId());
assertEquals(123L, progress.getBook().getId());
}
@Test
void updatePersonalRating_sideEffectDoublesRating() {
BookLoreUser user = getFakeUser(1L, true, List.of());
when(bookRepository.findById(123L)).thenReturn(Optional.of(getFakeBook(123L, 2L)));
service.updatePersonalRating(user, 123L, 4);
verify(userBookProgressRepository).save(progressCaptor.capture());
UserBookProgressEntity progress = progressCaptor.getValue();
assertEquals(8, progress.getPersonalRating());
}
@Test
void updatePersonalRating_sideEffectMinimumRating() {
BookLoreUser user = getFakeUser(1L, true, List.of());
when(bookRepository.findById(123L)).thenReturn(Optional.of(getFakeBook(123L, 2L)));
service.updatePersonalRating(user, 123L, -1);
verify(userBookProgressRepository).save(progressCaptor.capture());
UserBookProgressEntity progress = progressCaptor.getValue();
assertEquals(0, progress.getPersonalRating());
}
@Test
void updatePersonalRating_sideEffectMaximumRating() {
BookLoreUser user = getFakeUser(1L, true, List.of());
when(bookRepository.findById(123L)).thenReturn(Optional.of(getFakeBook(123L, 2L)));
service.updatePersonalRating(user, 123L, 6);
verify(userBookProgressRepository).save(progressCaptor.capture());
UserBookProgressEntity progress = progressCaptor.getValue();
assertEquals(10, progress.getPersonalRating());
}
}