feat(api): allow disable of kobo store proxy (#337)

* chore(api): fix typing for kobo sync service

* feat(api): add more paths for grimmory/kobo API

* fix(api): disable kobo features if kobo is unavailable

* feat(api): add proxy flag to kobo setting

* feat(api): adhere to kobo proxy enabled flag

* feat(ui): add forward requests toggle

* fix(ui): load setting

* style: use assertNotNull

* fix: reduce advertised routes

this cuts down the advertised routes - in particular to reduce the
number of auth-related requests we will be taking on.  we may eventually
want to do this but I want to reduce the amount of change in this PR

* fix: undo disable of kobo features

This reverts commit 1b242fa6614084b05c58ff3b24e142adb1bcf729.
This commit is contained in:
James Ward
2026-04-22 17:27:05 -04:00
committed by Zach Yale
parent 34042be1c9
commit 91c19739dc
12 changed files with 249 additions and 144 deletions
@@ -11,10 +11,12 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Shelf;
import org.booklore.model.dto.kobo.*;
import org.booklore.service.ShelfService;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.book.BookDownloadService;
import org.booklore.service.book.BookService;
import org.booklore.service.kobo.*;
@@ -27,9 +29,7 @@ import org.springframework.web.bind.annotation.*;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.JsonNode;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
@@ -42,6 +42,7 @@ public class KoboController {
private static final Pattern KOBO_V1_PRODUCTS_NEXTREAD_PATTERN = Pattern.compile(".*/v1/products/\\d+/nextread.*");
private String token;
private final AppSettingService appSettingService;
private final KoboServerProxy koboServerProxy;
private final KoboInitializationService koboInitializationService;
private final BookService bookService;
@@ -53,6 +54,10 @@ public class KoboController {
private final ShelfService shelfService;
private final BookDownloadService bookDownloadService;
private boolean isForwardingToKoboStore() {
return appSettingService.getAppSettings().getKoboSettings().isForwardToKoboStore();
}
@ModelAttribute
public void captureToken(@PathVariable("token") String token) {
this.token = token;
@@ -68,7 +73,7 @@ public class KoboController {
@Operation(summary = "Sync Kobo library", description = "Sync the user's Kobo library.")
@ApiResponse(responseCode = "200", description = "Library synced successfully")
@GetMapping("/v1/library/sync")
public ResponseEntity<?> syncLibrary(@AuthenticationPrincipal BookLoreUser user) {
public ResponseEntity<List<Entitlement>> syncLibrary(@AuthenticationPrincipal BookLoreUser user) {
return koboLibrarySyncService.syncLibrary(user, token);
}
@@ -97,10 +102,14 @@ public class KoboController {
return koboThumbnailService.getThumbnail(imageId);
}
return ResponseEntity
.status(HttpStatus.TEMPORARY_REDIRECT)
.location(koboServerProxy.getKoboCDNCoverUri(imageId, width, height, isGreyscale))
.build();
if (isForwardingToKoboStore()) {
return ResponseEntity
.status(HttpStatus.TEMPORARY_REDIRECT)
.location(koboServerProxy.getKoboCDNCoverUri(imageId, width, height, isGreyscale))
.build();
}
throw ApiError.GENERIC_NOT_FOUND.createException("Not Found");
}
@Operation(summary = "Authenticate Kobo device", description = "Authenticate a Kobo device.")
@@ -116,8 +125,10 @@ public class KoboController {
public ResponseEntity<?> getBookMetadata(@Parameter(description = "Book ID") @PathVariable String bookId) {
if (StringUtils.isNumeric(bookId)) {
return ResponseEntity.ok(List.of(koboEntitlementService.getMetadataForBook(Long.parseLong(bookId), token)));
} else {
} else if(isForwardingToKoboStore()) {
return koboServerProxy.proxyCurrentRequest(null, false);
} else {
throw ApiError.GENERIC_NOT_FOUND.createException("Not Found");
}
}
@@ -127,8 +138,10 @@ public class KoboController {
public ResponseEntity<?> getState(@Parameter(description = "Book ID") @PathVariable String bookId) {
if (StringUtils.isNumeric(bookId)) {
return ResponseEntity.ok(new KoboReadingStateList(koboReadingStateService.getReadingState(bookId)));
} else {
} else if (isForwardingToKoboStore()) {
return koboServerProxy.proxyCurrentRequest(null, false);
} else {
throw ApiError.GENERIC_NOT_FOUND.createException("Not Found");
}
}
@@ -140,8 +153,10 @@ public class KoboController {
@Parameter(description = "Reading state update body") @RequestBody KoboReadingStateRequest body) {
if (StringUtils.isNumeric(bookId)) {
return ResponseEntity.ok(koboReadingStateService.saveReadingState(body.getReadingStates()));
} else {
} else if (isForwardingToKoboStore()) {
return koboServerProxy.proxyCurrentRequest(body, false);
} else {
throw ApiError.GENERIC_NOT_FOUND.createException("Not Found");
}
}
@@ -161,8 +176,10 @@ public class KoboController {
public void downloadBook(@Parameter(description = "Book ID") @PathVariable String bookId, HttpServletResponse response) {
if (StringUtils.isNumeric(bookId)) {
bookDownloadService.downloadKoboBook(Long.parseLong(bookId), response);
} else {
} else if (isForwardingToKoboStore()) {
koboServerProxy.proxyCurrentRequest(null, false);
} else {
throw ApiError.GENERIC_NOT_FOUND.createException("Not Found");
}
}
@@ -176,8 +193,10 @@ public class KoboController {
bookService.assignShelvesToBooks(Set.of(Long.valueOf(bookId)), Set.of(), Set.of(userKoboShelf.getId()));
}
return ResponseEntity.ok().build();
} else {
} else if (isForwardingToKoboStore()) {
return koboServerProxy.proxyCurrentRequest(null, false);
} else {
throw ApiError.GENERIC_NOT_FOUND.createException("Not Found");
}
}
@@ -186,12 +205,20 @@ public class KoboController {
@RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.PATCH})
public ResponseEntity<JsonNode> catchAll(HttpServletRequest request, @RequestBody(required = false) Object body) {
String path = request.getRequestURI();
if (path.contains("/v1/analytics/event")) {
// Never pass along analytics events.
return ResponseEntity.ok().build();
}
if (KOBO_V1_PRODUCTS_NEXTREAD_PATTERN.matcher(path).matches()) {
return ResponseEntity.ok().build();
}
return koboServerProxy.proxyCurrentRequest(body, false);
if (isForwardingToKoboStore()) {
return koboServerProxy.proxyCurrentRequest(body, false);
}
return ResponseEntity.ok().build();
}
}
@@ -24,4 +24,6 @@ public class KoboSettings {
private boolean forceEnableHyphenation = false;
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
private int conversionImageCompressionPercentage = 85;
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
private boolean forwardToKoboStore = false;
}
@@ -3,6 +3,7 @@ package org.booklore.service.kobo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.kobo.KoboResources;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.util.kobo.KoboUrlBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
@@ -11,39 +12,67 @@ import tools.jackson.core.JacksonException;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.node.ObjectNode;
import java.util.Map;
@Slf4j
@Service
@RequiredArgsConstructor
public class KoboInitializationService {
private final AppSettingService appSettingService;
private final KoboServerProxy koboServerProxy;
private final KoboResourcesComponent koboResourcesComponent;
private final KoboUrlBuilder koboUrlBuilder;
private static final Map<String, String[]> initializationResources = Map.<String, String[]>ofEntries(
Map.entry("delete_entitlement", new String[]{"v1", "library", "{Ids}"}),
Map.entry("get_tests_request", new String[]{"v1", "analytics", "gettests"}),
Map.entry("library_book", new String[]{"v1", "user", "library", "books", "{LibraryItemId}"}),
Map.entry("library_metadata", new String[]{"v1", "library", "{Ids}", "metadata"}),
Map.entry("library_search", new String[]{"v1", "library", "search"}),
Map.entry("library_sync", new String[]{"v1", "library", "sync"}),
Map.entry("post_analytics_event", new String[]{"v1", "analytics", "event"}),
Map.entry("reading_state", new String[]{"v1", "library", "{Ids}", "state"})
);
private boolean isForwardingToKoboStore() {
return appSettingService.getAppSettings().getKoboSettings().isForwardToKoboStore();
}
public ResponseEntity<KoboResources> initialize(String token) throws JacksonException {
JsonNode resources;
ObjectNode resources = null;
JsonNode body = null;
try {
var response = koboServerProxy.proxyCurrentRequest(null, false);
body = response != null ? response.getBody() : null;
} catch (Exception e) {
log.warn("Failed to get response from Kobo /v1/initialization, fallback to noproxy", e);
if (isForwardingToKoboStore()) {
try {
ResponseEntity<JsonNode> response = koboServerProxy.proxyCurrentRequest(null, false);
JsonNode body = response.getBody();
JsonNode bodyResources = body == null ? null : body.get("Resources");
if (bodyResources instanceof ObjectNode objectNode) {
resources = objectNode;
} else {
log.warn("Unexpected response from Kobo /v1/initialization, fallback to noproxy");
}
} catch (Exception e) {
log.warn("Failed to get response from Kobo /v1/initialization, fallback to noproxy", e);
}
}
resources = (body != null && body.has("Resources"))
? body.get("Resources")
: koboResourcesComponent.getResources();
if (resources instanceof ObjectNode objectNode) {
UriComponentsBuilder baseBuilder = koboUrlBuilder.baseBuilder();
objectNode.put("image_host", baseBuilder.build().toUriString());
objectNode.put("image_url_template", koboUrlBuilder.imageUrlTemplate(token));
objectNode.put("image_url_quality_template", koboUrlBuilder.imageUrlQualityTemplate(token));
objectNode.put("library_sync", koboUrlBuilder.librarySyncUrl(token));
if (resources == null) {
resources = koboResourcesComponent.getResources();
}
UriComponentsBuilder baseBuilder = koboUrlBuilder.baseBuilder();
for (String name : initializationResources.keySet()) {
resources.put(name, koboUrlBuilder.withBaseUrl(token, initializationResources.get(name)));
}
// Build extra routes for CDN
resources.put("image_host", baseBuilder.build().toUriString());
resources.put("image_url_template", koboUrlBuilder.imageUrlTemplate(token));
resources.put("image_url_quality_template", koboUrlBuilder.imageUrlQualityTemplate(token));
return ResponseEntity.ok()
.header("x-kobo-apitoken", "e30=")
.body(new KoboResources(resources));
@@ -11,6 +11,7 @@ import org.booklore.model.entity.KoboSnapshotBookEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.repository.KoboDeletedBookProgressRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.util.RequestUtils;
import org.booklore.util.kobo.BookloreSyncTokenGenerator;
import org.springframework.data.domain.Page;
@@ -38,6 +39,7 @@ public class KoboLibrarySyncService {
private final KoboServerProxy koboServerProxy;
private final ObjectMapper objectMapper;
private final KoboSettingsService koboSettingsService;
private final AppSettingService appSettingService;
private Collection<Entitlement> getEntitlementsFromKoboStoreResponse(ResponseEntity<JsonNode> koboStoreResponse) {
return Optional.ofNullable(koboStoreResponse.getBody())
@@ -64,8 +66,13 @@ public class KoboLibrarySyncService {
.orElse(Collections.emptyList());
}
private boolean isForwardingToKoboStore() {
return appSettingService.getAppSettings().getKoboSettings().isForwardToKoboStore();
}
@Transactional
public ResponseEntity<?> syncLibrary(BookLoreUser user, String token) {
public ResponseEntity<List<Entitlement>> syncLibrary(BookLoreUser user, String token) {
HttpServletRequest request = RequestUtils.getCurrentRequest();
BookloreSyncToken syncToken = Optional.ofNullable(tokenGenerator.fromRequestHeaders(request)).orElse(new BookloreSyncToken());
@@ -134,7 +141,7 @@ public class KoboLibrarySyncService {
}
}
if (!shouldContinueSync) {
if (!shouldContinueSync && isForwardingToKoboStore()) {
ResponseEntity<JsonNode> koboStoreResponse = null;
try {
koboStoreResponse = koboServerProxy.proxyCurrentRequest(null, true);
@@ -3,8 +3,8 @@ package org.booklore.service.kobo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.node.ObjectNode;
@AllArgsConstructor
@Component
@@ -12,8 +12,8 @@ public class KoboResourcesComponent {
private final ObjectMapper objectMapper;
public JsonNode getResources() throws JacksonException {
return objectMapper.readTree(
public ObjectNode getResources() throws JacksonException {
return (ObjectNode) objectMapper.readTree(
"""
{
"account_page": "https://www.kobo.com/account/settings",
@@ -44,31 +44,28 @@ public class KoboUrlBuilder {
return ("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443);
}
public String downloadUrl(String token, Long bookId) {
return baseBuilder()
.pathSegment("api", "kobo", token, "v1", "books", "{bookId}", "download")
.buildAndExpand(bookId)
public String withBaseUrl(String token, String... pathSegments) {
UriComponentsBuilder builder = baseBuilder()
.pathSegment("api", "kobo", token);
for (String p : pathSegments) {
builder.pathSegment(p);
}
return builder
.build()
.toUriString();
}
public String downloadUrl(String token, Long bookId) {
return withBaseUrl(token, "v1", "books", bookId.toString(), "download");
}
public String imageUrlTemplate(String token) {
return baseBuilder()
.pathSegment("api", "kobo", token, "v1", "books", "{ImageId}", "thumbnail", "{Width}", "{Height}", "false", "image.jpg")
.build()
.toUriString();
return withBaseUrl( token, "v1", "books", "{ImageId}", "thumbnail", "{Width}", "{Height}", "false", "image.jpg");
}
public String imageUrlQualityTemplate(String token) {
return baseBuilder()
.pathSegment("api", "kobo", token, "v1", "books", "{ImageId}", "thumbnail", "{Width}", "{Height}", "{Quality}", "{IsGreyscale}", "image.jpg")
.build()
.toUriString();
}
public String librarySyncUrl(String token) {
return baseBuilder()
.pathSegment("api", "kobo", token, "v1", "library", "sync")
.build()
.toUriString();
return withBaseUrl( token, "v1", "books", "{ImageId}", "thumbnail", "{Width}", "{Height}", "{Quality}", "{IsGreyscale}", "image.jpg");
}
}