fix(metadata): migrate GoodReads parser from HTML scraping to GraphQL (#1734)
Co-authored-by: James Ward <james@notjam.es>
This commit is contained in:
co-authored by
James Ward
parent
284b7a41ef
commit
90fa4d7c42
@@ -14,17 +14,13 @@ import org.booklore.util.BookUtils;
|
|||||||
import org.booklore.util.LanguageNormalizer;
|
import org.booklore.util.LanguageNormalizer;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.jsoup.Connection;
|
|
||||||
import org.jsoup.Jsoup;
|
import org.jsoup.Jsoup;
|
||||||
import org.jsoup.nodes.Document;
|
|
||||||
import org.jsoup.nodes.Element;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import reactor.core.publisher.Flux;
|
import reactor.core.publisher.Flux;
|
||||||
import tools.jackson.core.type.TypeReference;
|
import tools.jackson.core.type.TypeReference;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.URISyntaxException;
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.net.http.HttpClient;
|
import java.net.http.HttpClient;
|
||||||
import java.net.http.HttpRequest;
|
import java.net.http.HttpRequest;
|
||||||
@@ -37,6 +33,7 @@ import java.time.ZoneId;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ThreadLocalRandom;
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -44,9 +41,51 @@ import java.util.function.Function;
|
|||||||
public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
||||||
private static final TypeReference<List<GoodreadsAutocompleteEntry>> AUTOCOMPLETE_RESPONSE_TYPE = new TypeReference<>() {};
|
private static final TypeReference<List<GoodreadsAutocompleteEntry>> AUTOCOMPLETE_RESPONSE_TYPE = new TypeReference<>() {};
|
||||||
|
|
||||||
|
// Located in Goodreads _app JS chunk, visible in DevTools → Network → GraphQL requests
|
||||||
|
private static final String GRAPHQL_ENDPOINT = "https://kxbwmqov6jgg3daaamb744ycu4.appsync-api.us-east-1.amazonaws.com/graphql";
|
||||||
|
private static final String API_KEY = "da2-xpgsdydkbregjhpr6ejzqdhuwy";
|
||||||
|
private static final String GRAPHQL_QUERY = """
|
||||||
|
query getBookPageData($legacyBookId: Int!) {
|
||||||
|
getBookByLegacyId(legacyId: $legacyBookId) {
|
||||||
|
title
|
||||||
|
description
|
||||||
|
imageUrl
|
||||||
|
primaryContributorEdge { node { name } }
|
||||||
|
secondaryContributorEdges { node { name } }
|
||||||
|
bookSeries { userPosition series { title } }
|
||||||
|
bookGenres { genre { name } }
|
||||||
|
details {
|
||||||
|
numPages
|
||||||
|
publicationTime
|
||||||
|
publisher
|
||||||
|
isbn
|
||||||
|
isbn13
|
||||||
|
language { name }
|
||||||
|
}
|
||||||
|
work {
|
||||||
|
stats { averageRating ratingsCount }
|
||||||
|
reviews {
|
||||||
|
edges {
|
||||||
|
node {
|
||||||
|
text
|
||||||
|
rating
|
||||||
|
spoilerStatus
|
||||||
|
updatedAt
|
||||||
|
creator {
|
||||||
|
name
|
||||||
|
followersCount
|
||||||
|
textReviewsCount
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""";
|
||||||
private static final String BASE_AUTOCOMPLETE_URL = "https://www.goodreads.com/book/auto_complete?format=json&q=";
|
private static final String BASE_AUTOCOMPLETE_URL = "https://www.goodreads.com/book/auto_complete?format=json&q=";
|
||||||
private static final String BASE_BOOK_URL = "https://www.goodreads.com/book/show/";
|
|
||||||
private static final String BASE_ISBN_URL = "https://www.goodreads.com/book/isbn/";
|
private static final String BASE_ISBN_URL = "https://www.goodreads.com/book/isbn/";
|
||||||
|
private static final Pattern PATTERN_PATH_GOODREADS_ID = Pattern.compile("^/book/show/([0-9]+)[^/]+$");
|
||||||
private static final int COUNT_DETAILED_METADATA_TO_GET = 3;
|
private static final int COUNT_DETAILED_METADATA_TO_GET = 3;
|
||||||
|
|
||||||
private final HttpClient httpClient;
|
private final HttpClient httpClient;
|
||||||
@@ -64,8 +103,7 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
if (existingGoodreadsId != null) {
|
if (existingGoodreadsId != null) {
|
||||||
log.info("GoodReads: Using existing Goodreads ID: {}", existingGoodreadsId);
|
log.info("GoodReads: Using existing Goodreads ID: {}", existingGoodreadsId);
|
||||||
try {
|
try {
|
||||||
Document document = fetchDoc(BASE_BOOK_URL + existingGoodreadsId);
|
BookMetadata metadata = fetchAndParseBook(existingGoodreadsId);
|
||||||
BookMetadata metadata = parseBookDetails(document, existingGoodreadsId);
|
|
||||||
if (metadata != null) {
|
if (metadata != null) {
|
||||||
return metadata;
|
return metadata;
|
||||||
}
|
}
|
||||||
@@ -96,26 +134,6 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String extractGoodreadsIdFromOgUrl(Document doc) {
|
|
||||||
String ogUrl = Optional.ofNullable(doc.selectFirst("meta[property=og:url]"))
|
|
||||||
.map(e -> e.attr("content"))
|
|
||||||
.orElse(null);
|
|
||||||
if (ogUrl == null || ogUrl.isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
String path = new URI(ogUrl).getPath();
|
|
||||||
if (path == null || path.isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String id = path.substring(path.lastIndexOf('/') + 1);
|
|
||||||
return id.isBlank() ? null : id;
|
|
||||||
} catch (URISyntaxException e) {
|
|
||||||
log.warn("GoodReads: Could not parse og:url '{}': {}", ogUrl, e.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
|
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
|
||||||
return fetchMetadataStream(book, fetchMetadataRequest).collectList().block();
|
return fetchMetadataStream(book, fetchMetadataRequest).collectList().block();
|
||||||
@@ -128,14 +146,10 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
String isbn = ParserUtils.cleanIsbn(fetchMetadataRequest.getIsbn());
|
String isbn = ParserUtils.cleanIsbn(fetchMetadataRequest.getIsbn());
|
||||||
if (isbn != null && !isbn.isBlank()) {
|
if (isbn != null && !isbn.isBlank()) {
|
||||||
try {
|
try {
|
||||||
log.info("Goodreads Query URL (ISBN): {}{}", BASE_ISBN_URL, isbn);
|
String legacyId = resolveIsbn(isbn);
|
||||||
Document doc = fetchDoc(BASE_ISBN_URL + isbn);
|
BookMetadata metadata = fetchAndParseBook(legacyId);
|
||||||
String goodreadsId = extractGoodreadsIdFromOgUrl(doc);
|
if (metadata != null) {
|
||||||
if (goodreadsId != null) {
|
sink.next(metadata);
|
||||||
BookMetadata metadata = parseBookDetails(doc, goodreadsId);
|
|
||||||
if (metadata != null) {
|
|
||||||
sink.next(metadata);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("GoodReads: ISBN lookup failed: {}, falling back to title search", e.getMessage());
|
log.warn("GoodReads: ISBN lookup failed: {}, falling back to title search", e.getMessage());
|
||||||
@@ -147,13 +161,14 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
for (String goodreadsId : searchResultIds) {
|
for (String goodreadsId : searchResultIds) {
|
||||||
if (sink.isCancelled()) return;
|
if (sink.isCancelled()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
log.info("GoodReads: Fetching metadata for: Goodreads ID {}", goodreadsId);
|
log.info("GoodReads: Fetching metadata for: Goodreads ID {}", goodreadsId);
|
||||||
try {
|
try {
|
||||||
Document document = fetchDoc(BASE_BOOK_URL + goodreadsId);
|
BookMetadata metadata = fetchAndParseBook(goodreadsId);
|
||||||
BookMetadata detailedMetadata = parseBookDetails(document, goodreadsId);
|
if (metadata != null) {
|
||||||
if (detailedMetadata != null) {
|
sink.next(metadata);
|
||||||
sink.next(detailedMetadata);
|
|
||||||
}
|
}
|
||||||
Thread.sleep(ThreadLocalRandom.current().nextLong(500, 1501));
|
Thread.sleep(ThreadLocalRandom.current().nextLong(500, 1501));
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
@@ -170,35 +185,100 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private BookMetadata parseBookDetails(Document document, String goodreadsId) {
|
private BookMetadata fetchAndParseBook(String goodreadsId) {
|
||||||
|
JsonNode bookNode = fetchBookFromGraphql(goodreadsId);
|
||||||
|
if (bookNode == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return parseBookDetails(bookNode, goodreadsId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveIsbn(String isbn) throws IOException, InterruptedException {
|
||||||
|
HttpRequest request = HttpRequest.newBuilder()
|
||||||
|
.uri(URI.create(BASE_ISBN_URL + isbn))
|
||||||
|
.GET()
|
||||||
|
.build();
|
||||||
|
HttpResponse<Void> response = httpClient.send(request, HttpResponse.BodyHandlers.discarding());
|
||||||
|
String path = response.uri().getPath();
|
||||||
|
var goodreadsIdMatcher = PATTERN_PATH_GOODREADS_ID.matcher(path);
|
||||||
|
if (!goodreadsIdMatcher.matches()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String id = goodreadsIdMatcher.group(1);
|
||||||
|
log.info("GoodReads: ISBN {} resolved to legacyId {}", isbn, id);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode fetchBookFromGraphql(String goodreadsId) {
|
||||||
|
try {
|
||||||
|
int legacyBookId = Integer.parseInt(goodreadsId);
|
||||||
|
|
||||||
|
ObjectNode payload = objectMapper.createObjectNode()
|
||||||
|
.put("operationName", "getBookPageData")
|
||||||
|
.set("variables", objectMapper.createObjectNode().put("legacyBookId", legacyBookId))
|
||||||
|
.put("query", GRAPHQL_QUERY);
|
||||||
|
String requestBody = payload.toString();
|
||||||
|
|
||||||
|
HttpRequest request = HttpRequest.newBuilder()
|
||||||
|
.uri(URI.create(GRAPHQL_ENDPOINT))
|
||||||
|
.header("x-api-key", API_KEY)
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
|
if (response.statusCode() < 200 || response.statusCode() > 399) {
|
||||||
|
String errorBody = response.body();
|
||||||
|
log.error("GraphQL request failed with status: {}, body: {}", response.statusCode(),
|
||||||
|
errorBody != null ? errorBody.substring(0, Math.min(errorBody.length(), 500)) : "null");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode root = objectMapper.readTree(response.body());
|
||||||
|
JsonNode errors = root.get("errors");
|
||||||
|
if (errors != null && errors.isArray() && errors.size() > 0) {
|
||||||
|
log.error("GraphQL returned errors: {}", errors);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode bookNode = root.path("data").path("getBookByLegacyId");
|
||||||
|
|
||||||
|
if (bookNode.isMissingNode() || bookNode.isNull()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return bookNode;
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
log.error("Invalid Goodreads ID format: {}", goodreadsId);
|
||||||
|
return null;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("GraphQL request failed for ID: {}", goodreadsId, e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BookMetadata parseBookDetails(JsonNode bookNode, String goodreadsId) {
|
||||||
|
if (bookNode == null || bookNode.isMissingNode() || bookNode.isNull()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
BookMetadata.BookMetadataBuilder builder = BookMetadata.builder()
|
BookMetadata.BookMetadataBuilder builder = BookMetadata.builder()
|
||||||
.goodreadsId(goodreadsId)
|
.goodreadsId(goodreadsId)
|
||||||
.provider(MetadataProvider.GoodReads);
|
.provider(MetadataProvider.GoodReads);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
JsonNode root = getJson(document);
|
extractContributorDetails(bookNode, builder);
|
||||||
if (root == null) return null;
|
extractSeriesDetails(bookNode, builder);
|
||||||
|
extractBookDetails(bookNode, builder);
|
||||||
|
extractWorkDetails(bookNode, builder);
|
||||||
|
|
||||||
JsonNode apolloStateJson = root.path("props")
|
var reviewSettings = appSettingService.getAppSettings().getMetadataPublicReviewsSettings();
|
||||||
.path("pageProps")
|
if (reviewSettings != null && reviewSettings.getProviders() != null) {
|
||||||
.path("apolloState");
|
reviewSettings.getProviders().stream()
|
||||||
|
.filter(cfg -> cfg.getProvider() == MetadataProvider.GoodReads && cfg.isEnabled())
|
||||||
if (apolloStateJson.isMissingNode()) return null;
|
.findFirst()
|
||||||
|
.ifPresent(cfg -> extractReviews(bookNode, builder, cfg.getMaxReviews()));
|
||||||
LinkedHashSet<String> keySet = getJsonKeys(apolloStateJson);
|
}
|
||||||
|
|
||||||
extractContributorDetails(apolloStateJson, keySet, builder);
|
|
||||||
extractSeriesDetails(apolloStateJson, keySet, builder);
|
|
||||||
extractBookDetails(apolloStateJson, keySet, builder);
|
|
||||||
extractWorkDetails(apolloStateJson, keySet, builder);
|
|
||||||
|
|
||||||
appSettingService.getAppSettings()
|
|
||||||
.getMetadataPublicReviewsSettings()
|
|
||||||
.getProviders()
|
|
||||||
.stream()
|
|
||||||
.filter(cfg -> cfg.getProvider() == MetadataProvider.GoodReads && cfg.isEnabled())
|
|
||||||
.findFirst()
|
|
||||||
.ifPresent(cfg -> extractReviews(apolloStateJson, keySet, builder, cfg.getMaxReviews()));
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Error parsing book details for providerBookId: {}", goodreadsId, e);
|
log.error("Error parsing book details for providerBookId: {}", goodreadsId, e);
|
||||||
@@ -208,57 +288,93 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
return builder.build();
|
return builder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void extractContributorDetails(JsonNode apolloStateJson, LinkedHashSet<String> keySet, BookMetadata.BookMetadataBuilder builder) {
|
private void extractContributorDetails(JsonNode bookNode, BookMetadata.BookMetadataBuilder builder) {
|
||||||
String contributorKey = findKeyByPrefix(keySet, "Contributor:kca");
|
List<String> authors = new ArrayList<>();
|
||||||
String contributorName = getJsonStringField(apolloStateJson, contributorKey, "name");
|
|
||||||
if (contributorName != null) {
|
JsonNode primaryEdge = bookNode.get("primaryContributorEdge");
|
||||||
builder.authors(List.of(contributorName));
|
if (primaryEdge != null && primaryEdge.isObject()) {
|
||||||
|
JsonNode node = primaryEdge.get("node");
|
||||||
|
if (node != null) {
|
||||||
|
String name = node.path("name").asText(null);
|
||||||
|
if (name != null) {
|
||||||
|
authors.add(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode secondaryEdges = bookNode.get("secondaryContributorEdges");
|
||||||
|
if (secondaryEdges != null && secondaryEdges.isArray()) {
|
||||||
|
for (int i = 0; i < secondaryEdges.size(); i++) {
|
||||||
|
JsonNode node = secondaryEdges.get(i).path("node");
|
||||||
|
String name = node.path("name").asText(null);
|
||||||
|
if (name != null) {
|
||||||
|
authors.add(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!authors.isEmpty()) {
|
||||||
|
builder.authors(authors);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void extractReviews(JsonNode apolloStateJson, LinkedHashSet<String> keySet, BookMetadata.BookMetadataBuilder builder, int maxReviews) {
|
private void extractReviews(JsonNode bookNode, BookMetadata.BookMetadataBuilder builder, int maxReviews) {
|
||||||
List<String> allReviewKeys = findKeysByPrefixAll(keySet, "Review:kca");
|
|
||||||
List<BookReview> reviews = new ArrayList<>();
|
List<BookReview> reviews = new ArrayList<>();
|
||||||
|
|
||||||
|
JsonNode work = bookNode.get("work");
|
||||||
|
if (work == null || !work.isObject()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode reviewsJson = work.get("reviews");
|
||||||
|
if (reviewsJson == null || !reviewsJson.isObject()) {
|
||||||
|
reviewsJson = work.get("reviewStats");
|
||||||
|
if (reviewsJson == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode edges = reviewsJson.get("edges");
|
||||||
|
if (edges == null || !edges.isArray()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
int count = 0;
|
int count = 0;
|
||||||
int index = 0;
|
for (int i = 0; i < edges.size() && count < maxReviews; i++) {
|
||||||
|
JsonNode reviewNode = edges.get(i).path("node");
|
||||||
|
if (reviewNode == null || reviewNode.isMissingNode()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
while (count < maxReviews && index < allReviewKeys.size()) {
|
|
||||||
String reviewKey = allReviewKeys.get(index);
|
|
||||||
index++;
|
|
||||||
try {
|
try {
|
||||||
JsonNode reviewJson = apolloStateJson.get(reviewKey);
|
String rawBody = reviewNode.path("text").asText(null);
|
||||||
if (reviewJson == null) continue;
|
|
||||||
|
|
||||||
JsonNode creatorNode = reviewJson.path("creator");
|
|
||||||
String creatorRef = creatorNode.path("__ref").asText(null);
|
|
||||||
JsonNode userJson = apolloStateJson.get(creatorRef);
|
|
||||||
|
|
||||||
String reviewerName = null;
|
|
||||||
Integer followersCount = null;
|
|
||||||
Integer textReviewsCount = null;
|
|
||||||
if (userJson != null) {
|
|
||||||
reviewerName = userJson.path("name").asText(null);
|
|
||||||
JsonNode followersNode = userJson.path("followersCount");
|
|
||||||
followersCount = followersNode.canConvertToInt() ? followersNode.asInt() : null;
|
|
||||||
JsonNode textReviewsNode = userJson.path("textReviewsCount");
|
|
||||||
textReviewsCount = textReviewsNode.canConvertToInt() ? textReviewsNode.asInt() : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
String rawBody = reviewJson.path("text").asText(null);
|
|
||||||
String plainBody = rawBody != null ? Jsoup.parse(rawBody).text() : null;
|
String plainBody = rawBody != null ? Jsoup.parse(rawBody).text() : null;
|
||||||
|
|
||||||
if (plainBody == null || plainBody.trim().isEmpty()) {
|
if (plainBody == null || plainBody.trim().isEmpty()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonNode updatedAtNode = reviewJson.path("updatedAt");
|
JsonNode creator = reviewNode.get("creator");
|
||||||
|
String reviewerName = creator != null ? creator.path("name").asText(null) : null;
|
||||||
|
Integer followersCount = null;
|
||||||
|
Integer textReviewsCount = null;
|
||||||
|
if (creator != null) {
|
||||||
|
JsonNode fn = creator.path("followersCount");
|
||||||
|
if (fn.canConvertToInt()) {
|
||||||
|
followersCount = fn.asInt();
|
||||||
|
}
|
||||||
|
JsonNode trn = creator.path("textReviewsCount");
|
||||||
|
if (trn.canConvertToInt()) {
|
||||||
|
textReviewsCount = trn.asInt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode updatedAtNode = reviewNode.path("updatedAt");
|
||||||
BookReview review = BookReview.builder()
|
BookReview review = BookReview.builder()
|
||||||
.metadataProvider(MetadataProvider.GoodReads)
|
.metadataProvider(MetadataProvider.GoodReads)
|
||||||
.date(updatedAtNode.isIntegralNumber() ? Instant.ofEpochMilli(updatedAtNode.asLong()) : null)
|
.date(updatedAtNode.isIntegralNumber() ? Instant.ofEpochMilli(updatedAtNode.asLong()) : null)
|
||||||
.body(plainBody.trim())
|
.body(plainBody.trim())
|
||||||
.rating(Float.valueOf(reviewJson.path("rating").asText("0")))
|
.rating(Float.valueOf(reviewNode.path("rating").asText("0")))
|
||||||
.spoiler(reviewJson.path("spoilerStatus").asBoolean(false))
|
.spoiler(reviewNode.path("spoilerStatus").asBoolean(false))
|
||||||
.reviewerName(reviewerName != null ? reviewerName.trim() : null)
|
.reviewerName(reviewerName != null ? reviewerName.trim() : null)
|
||||||
.followersCount(followersCount)
|
.followersCount(followersCount)
|
||||||
.textReviewsCount(textReviewsCount)
|
.textReviewsCount(textReviewsCount)
|
||||||
@@ -266,49 +382,38 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
reviews.add(review);
|
reviews.add(review);
|
||||||
count++;
|
count++;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Error fetching review: {}, Error: {}", reviewKey, e.getMessage());
|
log.error("Error parsing review at index {}: {}", i, e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
builder.bookReviews(reviews);
|
builder.bookReviews(reviews);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void extractSeriesDetails(JsonNode bookNode, BookMetadata.BookMetadataBuilder builder) {
|
||||||
private List<String> findKeysByPrefixAll(LinkedHashSet<String> keySet, String prefix) {
|
JsonNode bookSeries = bookNode.get("bookSeries");
|
||||||
List<String> matchingKeys = new ArrayList<>();
|
if (bookSeries != null && bookSeries.isArray() && bookSeries.size() > 0) {
|
||||||
for (String key : keySet) {
|
JsonNode first = bookSeries.get(0);
|
||||||
if (key.startsWith(prefix)) {
|
JsonNode series = first.path("series");
|
||||||
matchingKeys.add(key);
|
String seriesName = series.path("title").asText(null);
|
||||||
|
if (seriesName != null) {
|
||||||
|
builder.seriesName(seriesName);
|
||||||
}
|
}
|
||||||
}
|
builder.seriesNumber(parseNumber(first.path("userPosition").asText(null), Float::parseFloat));
|
||||||
return matchingKeys;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void extractSeriesDetails(JsonNode apolloStateJson, LinkedHashSet<String> keySet, BookMetadata.BookMetadataBuilder builder) {
|
|
||||||
String seriesKey = findKeyByPrefix(keySet, "Series:kca");
|
|
||||||
String seriesName = getJsonStringField(apolloStateJson, seriesKey, "title");
|
|
||||||
if (seriesName != null) {
|
|
||||||
builder.seriesName(seriesName);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void extractBookDetails(JsonNode apolloStateJson, LinkedHashSet<String> keySet, BookMetadata.BookMetadataBuilder builder) {
|
private void extractBookDetails(JsonNode bookNode, BookMetadata.BookMetadataBuilder builder) {
|
||||||
JsonNode bookJson = getValidBookJson(apolloStateJson, keySet);
|
TitleInfo titleInfo = parseTitleInfo(bookNode.path("title").asText(null));
|
||||||
if (bookJson == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
TitleInfo titleInfo = parseTitleInfo(bookJson.path("title").asText(null));
|
|
||||||
builder.title(titleInfo.title())
|
builder.title(titleInfo.title())
|
||||||
.subtitle(titleInfo.subtitle())
|
.subtitle(titleInfo.subtitle())
|
||||||
.description(normalizeNull(bookJson.path("description").asText(null)))
|
.description(normalizeNull(bookNode.path("description").asText(null)))
|
||||||
.thumbnailUrl(normalizeNull(bookJson.path("imageUrl").asText(null)))
|
.thumbnailUrl(normalizeNull(bookNode.path("imageUrl").asText(null)))
|
||||||
.categories(extractGenres(bookJson));
|
.categories(extractGenres(bookNode));
|
||||||
|
|
||||||
JsonNode detailsJson = bookJson.get("details");
|
JsonNode detailsJson = bookNode.get("details");
|
||||||
if (detailsJson != null && detailsJson.isObject()) {
|
if (detailsJson != null && detailsJson.isObject()) {
|
||||||
builder.pageCount(parseNumber(detailsJson.path("numPages").asText(null), Integer::parseInt))
|
builder.pageCount(parseNumber(detailsJson.path("numPages").asText(null), Integer::parseInt))
|
||||||
.publishedDate(convertToLocalDate(detailsJson.path("publicationTime").asText(null)))
|
.publishedDate(convertToLocalDate(detailsJson.path("publicationTime")))
|
||||||
.publisher(normalizeNull(detailsJson.path("publisher").asText(null)))
|
.publisher(normalizeNull(detailsJson.path("publisher").asText(null)))
|
||||||
.isbn10(normalizeNull(detailsJson.path("isbn").asText(null)))
|
.isbn10(normalizeNull(detailsJson.path("isbn").asText(null)))
|
||||||
.isbn13(normalizeNull(detailsJson.path("isbn13").asText(null)));
|
.isbn13(normalizeNull(detailsJson.path("isbn13").asText(null)));
|
||||||
@@ -318,32 +423,38 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
builder.language(LanguageNormalizer.normalize(normalizeNull(languageJson.path("name").asText(null))));
|
builder.language(LanguageNormalizer.normalize(normalizeNull(languageJson.path("name").asText(null))));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonNode bookSeriesJson = bookJson.get("bookSeries");
|
|
||||||
if (bookSeriesJson != null && bookSeriesJson.isArray() && bookSeriesJson.size() > 0) {
|
|
||||||
JsonNode firstElement = bookSeriesJson.get(0);
|
|
||||||
if (firstElement != null) {
|
|
||||||
builder.seriesNumber(parseNumber(firstElement.path("userPosition").asText(null), Float::parseFloat));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void extractWorkDetails(JsonNode apolloStateJson, LinkedHashSet<String> keySet, BookMetadata.BookMetadataBuilder builder) {
|
private void extractWorkDetails(JsonNode bookNode, BookMetadata.BookMetadataBuilder builder) {
|
||||||
String workKey = findKeyByPrefix(keySet, "Work:kca:");
|
JsonNode work = bookNode.get("work");
|
||||||
if (workKey == null) {
|
if (work == null || !work.isObject()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
JsonNode workJson = apolloStateJson.get(workKey);
|
|
||||||
if (workJson == null) {
|
JsonNode statsJson = work.get("stats");
|
||||||
return;
|
|
||||||
}
|
|
||||||
JsonNode statsJson = workJson.get("stats");
|
|
||||||
if (statsJson != null && statsJson.isObject()) {
|
if (statsJson != null && statsJson.isObject()) {
|
||||||
builder.goodreadsRating(parseNumber(statsJson.path("averageRating").asText(null), Double::parseDouble))
|
builder.goodreadsRating(parseNumber(statsJson.path("averageRating").asText(null), Double::parseDouble))
|
||||||
.goodreadsReviewCount(parseNumber(statsJson.path("ratingsCount").asText(null), Integer::parseInt));
|
.goodreadsReviewCount(parseNumber(statsJson.path("ratingsCount").asText(null), Integer::parseInt));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Set<String> extractGenres(JsonNode bookNode) {
|
||||||
|
try {
|
||||||
|
Set<String> genres = new HashSet<>();
|
||||||
|
JsonNode bookGenresArray = bookNode.get("bookGenres");
|
||||||
|
if (bookGenresArray != null && bookGenresArray.isArray()) {
|
||||||
|
for (int i = 0; i < bookGenresArray.size(); i++) {
|
||||||
|
JsonNode genreJson = bookGenresArray.get(i).path("genre");
|
||||||
|
genres.add(genreJson.path("name").asText());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return genres;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error extracting genres", e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private TitleInfo parseTitleInfo(String fullTitle) {
|
private TitleInfo parseTitleInfo(String fullTitle) {
|
||||||
if (fullTitle == null || "null".equals(fullTitle)) {
|
if (fullTitle == null || "null".equals(fullTitle)) {
|
||||||
return new TitleInfo(null, null);
|
return new TitleInfo(null, null);
|
||||||
@@ -370,103 +481,30 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
return "null".equals(s) || (s != null && s.isEmpty()) ? null : s;
|
return "null".equals(s) || (s != null && s.isEmpty()) ? null : s;
|
||||||
}
|
}
|
||||||
|
|
||||||
private LinkedHashSet<String> getJsonKeys(JsonNode apolloStateJson) {
|
private LocalDate convertToLocalDate(JsonNode publicationTimeNode) {
|
||||||
LinkedHashSet<String> keySet = new LinkedHashSet<>();
|
if (publicationTimeNode == null || publicationTimeNode.isMissingNode() || publicationTimeNode.isNull()) {
|
||||||
if (apolloStateJson instanceof ObjectNode objectNode) {
|
return null;
|
||||||
for (String fieldName : objectNode.propertyNames()) {
|
|
||||||
keySet.add(fieldName);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return keySet;
|
|
||||||
}
|
|
||||||
|
|
||||||
private JsonNode getValidBookJson(JsonNode apolloStateJson, LinkedHashSet<String> keySet) {
|
|
||||||
try {
|
try {
|
||||||
for (String key : keySet) {
|
long millis;
|
||||||
if (key.contains("Book:kca:")) {
|
if (publicationTimeNode.isNumber()) {
|
||||||
JsonNode bookJson = apolloStateJson.get(key);
|
millis = publicationTimeNode.asLong();
|
||||||
if (bookJson == null) continue;
|
} else {
|
||||||
String title = bookJson.path("title").asText(null);
|
String text = publicationTimeNode.asText(null);
|
||||||
if (title != null && !title.isEmpty()) {
|
if (text == null || text.isBlank() || "null".equals(text)) {
|
||||||
return bookJson;
|
return null;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
millis = Long.parseLong(text);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("Error finding valid book JSON: {}", e.getMessage());
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String findKeyByPrefix(LinkedHashSet<String> keySet, String prefix) {
|
|
||||||
return keySet.stream()
|
|
||||||
.filter(key -> key.contains(prefix))
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getJsonStringField(JsonNode apolloStateJson, String key, String fieldName) {
|
|
||||||
if (key == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
JsonNode node = apolloStateJson.get(key);
|
|
||||||
if (node == null) return null;
|
|
||||||
return node.path(fieldName).asText(null);
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Error fetching {} from {}: {}", fieldName, key, e.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Set<String> extractGenres(JsonNode bookJson) {
|
|
||||||
try {
|
|
||||||
Set<String> genres = new HashSet<>();
|
|
||||||
JsonNode bookGenresJsonArray = bookJson.get("bookGenres");
|
|
||||||
if (bookGenresJsonArray != null && bookGenresJsonArray.isArray()) {
|
|
||||||
for (int i = 0; i < bookGenresJsonArray.size(); i++) {
|
|
||||||
JsonNode genreJson = bookGenresJsonArray.get(i).path("genre");
|
|
||||||
genres.add(genreJson.path("name").asText());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return genres;
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("Error extracting genres from book: {}, Error: {}", bookJson, e.getMessage());
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private LocalDate convertToLocalDate(String timestamp) {
|
|
||||||
if (timestamp == null || timestamp.isBlank() || "null".equals(timestamp)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
long millis = Long.parseLong(timestamp);
|
|
||||||
return Instant.ofEpochMilli(millis)
|
return Instant.ofEpochMilli(millis)
|
||||||
.atZone(ZoneId.systemDefault())
|
.atZone(ZoneId.systemDefault())
|
||||||
.toLocalDate();
|
.toLocalDate();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Invalid publication time: {}, Error: {}", timestamp, e.getMessage());
|
log.error("Invalid publication time: {}, Error: {}", publicationTimeNode, e.getMessage());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public JsonNode getJson(Element document) {
|
|
||||||
try {
|
|
||||||
Element scriptElement = document.getElementById("__NEXT_DATA__");
|
|
||||||
|
|
||||||
if (scriptElement != null) {
|
|
||||||
String jsonString = scriptElement.html();
|
|
||||||
return objectMapper.readTree(jsonString);
|
|
||||||
} else {
|
|
||||||
log.warn("No JSON script element found!");
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("No JSON script element found!", e);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String generateSearchUrl(String searchTerm) {
|
public String generateSearchUrl(String searchTerm) {
|
||||||
String encodedSearchTerm = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8);
|
String encodedSearchTerm = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8);
|
||||||
String url = BASE_AUTOCOMPLETE_URL + encodedSearchTerm;
|
String url = BASE_AUTOCOMPLETE_URL + encodedSearchTerm;
|
||||||
@@ -474,7 +512,6 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public List<String> fetchSearchResults(Book book, FetchMetadataRequest request) throws InterruptedException {
|
public List<String> fetchSearchResults(Book book, FetchMetadataRequest request) throws InterruptedException {
|
||||||
String searchTerm = getSearchTerm(book, request);
|
String searchTerm = getSearchTerm(book, request);
|
||||||
|
|
||||||
@@ -522,8 +559,7 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
public BookMetadata fetchDetailedMetadata(String goodreadsId) {
|
public BookMetadata fetchDetailedMetadata(String goodreadsId) {
|
||||||
log.info("GoodReads: Fetching detailed metadata for ID: {}", goodreadsId);
|
log.info("GoodReads: Fetching detailed metadata for ID: {}", goodreadsId);
|
||||||
try {
|
try {
|
||||||
Document document = fetchDoc(BASE_BOOK_URL + goodreadsId);
|
return fetchAndParseBook(goodreadsId);
|
||||||
return parseBookDetails(document, goodreadsId);
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Error fetching detailed metadata for GoodReads ID: {}", goodreadsId, e);
|
log.error("Error fetching detailed metadata for GoodReads ID: {}", goodreadsId, e);
|
||||||
return null;
|
return null;
|
||||||
@@ -552,38 +588,4 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Document fetchDoc(String url) {
|
|
||||||
try {
|
|
||||||
return Jsoup.connect(url)
|
|
||||||
.header("accept", "text/html, application/json")
|
|
||||||
.header("accept-language", "en-US,en;q=0.9")
|
|
||||||
.header("content-type", "application/json")
|
|
||||||
.header("device-memory", "8")
|
|
||||||
.header("downlink", "10")
|
|
||||||
.header("dpr", "2")
|
|
||||||
.header("ect", "4g")
|
|
||||||
.header("origin", "https://www.amazon.com")
|
|
||||||
.header("priority", "u=1, i")
|
|
||||||
.header("rtt", "50")
|
|
||||||
.header("sec-ch-device-memory", "8")
|
|
||||||
.header("sec-ch-dpr", "2")
|
|
||||||
.header("sec-ch-ua", "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"")
|
|
||||||
.header("sec-ch-ua-mobile", "?0")
|
|
||||||
.header("sec-ch-ua-platform", "\"macOS\"")
|
|
||||||
.header("sec-ch-viewport-width", "1170")
|
|
||||||
.header("sec-fetch-dest", "empty")
|
|
||||||
.header("sec-fetch-mode", "cors")
|
|
||||||
.header("sec-fetch-site", "same-origin")
|
|
||||||
.header("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
|
|
||||||
.header("viewport-width", "1170")
|
|
||||||
.header("x-amz-amabot-click-attributes", "disable")
|
|
||||||
.header("x-requested-with", "XMLHttpRequest")
|
|
||||||
.method(Connection.Method.GET)
|
|
||||||
.get();
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.error("Error parsing url: {}", url, e);
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-35
@@ -9,14 +9,10 @@ import org.booklore.model.dto.settings.MetadataProviderSettings;
|
|||||||
import org.booklore.model.dto.settings.MetadataPublicReviewsSettings;
|
import org.booklore.model.dto.settings.MetadataPublicReviewsSettings;
|
||||||
import org.booklore.model.enums.MetadataProvider;
|
import org.booklore.model.enums.MetadataProvider;
|
||||||
import org.booklore.service.appsettings.AppSettingService;
|
import org.booklore.service.appsettings.AppSettingService;
|
||||||
import org.jsoup.Connection;
|
|
||||||
import org.jsoup.Jsoup;
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.MockedStatic;
|
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
import tools.jackson.databind.ObjectMapper;
|
import tools.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
@@ -40,13 +36,11 @@ public class GoodReadsParserTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private HttpClient httpClient;
|
private HttpClient httpClient;
|
||||||
|
|
||||||
private MockedStatic<Jsoup> mockJsoup;
|
|
||||||
|
|
||||||
private GoodReadsParser parser;
|
private GoodReadsParser parser;
|
||||||
|
|
||||||
private String exampleSearchJsonFixture;
|
private String exampleSearchJsonFixture;
|
||||||
|
|
||||||
private String exampleBookHtmlFixture;
|
private String exampleGraphqlResponseFixture;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() throws IOException {
|
void setUp() throws IOException {
|
||||||
@@ -57,16 +51,7 @@ public class GoodReadsParserTest {
|
|||||||
);
|
);
|
||||||
|
|
||||||
exampleSearchJsonFixture = readFixture("example-search.json");
|
exampleSearchJsonFixture = readFixture("example-search.json");
|
||||||
exampleBookHtmlFixture = readFixture("example-book.html");
|
exampleGraphqlResponseFixture = readFixture("example-graphql-response.json");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
mockJsoup = mockStatic(Jsoup.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterEach
|
|
||||||
void tearDown() {
|
|
||||||
mockJsoup.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void mockSettings(boolean enabled) {
|
private void mockSettings(boolean enabled) {
|
||||||
@@ -114,30 +99,16 @@ public class GoodReadsParserTest {
|
|||||||
return httpResponse;
|
return httpResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
private void mockHttpClientResponse(String urlPrefix, int statusCode, String response) throws Exception {
|
private void mockHttpClientResponse(String urlPrefix, int statusCode, String response) throws Exception {
|
||||||
when(
|
when(
|
||||||
httpClient.<String>send(
|
httpClient.<String>send(
|
||||||
argThat(r -> r.uri().toString().startsWith(urlPrefix)),
|
argThat(r -> r != null && r.uri() != null && r.uri().toString().startsWith(urlPrefix)),
|
||||||
any()
|
any()
|
||||||
)
|
)
|
||||||
).thenAnswer((_) -> getMockResponse(statusCode, response));
|
).thenAnswer((_) -> getMockResponse(statusCode, response));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void mockJsoupResponse(String urlPrefix, String response) throws Exception {
|
|
||||||
Connection mockConnection = mock(Connection.class);
|
|
||||||
|
|
||||||
when(mockConnection.header(anyString(), anyString())).thenReturn(mockConnection);
|
|
||||||
when(mockConnection.method(any())).thenReturn(mockConnection);
|
|
||||||
|
|
||||||
// There may be a better way to get the parse to work here.
|
|
||||||
// However, this was the quickest and simplest way I could find.
|
|
||||||
mockJsoup.when(() -> Jsoup.parse(response)).thenCallRealMethod();
|
|
||||||
|
|
||||||
when(mockConnection.get()).thenAnswer(i -> Jsoup.parse(response));
|
|
||||||
|
|
||||||
mockJsoup.when(() -> Jsoup.connect(startsWith(urlPrefix))).thenReturn(mockConnection);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testFetchMetadata_EmptyQuery() {
|
void testFetchMetadata_EmptyQuery() {
|
||||||
// Given
|
// Given
|
||||||
@@ -172,9 +143,9 @@ public class GoodReadsParserTest {
|
|||||||
// Mock enabled provider
|
// Mock enabled provider
|
||||||
mockSettings(true);
|
mockSettings(true);
|
||||||
|
|
||||||
// Two expected URLs
|
// Two expected URLs: search + GraphQL
|
||||||
mockHttpClientResponse("https://www.goodreads.com/book/auto_complete", 200, exampleSearchJsonFixture);
|
mockHttpClientResponse("https://www.goodreads.com/book/auto_complete", 200, exampleSearchJsonFixture);
|
||||||
mockJsoupResponse("https://www.goodreads.com/book/show/", exampleBookHtmlFixture);
|
mockHttpClientResponse("https://kxbwmqov6jgg3daaamb744ycu4.appsync-api.us-east-1.amazonaws.com/graphql", 200, exampleGraphqlResponseFixture);
|
||||||
|
|
||||||
// When
|
// When
|
||||||
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"getBookByLegacyId": {
|
||||||
|
"title": "A Clockwork Orange",
|
||||||
|
"description": "In Anthony Burgess's influential nightmare vision of the future, criminals take over after dark. Teen gang leader Alex narrates in fantastically inventive slang that echoes the brutal realities of a world that is both horrifying and yet mesmerizing. This edition includes the controversial final chapter that was omitted from the original American publication, offering readers a complete and unexpurgated experience of one of the most powerful and thought-provoking works of dystopian fiction ever written. A c",
|
||||||
|
"imageUrl": "https://m.media-amazon.com/images/S/compressed.photo.goodreads.com/books/1549260060i/41817486.jpg",
|
||||||
|
"primaryContributorEdge": {
|
||||||
|
"node": {
|
||||||
|
"name": "Anthony Burgess"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"secondaryContributorEdges": [],
|
||||||
|
"bookSeries": [],
|
||||||
|
"bookGenres": [
|
||||||
|
{ "genre": { "name": "Classics" } },
|
||||||
|
{ "genre": { "name": "Fiction" } },
|
||||||
|
{ "genre": { "name": "Science Fiction" } },
|
||||||
|
{ "genre": { "name": "Dystopia" } },
|
||||||
|
{ "genre": { "name": "Literature" } }
|
||||||
|
],
|
||||||
|
"details": {
|
||||||
|
"numPages": "240",
|
||||||
|
"publicationTime": 1.426896E12,
|
||||||
|
"publisher": "W. W. Norton & Company",
|
||||||
|
"isbn": "0393341763",
|
||||||
|
"isbn13": "9780393341768",
|
||||||
|
"language": {
|
||||||
|
"name": "English"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"work": {
|
||||||
|
"stats": {
|
||||||
|
"averageRating": "4.00",
|
||||||
|
"ratingsCount": "782433"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user