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:
@@ -3,6 +3,7 @@ package org.booklore.controller;
|
|||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
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 io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
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.book.BookService;
|
||||||
import org.booklore.service.kobo.*;
|
import org.booklore.service.kobo.*;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import tools.jackson.core.JacksonException;
|
import tools.jackson.core.JacksonException;
|
||||||
import tools.jackson.databind.JsonNode;
|
import tools.jackson.databind.JsonNode;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@@ -67,60 +72,35 @@ public class KoboController {
|
|||||||
return koboLibrarySyncService.syncLibrary(user, token);
|
return koboLibrarySyncService.syncLibrary(user, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "Get book thumbnail (versioned)", description = "Retrieve the thumbnail image for a local book with cache-busting version.")
|
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a local book.")
|
||||||
@ApiResponse(responseCode = "200", description = "Thumbnail returned successfully")
|
@ApiResponses({
|
||||||
@GetMapping("/v1/books/{imageId}/{version}/thumbnail/{width}/{height}/false/image.jpg")
|
@ApiResponse(responseCode = "200", description = "Thumbnail returned successfully"),
|
||||||
public ResponseEntity<Resource> getVersionedThumbnail(
|
@ApiResponse(responseCode = "307", description = "Thumbnail is at another location"),
|
||||||
@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 Kobo store book.")
|
@GetMapping(
|
||||||
@ApiResponse(responseCode = "200", description = "Thumbnail returned successfully")
|
value = {
|
||||||
@GetMapping("/v1/books/{imageId}/thumbnail/{width}/{height}/false/image.jpg")
|
"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(
|
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 = "Book ID") @PathVariable String imageId,
|
||||||
@Parameter(description = "Cover version (timestamp)") @PathVariable String version,
|
|
||||||
@Parameter(description = "Width of the thumbnail") @PathVariable int width,
|
@Parameter(description = "Width of the thumbnail") @PathVariable int width,
|
||||||
@Parameter(description = "Height of the thumbnail") @PathVariable int height,
|
@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) {
|
) {
|
||||||
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) {
|
|
||||||
if (imageId.startsWith("BL-")) {
|
if (imageId.startsWith("BL-")) {
|
||||||
return koboThumbnailService.getThumbnail(imageId);
|
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.")
|
@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.http.ResponseEntity;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
import org.springframework.web.util.UriComponentsBuilder;
|
||||||
import tools.jackson.databind.JsonNode;
|
import tools.jackson.databind.JsonNode;
|
||||||
import tools.jackson.databind.ObjectMapper;
|
import tools.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
@@ -33,6 +34,7 @@ import java.util.regex.Pattern;
|
|||||||
public class KoboServerProxy {
|
public class KoboServerProxy {
|
||||||
|
|
||||||
private static final Pattern KOBO_API_PREFIX_PATTERN = Pattern.compile("^/api/kobo/[^/]+");
|
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 HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofMinutes(1)).build();
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
private final BookloreSyncTokenGenerator bookloreSyncTokenGenerator;
|
private final BookloreSyncTokenGenerator bookloreSyncTokenGenerator;
|
||||||
@@ -68,23 +70,11 @@ public class KoboServerProxy {
|
|||||||
return executeProxyRequest(request, body, path, includeSyncToken, syncToken);
|
return executeProxyRequest(request, body, path, includeSyncToken, syncToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ResponseEntity<Resource> proxyExternalUrl(String url) {
|
public URI getKoboCDNCoverUri(String imageId, int width, int height, boolean isGreyscale) {
|
||||||
try {
|
return UriComponentsBuilder.fromUriString(KOBO_BOOK_IMAGE_CDN_URL)
|
||||||
HttpRequest request = HttpRequest.newBuilder()
|
.encode()
|
||||||
.uri(URI.create(url))
|
.buildAndExpand(imageId, width, height, isGreyscale)
|
||||||
.GET()
|
.toUri();
|
||||||
.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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private ResponseEntity<JsonNode> executeProxyRequest(HttpServletRequest request, Object body, String path, boolean includeSyncToken, BookloreSyncToken syncToken) {
|
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.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.mock.web.MockHttpServletRequest;
|
import org.springframework.mock.web.MockHttpServletRequest;
|
||||||
import org.springframework.web.context.request.RequestContextHolder;
|
import org.springframework.web.context.request.RequestContextHolder;
|
||||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
import tools.jackson.databind.JsonNode;
|
import tools.jackson.databind.JsonNode;
|
||||||
import tools.jackson.databind.ObjectMapper;
|
import tools.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
|
import java.net.URI;
|
||||||
import java.net.http.HttpClient;
|
import java.net.http.HttpClient;
|
||||||
import java.net.http.HttpRequest;
|
import java.net.http.HttpRequest;
|
||||||
import java.net.http.HttpResponse;
|
import java.net.http.HttpResponse;
|
||||||
@@ -31,7 +30,6 @@ import java.util.Collections;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
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.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
@@ -246,32 +244,16 @@ class KoboServerProxyTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void proxyExternalUrl_shouldFetchAndReturnImage() throws Exception {
|
void getKoboCDNCoverUri_shouldGenerateUri() {
|
||||||
String testUrl = "https://cdn.kobo.com/image123.jpg";
|
URI actual = koboServerProxy.getKoboCDNCoverUri("example", 1, 2, false);
|
||||||
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);
|
|
||||||
|
|
||||||
ResponseEntity<Resource> response = koboServerProxy.proxyExternalUrl(testUrl);
|
assertThat(actual.toString()).isEqualTo("https://cdn.kobo.com/book-images/example/1/2/false/image.jpg");
|
||||||
|
|
||||||
assertThat(response).isNotNull();
|
|
||||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
|
||||||
assertThat(response.getBody()).isNotNull();
|
|
||||||
assertThat(response.getBody().contentLength()).isEqualTo(5);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void proxyExternalUrl_withException_shouldThrowResponseStatusException() throws Exception {
|
void getKoboCDNCoverUri_shouldEscapeImageComponent() {
|
||||||
String testUrl = "https://cdn.kobo.com/image123.jpg";
|
URI actual = koboServerProxy.getKoboCDNCoverUri("foo/bar", 1, 2, false);
|
||||||
|
|
||||||
when(httpClient.<byte[]>send(any(HttpRequest.class), any()))
|
|
||||||
.thenThrow(new java.io.IOException("Network error"));
|
|
||||||
|
|
||||||
assertThatThrownBy(() -> koboServerProxy.proxyExternalUrl(testUrl))
|
assertThat(actual.toString()).isEqualTo("https://cdn.kobo.com/book-images/foo%2Fbar/1/2/false/image.jpg");
|
||||||
.isInstanceOf(ResponseStatusException.class)
|
|
||||||
.hasMessageContaining("Failed to fetch image");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user