fix(goodreads): use autocomplete endpoint for metadata provider (#1456)
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
package org.booklore.service.metadata.parser;
|
package org.booklore.service.metadata.parser;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
import tools.jackson.databind.JsonNode;
|
import tools.jackson.databind.JsonNode;
|
||||||
import tools.jackson.databind.ObjectMapper;
|
import tools.jackson.databind.ObjectMapper;
|
||||||
import tools.jackson.databind.json.JsonMapper;
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
@@ -14,19 +15,21 @@ 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.apache.commons.text.similarity.FuzzyScore;
|
|
||||||
import org.jsoup.Connection;
|
import org.jsoup.Connection;
|
||||||
import org.jsoup.Jsoup;
|
import org.jsoup.Jsoup;
|
||||||
import org.jsoup.nodes.Document;
|
import org.jsoup.nodes.Document;
|
||||||
import org.jsoup.nodes.Element;
|
import org.jsoup.nodes.Element;
|
||||||
import org.jsoup.select.Elements;
|
|
||||||
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 java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
@@ -35,27 +38,27 @@ 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.Matcher;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
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 String BASE_SEARCH_URL = "https://www.goodreads.com/search?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_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 int COUNT_DETAILED_METADATA_TO_GET = 3;
|
private static final int COUNT_DETAILED_METADATA_TO_GET = 3;
|
||||||
private static final int COUNT_DETAILED_METADATA_TO_GET_RETRY = 2;
|
|
||||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
|
||||||
private static final Pattern BOOK_SHOW_ID_PATTERN = Pattern.compile("/book/show/(\\d+)");
|
|
||||||
private static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder().build();
|
private static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
private final HttpClient httpClient;
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
|
|
||||||
private record TitleInfo(String title, String subtitle) {}
|
private record TitleInfo(String title, String subtitle) {}
|
||||||
|
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
private record GoodreadsAutocompleteEntry(String bookId) {}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public BookMetadata fetchTopMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
|
public BookMetadata fetchTopMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
|
||||||
String existingGoodreadsId = getExistingGoodreadsId(book);
|
String existingGoodreadsId = getExistingGoodreadsId(book);
|
||||||
@@ -140,51 +143,24 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
List<BookMetadata> previews = fetchMetadataPreviews(book, fetchMetadataRequest).stream()
|
List<String> searchResultIds = fetchSearchResults(book, fetchMetadataRequest).stream()
|
||||||
.limit(COUNT_DETAILED_METADATA_TO_GET)
|
.limit(COUNT_DETAILED_METADATA_TO_GET)
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
for (BookMetadata preview : previews) {
|
for (String goodreadsId : searchResultIds) {
|
||||||
if (sink.isCancelled()) return;
|
if (sink.isCancelled()) return;
|
||||||
log.info("GoodReads: Fetching metadata for: {}", preview.getTitle());
|
log.info("GoodReads: Fetching metadata for: Goodreads ID {}", goodreadsId);
|
||||||
try {
|
try {
|
||||||
Document document = fetchDoc(BASE_BOOK_URL + preview.getGoodreadsId());
|
Document document = fetchDoc(BASE_BOOK_URL + goodreadsId);
|
||||||
BookMetadata detailedMetadata = parseBookDetails(document, preview.getGoodreadsId());
|
BookMetadata detailedMetadata = parseBookDetails(document, goodreadsId);
|
||||||
if (detailedMetadata != null) {
|
if (detailedMetadata != null) {
|
||||||
sink.next(detailedMetadata);
|
sink.next(detailedMetadata);
|
||||||
}
|
}
|
||||||
Thread.sleep(ThreadLocalRandom.current().nextLong(500, 1501));
|
Thread.sleep(ThreadLocalRandom.current().nextLong(500, 1501));
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Error fetching metadata for book: {}", preview.getGoodreadsId(), e);
|
log.error("Error fetching metadata for book: {}", goodreadsId, e);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fetchMetadataRequest.getTitle() != null && !fetchMetadataRequest.getTitle().isBlank()
|
|
||||||
&& fetchMetadataRequest.getAuthor() != null && !fetchMetadataRequest.getAuthor().isBlank()
|
|
||||||
&& previews.isEmpty()) {
|
|
||||||
|
|
||||||
log.info("GoodReads: No hits for Title + Author search, retrying with Title only: {}", fetchMetadataRequest.getTitle());
|
|
||||||
FetchMetadataRequest titleOnlyRequest = FetchMetadataRequest.builder()
|
|
||||||
.title(fetchMetadataRequest.getTitle())
|
|
||||||
.build();
|
|
||||||
|
|
||||||
List<BookMetadata> titleOnlyPreviews = fetchMetadataPreviews(book, titleOnlyRequest).stream()
|
|
||||||
.limit(COUNT_DETAILED_METADATA_TO_GET_RETRY)
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
for (BookMetadata preview : titleOnlyPreviews) {
|
|
||||||
if (sink.isCancelled()) return;
|
|
||||||
log.info("GoodReads: Fetching metadata (Title only hit) for: {}", preview.getTitle());
|
|
||||||
try {
|
|
||||||
Document document = fetchDoc(BASE_BOOK_URL + preview.getGoodreadsId());
|
|
||||||
BookMetadata detailedMetadata = parseBookDetails(document, preview.getGoodreadsId());
|
|
||||||
if (detailedMetadata != null) {
|
|
||||||
sink.next(detailedMetadata);
|
|
||||||
}
|
|
||||||
Thread.sleep(ThreadLocalRandom.current().nextLong(500, 1501));
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("Error fetching metadata for book (Title only retry): {}", preview.getGoodreadsId(), e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -494,12 +470,13 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
|
|
||||||
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_SEARCH_URL + encodedSearchTerm;
|
String url = BASE_AUTOCOMPLETE_URL + encodedSearchTerm;
|
||||||
log.info("Goodreads Query URL: {}", url);
|
log.info("Goodreads Query URL: {}", url);
|
||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<BookMetadata> fetchMetadataPreviews(Book book, FetchMetadataRequest request) {
|
|
||||||
|
public List<String> fetchSearchResults(Book book, FetchMetadataRequest request) throws InterruptedException {
|
||||||
String searchTerm = getSearchTerm(book, request);
|
String searchTerm = getSearchTerm(book, request);
|
||||||
|
|
||||||
if (searchTerm == null || searchTerm.isEmpty()) {
|
if (searchTerm == null || searchTerm.isEmpty()) {
|
||||||
@@ -509,56 +486,22 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
String searchUrl = generateSearchUrl(searchTerm);
|
String searchUrl = generateSearchUrl(searchTerm);
|
||||||
Document doc = fetchDoc(searchUrl);
|
|
||||||
Element tableList = doc.select("table.tableList").first();
|
|
||||||
|
|
||||||
if (tableList == null) {
|
List<GoodreadsAutocompleteEntry> records = fetchJson(
|
||||||
log.warn("GoodReads: No results table found for search term: {}", searchTerm);
|
searchUrl,
|
||||||
return Collections.emptyList();
|
AUTOCOMPLETE_RESPONSE_TYPE
|
||||||
}
|
);
|
||||||
|
|
||||||
Elements previewBooks = tableList.select("tr[itemtype=http://schema.org/Book]");
|
|
||||||
|
|
||||||
List<BookMetadata> metadataPreviews = new ArrayList<>();
|
|
||||||
FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);
|
|
||||||
String queryAuthor = request.getAuthor();
|
|
||||||
|
|
||||||
for (Element previewBook : previewBooks) {
|
|
||||||
List<String> authors = extractAuthorsPreview(previewBook);
|
|
||||||
|
|
||||||
if (queryAuthor != null && !queryAuthor.isBlank()) {
|
|
||||||
List<String> queryAuthorTokens = List.of(WHITESPACE_PATTERN.split(queryAuthor.toLowerCase()));
|
|
||||||
boolean matches = authors.stream()
|
|
||||||
.flatMap(a -> Arrays.stream(WHITESPACE_PATTERN.split(a.toLowerCase())))
|
|
||||||
.anyMatch(actual -> {
|
|
||||||
for (String query : queryAuthorTokens) {
|
|
||||||
int score = fuzzyScore.fuzzyScore(actual, query);
|
|
||||||
int maxScore = Math.max(fuzzyScore.fuzzyScore(query, query),
|
|
||||||
fuzzyScore.fuzzyScore(actual, actual));
|
|
||||||
double similarity = maxScore > 0 ? (double) score / maxScore : 0;
|
|
||||||
if (similarity >= 0.5) return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!matches) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
BookMetadata previewMetadata = BookMetadata.builder()
|
|
||||||
.goodreadsId(String.valueOf(extractGoodReadsIdPreview(previewBook)))
|
|
||||||
.title(extractTitlePreview(previewBook))
|
|
||||||
.authors(authors)
|
|
||||||
.provider(MetadataProvider.GoodReads)
|
|
||||||
.thumbnailUrl(extractThumbnailPreview(previewBook))
|
|
||||||
.build();
|
|
||||||
metadataPreviews.add(previewMetadata);
|
|
||||||
}
|
|
||||||
|
|
||||||
Thread.sleep(Duration.ofSeconds(1));
|
Thread.sleep(Duration.ofSeconds(1));
|
||||||
return metadataPreviews;
|
return records.stream()
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.map(r -> r.bookId)
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.filter(id -> !id.isBlank())
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Error fetching metadata previews: {}", e.getMessage());
|
log.error("Error fetching metadata previews: {}", e.getMessage());
|
||||||
return Collections.emptyList();
|
return Collections.emptyList();
|
||||||
@@ -567,9 +510,8 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
|
|
||||||
private String getSearchTerm(Book book, FetchMetadataRequest request) {
|
private String getSearchTerm(Book book, FetchMetadataRequest request) {
|
||||||
if (request.getTitle() != null && !request.getTitle().isEmpty()) {
|
if (request.getTitle() != null && !request.getTitle().isEmpty()) {
|
||||||
if (request.getAuthor() != null && !request.getAuthor().isEmpty()) {
|
// We used to include the author name, but with the new autocomplete
|
||||||
return request.getTitle() + " " + request.getAuthor();
|
// endpoint it leads to less reliable results.
|
||||||
}
|
|
||||||
return request.getTitle();
|
return request.getTitle();
|
||||||
}
|
}
|
||||||
return (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null && !book.getPrimaryFile().getFileName().isEmpty()
|
return (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null && !book.getPrimaryFile().getFileName().isEmpty()
|
||||||
@@ -577,62 +519,6 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
: null);
|
: null);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Integer extractGoodReadsIdPreview(Element book) {
|
|
||||||
try {
|
|
||||||
Element bookTitle = book.select("a.bookTitle").first();
|
|
||||||
if (bookTitle == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String href = bookTitle.attr("href");
|
|
||||||
Matcher matcher = BOOK_SHOW_ID_PATTERN.matcher(href);
|
|
||||||
if (matcher.find()) {
|
|
||||||
return Integer.valueOf(matcher.group(1));
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<String> extractAuthorsPreview(Element book) {
|
|
||||||
List<String> authors = new ArrayList<>();
|
|
||||||
try {
|
|
||||||
Elements authorsElement = book.select("a.authorName");
|
|
||||||
for (Element authorElement : authorsElement) {
|
|
||||||
authors.add(authorElement.text());
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Error extracting author: {}", e.getMessage());
|
|
||||||
return authors;
|
|
||||||
}
|
|
||||||
return authors;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String extractTitlePreview(Element book) {
|
|
||||||
try {
|
|
||||||
Element link = book.select("a[title]").first();
|
|
||||||
return link != null ? link.attr("title") : null;
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Error extracting title: {}", e.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String extractThumbnailPreview(Element book) {
|
|
||||||
try {
|
|
||||||
Element img = book.selectFirst("img");
|
|
||||||
if (img != null) {
|
|
||||||
String src = img.attr("src");
|
|
||||||
if (!src.isBlank()) {
|
|
||||||
return src;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Error extracting thumbnail: {}", e.getMessage());
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
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);
|
||||||
@@ -645,9 +531,32 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private <T> T fetchJson(String url, TypeReference<T> typeReference) throws InterruptedException {
|
||||||
|
HttpRequest request = HttpRequest.newBuilder()
|
||||||
|
.uri(URI.create(url))
|
||||||
|
.GET()
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try {
|
||||||
|
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
|
|
||||||
|
if (response.statusCode() < 200 || response.statusCode() > 399) {
|
||||||
|
log.error("GoodReads request failed with status code: {}", response.statusCode());
|
||||||
|
throw new RuntimeException("Failed to query GoodReads");
|
||||||
|
}
|
||||||
|
|
||||||
|
return OBJECT_MAPPER.readValue(response.body(), typeReference);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw e;
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("GoodReads request failed", e);
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private Document fetchDoc(String url) {
|
private Document fetchDoc(String url) {
|
||||||
try {
|
try {
|
||||||
Connection.Response response = Jsoup.connect(url)
|
return Jsoup.connect(url)
|
||||||
.header("accept", "text/html, application/json")
|
.header("accept", "text/html, application/json")
|
||||||
.header("accept-language", "en-US,en;q=0.9")
|
.header("accept-language", "en-US,en;q=0.9")
|
||||||
.header("content-type", "application/json")
|
.header("content-type", "application/json")
|
||||||
@@ -672,8 +581,7 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
|
|||||||
.header("x-amz-amabot-click-attributes", "disable")
|
.header("x-amz-amabot-click-attributes", "disable")
|
||||||
.header("x-requested-with", "XMLHttpRequest")
|
.header("x-requested-with", "XMLHttpRequest")
|
||||||
.method(Connection.Method.GET)
|
.method(Connection.Method.GET)
|
||||||
.execute();
|
.get();
|
||||||
return response.parse();
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("Error parsing url: {}", url, e);
|
log.error("Error parsing url: {}", url, e);
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
|
|||||||
@@ -0,0 +1,217 @@
|
|||||||
|
|
||||||
|
package org.booklore.service.metadata.parser;
|
||||||
|
|
||||||
|
import org.booklore.model.dto.Book;
|
||||||
|
import org.booklore.model.dto.BookMetadata;
|
||||||
|
import org.booklore.model.dto.request.FetchMetadataRequest;
|
||||||
|
import org.booklore.model.dto.settings.AppSettings;
|
||||||
|
import org.booklore.model.dto.settings.MetadataProviderSettings;
|
||||||
|
import org.booklore.model.dto.settings.MetadataPublicReviewsSettings;
|
||||||
|
import org.booklore.model.enums.MetadataProvider;
|
||||||
|
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.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
public class GoodReadsParserTest {
|
||||||
|
@Mock
|
||||||
|
private AppSettingService appSettingService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private HttpClient httpClient;
|
||||||
|
|
||||||
|
private MockedStatic<Jsoup> mockJsoup;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private GoodReadsParser parser;
|
||||||
|
|
||||||
|
private String exampleSearchJsonFixture;
|
||||||
|
|
||||||
|
private String exampleBookHtmlFixture;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws IOException {
|
||||||
|
exampleSearchJsonFixture = readFixture("example-search.json");
|
||||||
|
exampleBookHtmlFixture = readFixture("example-book.html");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
mockJsoup = mockStatic(Jsoup.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() {
|
||||||
|
mockJsoup.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void mockSettings(boolean enabled) {
|
||||||
|
AppSettings appSettings = new AppSettings();
|
||||||
|
MetadataProviderSettings providerSettings = new MetadataProviderSettings();
|
||||||
|
MetadataProviderSettings.Goodreads goodreads = new MetadataProviderSettings.Goodreads();
|
||||||
|
goodreads.setEnabled(enabled);
|
||||||
|
providerSettings.setGoodReads(goodreads);
|
||||||
|
appSettings.setMetadataProviderSettings(providerSettings);
|
||||||
|
|
||||||
|
MetadataPublicReviewsSettings.ReviewProviderConfig provider = MetadataPublicReviewsSettings.ReviewProviderConfig.builder()
|
||||||
|
.provider(MetadataProvider.GoodReads)
|
||||||
|
.enabled(enabled)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
MetadataPublicReviewsSettings reviewSettings = MetadataPublicReviewsSettings.builder()
|
||||||
|
.providers(Set.of(provider))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
appSettings.setMetadataPublicReviewsSettings(reviewSettings);
|
||||||
|
|
||||||
|
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String readFixture(String fixtureName) throws IOException {
|
||||||
|
String filename = Paths.get("goodreads", fixtureName + ".fixture").toString();
|
||||||
|
|
||||||
|
try (InputStream is = getClass().getClassLoader().getResourceAsStream(filename)) {
|
||||||
|
assert is != null;
|
||||||
|
|
||||||
|
return new String(is.readAllBytes(), StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private HttpResponse<String> getMockResponse(int statusCode, String response) {
|
||||||
|
HttpResponse<String> httpResponse = (HttpResponse<String>) mock(HttpResponse.class);
|
||||||
|
|
||||||
|
when(httpResponse.statusCode()).thenReturn(statusCode);
|
||||||
|
|
||||||
|
if (response != null) {
|
||||||
|
when(httpResponse.body()).thenReturn(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
return httpResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void mockHttpClientResponse(String urlPrefix, int statusCode, String response) throws Exception {
|
||||||
|
when(
|
||||||
|
httpClient.<String>send(
|
||||||
|
argThat(r -> r.uri().toString().startsWith(urlPrefix)),
|
||||||
|
any()
|
||||||
|
)
|
||||||
|
).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
|
||||||
|
void testFetchMetadata_EmptyQuery() {
|
||||||
|
// Given
|
||||||
|
Book book = Book.builder()
|
||||||
|
.title("Test Book")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||||
|
.build();
|
||||||
|
// Empty query - no title or ISBN
|
||||||
|
|
||||||
|
// When
|
||||||
|
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertThat(results).isNotNull();
|
||||||
|
assertThat(results).as("Should return empty list when query is empty").isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFetchMetadata_parsesBook() throws Exception {
|
||||||
|
// Given
|
||||||
|
Book book = Book.builder()
|
||||||
|
.title("A Clockwork Orange")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||||
|
.title("A Clockwork Orange")
|
||||||
|
.author("Anthony Burgess")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// Mock enabled provider
|
||||||
|
mockSettings(true);
|
||||||
|
|
||||||
|
// Two expected URLs
|
||||||
|
mockHttpClientResponse("https://www.goodreads.com/book/auto_complete", 200, exampleSearchJsonFixture);
|
||||||
|
mockJsoupResponse("https://www.goodreads.com/book/show/", exampleBookHtmlFixture);
|
||||||
|
|
||||||
|
// When
|
||||||
|
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertThat(results).isNotNull();
|
||||||
|
assertThat(results).as("Should return results for real book").isNotEmpty();
|
||||||
|
|
||||||
|
BookMetadata result = results.getFirst();
|
||||||
|
assertThat(result.getTitle()).isEqualTo("A Clockwork Orange");
|
||||||
|
assertThat(result.getIsbn10()).isEqualTo("0393341763");
|
||||||
|
assertThat(result.getIsbn13()).isEqualTo("9780393341768");
|
||||||
|
assertThat(result.getGoodreadsId()).isEqualTo("41817486");
|
||||||
|
assertThat(result.getAuthors()).isNotNull();
|
||||||
|
assertThat(result.getAuthors()).hasSize(1);
|
||||||
|
assertThat(result.getAuthors().getFirst()).isEqualTo("Anthony Burgess");
|
||||||
|
|
||||||
|
// The description is very long, but we need to make sure we're in the right ballpark.
|
||||||
|
assertThat(result.getDescription()).startsWith("In Anthony Burgess's influential");
|
||||||
|
assertThat(result.getDescription()).hasSize(511);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFetchMetadata_withRateLimitingError() throws Exception {
|
||||||
|
// Given
|
||||||
|
Book book = Book.builder()
|
||||||
|
.title("A Clockwork Orange")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
FetchMetadataRequest request = FetchMetadataRequest.builder()
|
||||||
|
.title("A Clockwork Orange")
|
||||||
|
.author("Anthony Burgess")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// Two expected URLs
|
||||||
|
mockHttpClientResponse("https://www.goodreads.com/book/auto_complete", 429, null);
|
||||||
|
|
||||||
|
// When
|
||||||
|
List<BookMetadata> results = parser.fetchMetadata(book, request);
|
||||||
|
|
||||||
|
// Then
|
||||||
|
assertThat(results).isNotNull();
|
||||||
|
assertThat(results).as("Should not return results").isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,142 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"imageUrl":"https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1549260060i/41817486._SX50_.jpg",
|
||||||
|
"bookId":"41817486",
|
||||||
|
"workId":"23596",
|
||||||
|
"bookUrl":"/book/show/41817486-a-clockwork-orange",
|
||||||
|
"from_search":true,
|
||||||
|
"from_srp":true,
|
||||||
|
"qid":"Gdu5vdYSS1",
|
||||||
|
"rank":1,
|
||||||
|
"title":"A Clockwork Orange",
|
||||||
|
"bookTitleBare":"A Clockwork Orange",
|
||||||
|
"numPages":240,
|
||||||
|
"avgRating":"4.00",
|
||||||
|
"ratingsCount":782433,
|
||||||
|
"author":{
|
||||||
|
"id":5735,
|
||||||
|
"name":"Anthony Burgess",
|
||||||
|
"isGoodreadsAuthor":false,
|
||||||
|
"profileUrl":"https://www.goodreads.com/author/show/5735.Anthony_Burgess",
|
||||||
|
"worksListUrl":"https://www.goodreads.com/author/list/5735.Anthony_Burgess"
|
||||||
|
},
|
||||||
|
"kcrPreviewUrl":"https://read.amazon.com/kp/embed?asin=B005HSGB6W\u0026ref=x_gr_w_preview_new_nf_story-20\u0026tag=x_gr_w_preview_new_nf_story-20\u0026preview=inline",
|
||||||
|
"description":{
|
||||||
|
"html":"In Anthony Burgess\u0026apos;s influential nightmare vision of the future, criminals take over after dark. Teen gang leader Alex narrates in fantastically inventive slang that echoes th…",
|
||||||
|
"truncated":true,
|
||||||
|
"fullContentUrl":"https://www.goodreads.com/book/show/41817486-a-clockwork-orange"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"imageUrl":"https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1388286789i/8809._SY75_.jpg",
|
||||||
|
"bookId":"8809",
|
||||||
|
"workId":"1416684",
|
||||||
|
"bookUrl":"/book/show/8809.The_Wanting_Seed",
|
||||||
|
"from_search":true,
|
||||||
|
"from_srp":true,
|
||||||
|
"qid":"Gdu5vdYSS1",
|
||||||
|
"rank":2,
|
||||||
|
"title":"The Wanting Seed",
|
||||||
|
"bookTitleBare":"The Wanting Seed",
|
||||||
|
"numPages":288,
|
||||||
|
"avgRating":"3.72",
|
||||||
|
"ratingsCount":6995,
|
||||||
|
"author":{
|
||||||
|
"id":5735,
|
||||||
|
"name":"Anthony Burgess",
|
||||||
|
"isGoodreadsAuthor":false,
|
||||||
|
"profileUrl":"https://www.goodreads.com/author/show/5735.Anthony_Burgess",
|
||||||
|
"worksListUrl":"https://www.goodreads.com/author/list/5735.Anthony_Burgess"
|
||||||
|
},
|
||||||
|
"kcrPreviewUrl":null,
|
||||||
|
"description":{
|
||||||
|
"html":"Set in the near future, The Wanting Seed is a Malthusian comedy about the strange world overpopulation will produce. Tristram Foxe and his wife, Beatrice-Joanna, live in the…",
|
||||||
|
"truncated":true,
|
||||||
|
"fullContentUrl":"https://www.goodreads.com/book/show/8809.The_Wanting_Seed"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"imageUrl":"https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1171476306i/101118._SY75_.jpg",
|
||||||
|
"bookId":"101118",
|
||||||
|
"workId":"97495",
|
||||||
|
"bookUrl":"/book/show/101118.Byrne",
|
||||||
|
"from_search":true,
|
||||||
|
"from_srp":true,
|
||||||
|
"qid":"Gdu5vdYSS1",
|
||||||
|
"rank":3,
|
||||||
|
"title":"Byrne (Burgess, Anthony)",
|
||||||
|
"bookTitleBare":"Byrne",
|
||||||
|
"numPages":160,
|
||||||
|
"avgRating":"3.40",
|
||||||
|
"ratingsCount":181,
|
||||||
|
"author":{
|
||||||
|
"id":5735,
|
||||||
|
"name":"Anthony Burgess",
|
||||||
|
"isGoodreadsAuthor":false,
|
||||||
|
"profileUrl":"https://www.goodreads.com/author/show/5735.Anthony_Burgess",
|
||||||
|
"worksListUrl":"https://www.goodreads.com/author/list/5735.Anthony_Burgess"
|
||||||
|
},
|
||||||
|
"kcrPreviewUrl":null,
|
||||||
|
"description":{
|
||||||
|
"html":"The first American publication of the late writer\u0026apos;s comic-satiric epic novel in verse tells the story of a Don Juan-type Irish artist who vanishes under Hitler\u0026apos;s regime. By th…",
|
||||||
|
"truncated":true,
|
||||||
|
"fullContentUrl":"https://www.goodreads.com/book/show/101118.Byrne"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"imageUrl":"https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1355598044i/8822._SY75_.jpg",
|
||||||
|
"bookId":"8822",
|
||||||
|
"workId":"1282899",
|
||||||
|
"bookUrl":"/book/show/8822.Earthly_Powers",
|
||||||
|
"from_search":true,
|
||||||
|
"from_srp":true,
|
||||||
|
"qid":"Gdu5vdYSS1",
|
||||||
|
"rank":4,
|
||||||
|
"title":"Earthly Powers",
|
||||||
|
"bookTitleBare":"Earthly Powers",
|
||||||
|
"numPages":649,
|
||||||
|
"avgRating":"4.13",
|
||||||
|
"ratingsCount":3449,
|
||||||
|
"author":{
|
||||||
|
"id":5735,
|
||||||
|
"name":"Anthony Burgess",
|
||||||
|
"isGoodreadsAuthor":false,
|
||||||
|
"profileUrl":"https://www.goodreads.com/author/show/5735.Anthony_Burgess",
|
||||||
|
"worksListUrl":"https://www.goodreads.com/author/list/5735.Anthony_Burgess"
|
||||||
|
},
|
||||||
|
"kcrPreviewUrl":"https://read.amazon.com/kp/embed?asin=B08Q61J6ZH\u0026ref=x_gr_w_preview_new_nf_story-20\u0026tag=x_gr_w_preview_new_nf_story-20\u0026preview=inline",
|
||||||
|
"description":{
|
||||||
|
"html":"Anthony Burgess, author of \u003ci\u003eA Clockwork Orange,\u003c/i\u003e is regarded as one of the most original and daring writers in the English language. His work is illuminated by a dazzling imagin…",
|
||||||
|
"truncated":true,
|
||||||
|
"fullContentUrl":"https://www.goodreads.com/book/show/8822.Earthly_Powers"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"imageUrl":"https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1347654176i/2418008._SY75_.jpg",
|
||||||
|
"bookId":"2418008",
|
||||||
|
"workId":"2425185",
|
||||||
|
"bookUrl":"/book/show/2418008.Anthony_Burgess",
|
||||||
|
"from_search":true,
|
||||||
|
"from_srp":true,
|
||||||
|
"qid":"Gdu5vdYSS1",
|
||||||
|
"rank":5,
|
||||||
|
"title":"Anthony Burgess",
|
||||||
|
"bookTitleBare":"Anthony Burgess",
|
||||||
|
"numPages":400,
|
||||||
|
"avgRating":"2.68",
|
||||||
|
"ratingsCount":81,
|
||||||
|
"author":{
|
||||||
|
"id":15095,
|
||||||
|
"name":"Roger Lewis",
|
||||||
|
"isGoodreadsAuthor":false,
|
||||||
|
"profileUrl":"https://www.goodreads.com/author/show/15095.Roger_Lewis",
|
||||||
|
"worksListUrl":"https://www.goodreads.com/author/list/15095.Roger_Lewis"
|
||||||
|
},
|
||||||
|
"kcrPreviewUrl":"https://read.amazon.com/kp/embed?asin=B00HFTZWGG\u0026ref=x_gr_w_preview_new_nf_story-20\u0026tag=x_gr_w_preview_new_nf_story-20\u0026preview=inline",
|
||||||
|
"description":{
|
||||||
|
"html":"This biography is the culmination and distillation of 20 years\u0026apos; work on Anthony Burgess (1917-1993), the author who remains best known for \u0026quot;A Clockwork Orange\u0026quot;, the source for…",
|
||||||
|
"truncated":true,
|
||||||
|
"fullContentUrl":"https://www.goodreads.com/book/show/2418008.Anthony_Burgess"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
Reference in New Issue
Block a user