feat(hardcover): implement book details response and search service enhancements (#2303)
Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
+246
-102
@@ -4,8 +4,7 @@ import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
|
||||
import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
import com.adityachandel.booklore.service.metadata.parser.hardcover.GraphQLResponse;
|
||||
import com.adityachandel.booklore.service.metadata.parser.hardcover.HardcoverBookSearchService;
|
||||
import com.adityachandel.booklore.service.metadata.parser.hardcover.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.text.WordUtils;
|
||||
@@ -15,9 +14,7 @@ import org.springframework.stereotype.Service;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -27,6 +24,8 @@ import java.util.stream.Collectors;
|
||||
public class HardcoverParser implements BookParser {
|
||||
|
||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
||||
private static final double AUTHOR_MATCH_THRESHOLD = 0.5;
|
||||
|
||||
private final HardcoverBookSearchService hardcoverBookSearchService;
|
||||
|
||||
@Override
|
||||
@@ -39,114 +38,259 @@ public class HardcoverParser implements BookParser {
|
||||
log.info("Hardcover: Fetching metadata using ISBN {}", fetchMetadataRequest.getIsbn());
|
||||
hits = hardcoverBookSearchService.searchBooks(fetchMetadataRequest.getIsbn());
|
||||
} else {
|
||||
log.info("Hardcover: Fetching metadata using title '{}'", fetchMetadataRequest.getTitle());
|
||||
hits = hardcoverBookSearchService.searchBooks(fetchMetadataRequest.getTitle());
|
||||
// Use improved search strategy with title cleaning and fallbacks
|
||||
hits = performSmartSearch(fetchMetadataRequest);
|
||||
}
|
||||
|
||||
if (hits == null || hits.isEmpty()) {
|
||||
log.info("Hardcover: No results found for {}", searchByIsbn ? "ISBN " + fetchMetadataRequest.getIsbn() : "title " + fetchMetadataRequest.getTitle());
|
||||
log.info("Hardcover: No results found for {}",
|
||||
searchByIsbn ? "ISBN " + fetchMetadataRequest.getIsbn() : "title " + fetchMetadataRequest.getTitle());
|
||||
return List.of();
|
||||
}
|
||||
|
||||
FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);
|
||||
String searchAuthor = fetchMetadataRequest.getAuthor() != null ? fetchMetadataRequest.getAuthor() : "";
|
||||
|
||||
return hits.stream()
|
||||
// Filter by author and map to metadata
|
||||
List<GraphQLResponse.Document> matchedDocs = hits.stream()
|
||||
.map(GraphQLResponse.Hit::getDocument)
|
||||
.filter(doc -> {
|
||||
if (searchByIsbn || searchAuthor.isBlank()) return true;
|
||||
|
||||
if (doc.getAuthorNames() == null || doc.getAuthorNames().isEmpty()) return false;
|
||||
|
||||
List<String> actualAuthorTokens = doc.getAuthorNames().stream()
|
||||
.map(String::toLowerCase)
|
||||
.flatMap(WHITESPACE_PATTERN::splitAsStream)
|
||||
.toList();
|
||||
List<String> searchAuthorTokens = List.of(WHITESPACE_PATTERN.split(searchAuthor.toLowerCase()));
|
||||
|
||||
for (String actual : actualAuthorTokens) {
|
||||
for (String query : searchAuthorTokens) {
|
||||
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;
|
||||
})
|
||||
.map(doc -> {
|
||||
BookMetadata metadata = new BookMetadata();
|
||||
metadata.setHardcoverId(doc.getSlug());
|
||||
// Set numeric book ID for API operations
|
||||
if (doc.getId() != null) {
|
||||
try {
|
||||
metadata.setHardcoverBookId(Integer.parseInt(doc.getId()));
|
||||
} catch (NumberFormatException e) {
|
||||
log.debug("Could not parse Hardcover book ID: {}", doc.getId());
|
||||
}
|
||||
}
|
||||
metadata.setTitle(doc.getTitle());
|
||||
metadata.setSubtitle(doc.getSubtitle());
|
||||
metadata.setDescription(doc.getDescription());
|
||||
if (doc.getAuthorNames() != null) {
|
||||
metadata.setAuthors(Set.copyOf(doc.getAuthorNames()));
|
||||
}
|
||||
|
||||
if (doc.getFeaturedSeries() != null) {
|
||||
if (doc.getFeaturedSeries().getSeries() != null) {
|
||||
metadata.setSeriesName(doc.getFeaturedSeries().getSeries().getName());
|
||||
metadata.setSeriesTotal(doc.getFeaturedSeries().getSeries().getBooksCount());
|
||||
}
|
||||
if (doc.getFeaturedSeries().getPosition() != null) {
|
||||
try {
|
||||
metadata.setSeriesNumber(Float.parseFloat(String.valueOf(doc.getFeaturedSeries().getPosition())));
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (doc.getRating() != null) {
|
||||
metadata.setHardcoverRating(BigDecimal.valueOf(doc.getRating()).setScale(2, RoundingMode.HALF_UP).doubleValue());
|
||||
}
|
||||
metadata.setHardcoverReviewCount(doc.getRatingsCount());
|
||||
metadata.setPageCount(doc.getPages());
|
||||
metadata.setPublishedDate(doc.getReleaseDate() != null ? LocalDate.parse(doc.getReleaseDate()) : null);
|
||||
|
||||
if (doc.getGenres() != null && !doc.getGenres().isEmpty()) {
|
||||
metadata.setCategories(doc.getGenres().stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
if (doc.getMoods() != null && !doc.getMoods().isEmpty()) {
|
||||
metadata.setMoods(doc.getMoods().stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
if (doc.getTags() != null && !doc.getTags().isEmpty()) {
|
||||
metadata.setTags(doc.getTags().stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
if (doc.getIsbns() != null) {
|
||||
String inputIsbn = fetchMetadataRequest.getIsbn();
|
||||
if (inputIsbn != null && inputIsbn.length() == 10 && doc.getIsbns().contains(inputIsbn)) {
|
||||
metadata.setIsbn10(inputIsbn);
|
||||
} else {
|
||||
metadata.setIsbn10(doc.getIsbns().stream().filter(isbn -> isbn.length() == 10).findFirst().orElse(null));
|
||||
}
|
||||
if (inputIsbn != null && inputIsbn.length() == 13 && doc.getIsbns().contains(inputIsbn)) {
|
||||
metadata.setIsbn13(inputIsbn);
|
||||
} else {
|
||||
metadata.setIsbn13(doc.getIsbns().stream().filter(isbn -> isbn.length() == 13).findFirst().orElse(null));
|
||||
}
|
||||
}
|
||||
|
||||
metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null);
|
||||
metadata.setProvider(MetadataProvider.Hardcover);
|
||||
return metadata;
|
||||
})
|
||||
.filter(doc -> filterByAuthor(doc, searchAuthor, searchByIsbn, fuzzyScore))
|
||||
.toList();
|
||||
|
||||
if (matchedDocs.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// Only fetch detailed mood data for the TOP match to minimize API calls
|
||||
// Other results use the basic mood data from search
|
||||
List<BookMetadata> results = new ArrayList<>();
|
||||
boolean isFirst = true;
|
||||
|
||||
for (GraphQLResponse.Document doc : matchedDocs) {
|
||||
BookMetadata metadata = mapDocumentToMetadata(doc, fetchMetadataRequest, isFirst);
|
||||
results.add(metadata);
|
||||
isFirst = false;
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private List<GraphQLResponse.Hit> performSmartSearch(FetchMetadataRequest request) {
|
||||
String title = request.getTitle();
|
||||
String author = request.getAuthor();
|
||||
|
||||
if (title == null || title.isBlank()) {
|
||||
log.warn("Hardcover: No title provided for search");
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
if (author != null && !author.isBlank()) {
|
||||
String combinedQuery = title.trim() + " " + author.trim();
|
||||
log.info("Hardcover: Searching with title+author: '{}'", combinedQuery);
|
||||
List<GraphQLResponse.Hit> results = hardcoverBookSearchService.searchBooks(combinedQuery);
|
||||
if (results != null && !results.isEmpty()) {
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
log.info("Hardcover: Searching with title: '{}'", title);
|
||||
List<GraphQLResponse.Hit> results = hardcoverBookSearchService.searchBooks(title.trim());
|
||||
return results != null ? results : Collections.emptyList();
|
||||
}
|
||||
|
||||
private boolean filterByAuthor(GraphQLResponse.Document doc, String searchAuthor,
|
||||
boolean searchByIsbn, FuzzyScore fuzzyScore) {
|
||||
// Skip author filtering for ISBN searches or when no author provided
|
||||
if (searchByIsbn || searchAuthor.isBlank()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (doc.getAuthorNames() == null || doc.getAuthorNames().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<String> actualAuthorTokens = doc.getAuthorNames().stream()
|
||||
.map(String::toLowerCase)
|
||||
.flatMap(WHITESPACE_PATTERN::splitAsStream)
|
||||
.toList();
|
||||
List<String> searchAuthorTokens = List.of(WHITESPACE_PATTERN.split(searchAuthor.toLowerCase()));
|
||||
|
||||
for (String actual : actualAuthorTokens) {
|
||||
for (String query : searchAuthorTokens) {
|
||||
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 >= AUTHOR_MATCH_THRESHOLD) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private BookMetadata mapDocumentToMetadata(GraphQLResponse.Document doc, FetchMetadataRequest request, boolean fetchDetailedMoods) {
|
||||
BookMetadata metadata = new BookMetadata();
|
||||
metadata.setHardcoverId(doc.getSlug());
|
||||
|
||||
Integer bookId = parseBookId(doc.getId());
|
||||
if (bookId != null) {
|
||||
metadata.setHardcoverBookId(bookId);
|
||||
}
|
||||
|
||||
metadata.setTitle(doc.getTitle());
|
||||
metadata.setSubtitle(doc.getSubtitle());
|
||||
metadata.setDescription(doc.getDescription());
|
||||
|
||||
if (doc.getAuthorNames() != null) {
|
||||
metadata.setAuthors(Set.copyOf(doc.getAuthorNames()));
|
||||
}
|
||||
|
||||
mapSeriesInfo(doc, metadata);
|
||||
|
||||
if (doc.getRating() != null) {
|
||||
metadata.setHardcoverRating(
|
||||
BigDecimal.valueOf(doc.getRating()).setScale(2, RoundingMode.HALF_UP).doubleValue()
|
||||
);
|
||||
}
|
||||
metadata.setHardcoverReviewCount(doc.getRatingsCount());
|
||||
metadata.setPageCount(doc.getPages());
|
||||
|
||||
if (doc.getReleaseDate() != null) {
|
||||
try {
|
||||
metadata.setPublishedDate(LocalDate.parse(doc.getReleaseDate()));
|
||||
} catch (Exception e) {
|
||||
log.debug("Could not parse release date: {}", doc.getReleaseDate());
|
||||
}
|
||||
}
|
||||
|
||||
mapTagsAndMoods(doc, metadata, bookId, fetchDetailedMoods);
|
||||
mapIsbns(doc, request, metadata);
|
||||
|
||||
metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null);
|
||||
metadata.setProvider(MetadataProvider.Hardcover);
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private Integer parseBookId(String id) {
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(id);
|
||||
} catch (NumberFormatException e) {
|
||||
log.debug("Could not parse Hardcover book ID: {}", id);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void mapSeriesInfo(GraphQLResponse.Document doc, BookMetadata metadata) {
|
||||
if (doc.getFeaturedSeries() == null) {
|
||||
return;
|
||||
}
|
||||
if (doc.getFeaturedSeries().getSeries() != null) {
|
||||
metadata.setSeriesName(doc.getFeaturedSeries().getSeries().getName());
|
||||
metadata.setSeriesTotal(doc.getFeaturedSeries().getSeries().getBooksCount());
|
||||
}
|
||||
if (doc.getFeaturedSeries().getPosition() != null) {
|
||||
try {
|
||||
metadata.setSeriesNumber(Float.parseFloat(String.valueOf(doc.getFeaturedSeries().getPosition())));
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void mapTagsAndMoods(GraphQLResponse.Document doc, BookMetadata metadata, Integer bookId, boolean fetchDetailedMoods) {
|
||||
boolean usedDetailedMoods = false;
|
||||
|
||||
if (fetchDetailedMoods && bookId != null) {
|
||||
usedDetailedMoods = tryFetchDetailedMoods(bookId, metadata);
|
||||
}
|
||||
|
||||
if (!usedDetailedMoods && doc.getMoods() != null && !doc.getMoods().isEmpty()) {
|
||||
Set<String> basicFilteredMoods = HardcoverMoodFilter.filterBasicMoods(doc.getMoods());
|
||||
metadata.setMoods(basicFilteredMoods.stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
}
|
||||
|
||||
if ((metadata.getCategories() == null || metadata.getCategories().isEmpty())
|
||||
&& doc.getGenres() != null && !doc.getGenres().isEmpty()) {
|
||||
metadata.setCategories(doc.getGenres().stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
if ((metadata.getTags() == null || metadata.getTags().isEmpty())
|
||||
&& doc.getTags() != null && !doc.getTags().isEmpty()) {
|
||||
metadata.setTags(doc.getTags().stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean tryFetchDetailedMoods(Integer bookId, BookMetadata metadata) {
|
||||
try {
|
||||
HardcoverBookDetails details = hardcoverBookSearchService.fetchBookDetails(bookId);
|
||||
if (details == null || details.getCachedTags() == null || details.getCachedTags().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Set<String> filteredMoods = HardcoverMoodFilter.filterMoodsWithCounts(details.getCachedTags());
|
||||
if (!filteredMoods.isEmpty()) {
|
||||
metadata.setMoods(filteredMoods.stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
}
|
||||
|
||||
Set<String> filteredGenres = HardcoverMoodFilter.filterGenresWithCounts(details.getCachedTags());
|
||||
if (!filteredGenres.isEmpty()) {
|
||||
metadata.setCategories(filteredGenres.stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
}
|
||||
|
||||
Set<String> filteredTags = HardcoverMoodFilter.filterTagsWithCounts(details.getCachedTags());
|
||||
if (!filteredTags.isEmpty()) {
|
||||
metadata.setTags(filteredTags.stream()
|
||||
.map(WordUtils::capitalizeFully)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
}
|
||||
|
||||
return !filteredMoods.isEmpty();
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to fetch book details: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void mapIsbns(GraphQLResponse.Document doc, FetchMetadataRequest request, BookMetadata metadata) {
|
||||
if (doc.getIsbns() == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String inputIsbn = request.getIsbn();
|
||||
|
||||
if (inputIsbn != null && inputIsbn.length() == 10 && doc.getIsbns().contains(inputIsbn)) {
|
||||
metadata.setIsbn10(inputIsbn);
|
||||
} else {
|
||||
metadata.setIsbn10(doc.getIsbns().stream()
|
||||
.filter(isbn -> isbn.length() == 10)
|
||||
.findFirst()
|
||||
.orElse(null));
|
||||
}
|
||||
|
||||
if (inputIsbn != null && inputIsbn.length() == 13 && doc.getIsbns().contains(inputIsbn)) {
|
||||
metadata.setIsbn13(inputIsbn);
|
||||
} else {
|
||||
metadata.setIsbn13(doc.getIsbns().stream()
|
||||
.filter(isbn -> isbn.length() == 13)
|
||||
.findFirst()
|
||||
.orElse(null));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.adityachandel.booklore.service.metadata.parser.hardcover;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class HardcoverBookDetails {
|
||||
|
||||
private Integer id;
|
||||
private String title;
|
||||
|
||||
@JsonProperty("cached_tags")
|
||||
private Map<String, List<CachedTag>> cachedTags;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CachedTag {
|
||||
private String tag;
|
||||
|
||||
@JsonProperty("tagSlug")
|
||||
private String tagSlug;
|
||||
|
||||
private String category;
|
||||
|
||||
@JsonProperty("categorySlug")
|
||||
private String categorySlug;
|
||||
|
||||
@JsonProperty("spoilerRatio")
|
||||
private Double spoilerRatio;
|
||||
|
||||
private Integer count;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.adityachandel.booklore.service.metadata.parser.hardcover;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.*;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class HardcoverBookDetailsResponse {
|
||||
|
||||
private Data data;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Data {
|
||||
@JsonProperty("books_by_pk")
|
||||
private HardcoverBookDetails booksByPk;
|
||||
}
|
||||
}
|
||||
+103
-23
@@ -7,62 +7,142 @@ import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestClient;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestClientResponseException;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class HardcoverBookSearchService {
|
||||
|
||||
public static final int DEFAULT_PER_PAGE = 10;
|
||||
private static final long INITIAL_DELAY_MS = 1200;
|
||||
private static final long MAX_DELAY_MS = 15000;
|
||||
|
||||
private final RestClient restClient;
|
||||
private final AppSettingService appSettingService;
|
||||
private final AtomicLong requestDelayMs = new AtomicLong(INITIAL_DELAY_MS);
|
||||
private final AtomicLong lastRequestTime = new AtomicLong(0);
|
||||
private final AtomicLong successCount = new AtomicLong(0);
|
||||
|
||||
@Autowired
|
||||
public HardcoverBookSearchService(AppSettingService appSettingService) {
|
||||
this.appSettingService = appSettingService;
|
||||
String apiUrl = "https://api.hardcover.app/v1/graphql";
|
||||
this.restClient = RestClient.builder()
|
||||
.baseUrl(apiUrl)
|
||||
.baseUrl("https://api.hardcover.app/v1/graphql")
|
||||
.build();
|
||||
}
|
||||
|
||||
public List<GraphQLResponse.Hit> searchBooks(String query) {
|
||||
String apiToken = appSettingService.getAppSettings().getMetadataProviderSettings().getHardcover().getApiKey();
|
||||
if (apiToken == null || apiToken.isEmpty()) {
|
||||
log.warn("Hardcover API token not set");
|
||||
return searchBooks(query, DEFAULT_PER_PAGE);
|
||||
}
|
||||
|
||||
public List<GraphQLResponse.Hit> searchBooks(String query, int perPage) {
|
||||
String apiToken = getApiToken();
|
||||
if (apiToken == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
String graphqlQuery = String.format(
|
||||
"query SearchBooks { search(query: \"%s\", query_type: \"Book\", per_page: 5, page: 1) { results } }",
|
||||
query.replace("\"", "\\\"")
|
||||
);
|
||||
int sanitizedPerPage = Math.min(Math.max(perPage, 1), 100);
|
||||
|
||||
GraphQLRequest body = new GraphQLRequest();
|
||||
body.setQuery("query BookSearch($q: String!, $limit: Int!) { search(query: $q, query_type: \"Book\", per_page: $limit, page: 1) { results } }");
|
||||
body.setVariables(java.util.Map.of("q", query, "limit", sanitizedPerPage));
|
||||
|
||||
GraphQLResponse response = executeRequest(body, GraphQLResponse.class, apiToken);
|
||||
if (response == null || response.getData() == null ||
|
||||
response.getData().getSearch() == null ||
|
||||
response.getData().getSearch().getResults() == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
List<GraphQLResponse.Hit> hits = response.getData().getSearch().getResults().getHits();
|
||||
return hits != null ? hits : Collections.emptyList();
|
||||
}
|
||||
|
||||
public HardcoverBookDetails fetchBookDetails(int bookId) {
|
||||
String apiToken = getApiToken();
|
||||
if (apiToken == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
GraphQLRequest body = new GraphQLRequest();
|
||||
body.setQuery(graphqlQuery);
|
||||
body.setVariables(Collections.emptyMap());
|
||||
body.setQuery("query BookDetails($id: Int!) { books_by_pk(id: $id) { id title cached_tags } }");
|
||||
body.setVariables(java.util.Map.of("id", bookId));
|
||||
|
||||
HardcoverBookDetailsResponse response = executeRequest(body, HardcoverBookDetailsResponse.class, apiToken);
|
||||
if (response == null || response.getData() == null) {
|
||||
return null;
|
||||
}
|
||||
return response.getData().getBooksByPk();
|
||||
}
|
||||
|
||||
private <T> T executeRequest(GraphQLRequest body, Class<T> responseType, String apiToken) {
|
||||
enforceRateLimit();
|
||||
|
||||
try {
|
||||
GraphQLResponse response = restClient.post()
|
||||
T response = restClient.post()
|
||||
.uri("")
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.header(HttpHeaders.AUTHORIZATION, "Bearer " + apiToken)
|
||||
.body(body)
|
||||
.retrieve()
|
||||
.body(GraphQLResponse.class);
|
||||
.body(responseType);
|
||||
|
||||
if (response == null || response.getData() == null || response.getData().getSearch() == null || response.getData().getSearch().getResults() == null) {
|
||||
log.warn("Empty or malformed response from Hardcover API");
|
||||
return Collections.emptyList();
|
||||
successCount.incrementAndGet();
|
||||
if (successCount.get() % 5 == 0) {
|
||||
reduceDelay();
|
||||
}
|
||||
return response;
|
||||
|
||||
return response.getData().getSearch().getResults().getHits();
|
||||
|
||||
} catch (RestClientException e) {
|
||||
log.error("Failed to fetch data from Hardcover API, Error: {}", e.getMessage());
|
||||
return Collections.emptyList();
|
||||
} catch (RestClientResponseException e) {
|
||||
successCount.set(0);
|
||||
if (e.getStatusCode().value() == 429 || e.getResponseBodyAsString().contains("Throttled")) {
|
||||
increaseDelay();
|
||||
log.warn("Hardcover API throttled, increased delay to {}ms", requestDelayMs.get());
|
||||
} else {
|
||||
log.error("Hardcover API error: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
log.error("Hardcover API request failed: {}", e.getMessage());
|
||||
return null;
|
||||
} finally {
|
||||
lastRequestTime.set(System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void enforceRateLimit() {
|
||||
long now = System.currentTimeMillis();
|
||||
long last = lastRequestTime.get();
|
||||
long delay = requestDelayMs.get();
|
||||
long elapsed = now - last;
|
||||
|
||||
if (elapsed < delay) {
|
||||
try {
|
||||
Thread.sleep(delay - elapsed);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void increaseDelay() {
|
||||
requestDelayMs.updateAndGet(current -> Math.min(current * 2, MAX_DELAY_MS));
|
||||
}
|
||||
|
||||
private void reduceDelay() {
|
||||
requestDelayMs.updateAndGet(current -> Math.max(current - 100, INITIAL_DELAY_MS));
|
||||
}
|
||||
|
||||
private String getApiToken() {
|
||||
String apiToken = appSettingService.getAppSettings().getMetadataProviderSettings().getHardcover().getApiKey();
|
||||
if (apiToken == null || apiToken.isEmpty()) {
|
||||
log.warn("Hardcover API token not set");
|
||||
return null;
|
||||
}
|
||||
return apiToken;
|
||||
}
|
||||
}
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.adityachandel.booklore.service.metadata.parser.hardcover;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
public class HardcoverMoodFilter {
|
||||
|
||||
|
||||
public static final Set<String> RECOGNIZED_MOODS = Set.of(
|
||||
"adventurous", "challenging", "dark", "emotional", "funny",
|
||||
"hopeful", "informative", "inspiring", "lighthearted", "mysterious",
|
||||
"reflective", "relaxing", "romantic", "sad", "scary", "tense"
|
||||
);
|
||||
|
||||
public static final int MIN_VOTE_COUNT = 3;
|
||||
|
||||
public static final double MIN_VOTE_RATIO = 0.15;
|
||||
|
||||
public static final int MAX_MOODS = 5;
|
||||
|
||||
private HardcoverMoodFilter() {
|
||||
}
|
||||
|
||||
public static Set<String> filterBasicMoods(List<String> moods) {
|
||||
if (moods == null || moods.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
return moods.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::toLowerCase)
|
||||
.map(String::trim)
|
||||
.filter(RECOGNIZED_MOODS::contains)
|
||||
.limit(MAX_MOODS)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
}
|
||||
|
||||
public static Set<String> filterMoodsWithCounts(Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags) {
|
||||
if (cachedTags == null || cachedTags.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
List<HardcoverBookDetails.CachedTag> moodTags = cachedTags.get("Mood");
|
||||
if (moodTags == null || moodTags.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
// Find the maximum vote count
|
||||
int maxCount = moodTags.stream()
|
||||
.filter(tag -> tag.getCount() != null)
|
||||
.mapToInt(HardcoverBookDetails.CachedTag::getCount)
|
||||
.max()
|
||||
.orElse(0);
|
||||
|
||||
if (maxCount == 0) {
|
||||
// No votes at all, just return empty
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
int minCountThreshold = Math.max(MIN_VOTE_COUNT, (int) (maxCount * MIN_VOTE_RATIO));
|
||||
|
||||
List<HardcoverBookDetails.CachedTag> filteredMoods = moodTags.stream()
|
||||
.filter(tag -> tag.getCount() != null && tag.getCount() >= minCountThreshold)
|
||||
.filter(tag -> tag.getTag() != null)
|
||||
.sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed())
|
||||
.limit(MAX_MOODS)
|
||||
.toList();
|
||||
|
||||
log.debug("Filtered moods from {} to {} (max count: {}, threshold: {})",
|
||||
moodTags.size(), filteredMoods.size(), maxCount, minCountThreshold);
|
||||
|
||||
return filteredMoods.stream()
|
||||
.map(HardcoverBookDetails.CachedTag::getTag)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
}
|
||||
|
||||
public static Set<String> filterGenresWithCounts(Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags) {
|
||||
if (cachedTags == null || cachedTags.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
List<HardcoverBookDetails.CachedTag> genreTags = cachedTags.get("Genre");
|
||||
if (genreTags == null || genreTags.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
// For genres, we're more lenient as they're generally more reliable
|
||||
return genreTags.stream()
|
||||
.filter(tag -> tag.getCount() != null && tag.getCount() >= 1)
|
||||
.filter(tag -> tag.getTag() != null)
|
||||
.sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed())
|
||||
.limit(10) // Allow more genres
|
||||
.map(HardcoverBookDetails.CachedTag::getTag)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
}
|
||||
|
||||
public static Set<String> filterTagsWithCounts(Map<String, List<HardcoverBookDetails.CachedTag>> cachedTags) {
|
||||
if (cachedTags == null || cachedTags.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
List<HardcoverBookDetails.CachedTag> tagList = cachedTags.get("Tag");
|
||||
if (tagList == null || tagList.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
// For general tags, use a moderate threshold
|
||||
return tagList.stream()
|
||||
.filter(tag -> tag.getCount() != null && tag.getCount() >= 2)
|
||||
.filter(tag -> tag.getTag() != null)
|
||||
.sorted(Comparator.comparingInt(HardcoverBookDetails.CachedTag::getCount).reversed())
|
||||
.limit(10)
|
||||
.map(HardcoverBookDetails.CachedTag::getTag)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
}
|
||||
|
||||
public static String normalizeMood(String mood) {
|
||||
if (mood == null) {
|
||||
return null;
|
||||
}
|
||||
return mood.toLowerCase().trim();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user