feat(api): use redirect for kobo sync book images (#198)

* refactor(api): simplify routes for kobo thumbnails

the versioned thumbnails are not seemingly called by kobo
and are not in other implementations of kobo sync

* feat(api): use redirect for kobo book images

* chore(api): add documentation for thumbnail redirect
This commit is contained in:
James Ward
2026-04-22 17:26:54 -04:00
committed by Zach Yale
parent 66de45c4be
commit c4107a9ff8
3 changed files with 40 additions and 88 deletions
@@ -3,6 +3,7 @@ package org.booklore.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@@ -18,13 +19,17 @@ import org.booklore.service.book.BookDownloadService;
import org.booklore.service.book.BookService;
import org.booklore.service.kobo.*;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
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;
@@ -67,60 +72,35 @@ public class KoboController {
return koboLibrarySyncService.syncLibrary(user, token);
}
@Operation(summary = "Get book thumbnail (versioned)", description = "Retrieve the thumbnail image for a local book with cache-busting version.")
@ApiResponse(responseCode = "200", description = "Thumbnail returned successfully")
@GetMapping("/v1/books/{imageId}/{version}/thumbnail/{width}/{height}/false/image.jpg")
public ResponseEntity<Resource> getVersionedThumbnail(
@Parameter(description = "Book ID") @PathVariable String imageId,
@Parameter(description = "Cover version (timestamp)") @PathVariable String version,
@Parameter(description = "Width of the thumbnail") @PathVariable int width,
@Parameter(description = "Height of the thumbnail") @PathVariable int height) {
return koboThumbnailService.getThumbnail(imageId);
}
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a local book.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Thumbnail returned successfully"),
@ApiResponse(responseCode = "307", description = "Thumbnail is at another location"),
})
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a Kobo store book.")
@ApiResponse(responseCode = "200", description = "Thumbnail returned successfully")
@GetMapping("/v1/books/{imageId}/thumbnail/{width}/{height}/false/image.jpg")
@GetMapping(
value = {
"v1/books/{imageId}/{version}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg",
"v1/books/{imageId}/{version}/thumbnail/{width}/{height}/{isGreyscale}/image.jpg",
"v1/books/{imageId}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg",
"v1/books/{imageId}/thumbnail/{width}/{height}/{isGreyscale}/image.jpg",
},
produces = MediaType.IMAGE_JPEG_VALUE
)
public ResponseEntity<Resource> getThumbnail(
@Parameter(description = "Image ID") @PathVariable String imageId,
@Parameter(description = "Width of the thumbnail") @PathVariable int width,
@Parameter(description = "Height of the thumbnail") @PathVariable int height) {
if (imageId.startsWith("BL-")) {
return koboThumbnailService.getThumbnail(imageId);
} else {
String cdnUrl = String.format("https://cdn.kobo.com/book-images/%s/%d/%d/false/image.jpg", imageId, width, height);
return koboServerProxy.proxyExternalUrl(cdnUrl);
}
}
@Operation(summary = "Get greyscale book thumbnail (versioned)", description = "Retrieve a greyscale thumbnail for a local book with cache-busting version.")
@ApiResponse(responseCode = "200", description = "Greyscale thumbnail returned successfully")
@GetMapping("/v1/books/{imageId}/{version}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg")
public ResponseEntity<Resource> getVersionedGreyThumbnail(
@Parameter(description = "Book ID") @PathVariable String imageId,
@Parameter(description = "Cover version (timestamp)") @PathVariable String version,
@Parameter(description = "Width of the thumbnail") @PathVariable int width,
@Parameter(description = "Height of the thumbnail") @PathVariable int height,
@Parameter(description = "Quality of the thumbnail") @PathVariable int quality,
@Parameter(description = "Is greyscale") @PathVariable boolean isGreyscale) {
return koboThumbnailService.getThumbnail(imageId);
}
@Operation(summary = "Get greyscale book thumbnail", description = "Retrieve a greyscale thumbnail image for a Kobo store book.")
@ApiResponse(responseCode = "200", description = "Greyscale thumbnail returned successfully")
@GetMapping("/v1/books/{imageId}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg")
public ResponseEntity<Resource> getGreyThumbnail(
@Parameter(description = "Image ID") @PathVariable String imageId,
@Parameter(description = "Width of the thumbnail") @PathVariable int width,
@Parameter(description = "Height of the thumbnail") @PathVariable int height,
@Parameter(description = "Quality of the thumbnail") @PathVariable int quality,
@Parameter(description = "Is greyscale") @PathVariable boolean isGreyscale) {
@Parameter(description = "Is greyscale") @PathVariable boolean isGreyscale
) {
if (imageId.startsWith("BL-")) {
return koboThumbnailService.getThumbnail(imageId);
} else {
String cdnUrl = String.format("https://cdn.kobo.com/book-images/%s/%d/%d/%d/%b/image.jpg", imageId, width, height, quality, isGreyscale);
return koboServerProxy.proxyExternalUrl(cdnUrl);
}
return ResponseEntity
.status(HttpStatus.TEMPORARY_REDIRECT)
.location(koboServerProxy.getKoboCDNCoverUri(imageId, width, height, isGreyscale))
.build();
}
@Operation(summary = "Authenticate Kobo device", description = "Authenticate a Kobo device.")
@@ -15,6 +15,7 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.util.UriComponentsBuilder;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
@@ -33,6 +34,7 @@ import java.util.regex.Pattern;
public class KoboServerProxy {
private static final Pattern KOBO_API_PREFIX_PATTERN = Pattern.compile("^/api/kobo/[^/]+");
private final String KOBO_BOOK_IMAGE_CDN_URL = "https://cdn.kobo.com/book-images/{ImageId}/{Width}/{Height}/{IsGreyscale}/image.jpg";
private final HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofMinutes(1)).build();
private final ObjectMapper objectMapper;
private final BookloreSyncTokenGenerator bookloreSyncTokenGenerator;
@@ -68,23 +70,11 @@ public class KoboServerProxy {
return executeProxyRequest(request, body, path, includeSyncToken, syncToken);
}
public ResponseEntity<Resource> proxyExternalUrl(String url) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
HttpResponse<byte[]> response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<>(new ByteArrayResource(response.body()), headers, HttpStatus.valueOf(response.statusCode()));
} catch (Exception e) {
log.error("Failed to proxy external Kobo CDN URL", e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to fetch image", e);
}
public URI getKoboCDNCoverUri(String imageId, int width, int height, boolean isGreyscale) {
return UriComponentsBuilder.fromUriString(KOBO_BOOK_IMAGE_CDN_URL)
.encode()
.buildAndExpand(imageId, width, height, isGreyscale)
.toUri();
}
private ResponseEntity<JsonNode> executeProxyRequest(HttpServletRequest request, Object body, String path, boolean includeSyncToken, BookloreSyncToken syncToken) {
@@ -13,17 +13,16 @@ import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.server.ResponseStatusException;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
@@ -31,7 +30,6 @@ import java.util.Collections;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@@ -246,32 +244,16 @@ class KoboServerProxyTest {
}
@Test
void proxyExternalUrl_shouldFetchAndReturnImage() throws Exception {
String testUrl = "https://cdn.kobo.com/image123.jpg";
byte[] imageData = {1, 2, 3, 4, 5};
when(httpResponseBytes.statusCode()).thenReturn(200);
when(httpResponseBytes.body()).thenReturn(imageData);
when(httpClient.<byte[]>send(any(HttpRequest.class), any()))
.thenReturn(httpResponseBytes);
void getKoboCDNCoverUri_shouldGenerateUri() {
URI actual = koboServerProxy.getKoboCDNCoverUri("example", 1, 2, false);
ResponseEntity<Resource> response = koboServerProxy.proxyExternalUrl(testUrl);
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().contentLength()).isEqualTo(5);
assertThat(actual.toString()).isEqualTo("https://cdn.kobo.com/book-images/example/1/2/false/image.jpg");
}
@Test
void proxyExternalUrl_withException_shouldThrowResponseStatusException() throws Exception {
String testUrl = "https://cdn.kobo.com/image123.jpg";
when(httpClient.<byte[]>send(any(HttpRequest.class), any()))
.thenThrow(new java.io.IOException("Network error"));
void getKoboCDNCoverUri_shouldEscapeImageComponent() {
URI actual = koboServerProxy.getKoboCDNCoverUri("foo/bar", 1, 2, false);
assertThatThrownBy(() -> koboServerProxy.proxyExternalUrl(testUrl))
.isInstanceOf(ResponseStatusException.class)
.hasMessageContaining("Failed to fetch image");
assertThat(actual.toString()).isEqualTo("https://cdn.kobo.com/book-images/foo%2Fbar/1/2/false/image.jpg");
}
}