Add ISBN to Metadata Search

This commit is contained in:
aditya.chandel
2025-08-28 23:35:24 -06:00
committed by Aditya Chandel
parent 12b7aaa8e9
commit 4abf5eccaa
9 changed files with 257 additions and 134 deletions
@@ -38,7 +38,12 @@ public class GoogleBooksApiResponse {
@Data
public static class ImageLinks {
private String smallThumbnail;
private String thumbnail;
private String small;
private String medium;
private String large;
private String extraLarge;
}
}
}
}
@@ -32,7 +32,7 @@ import java.util.stream.Collectors;
@AllArgsConstructor
public class AmazonBookParser implements BookParser {
private static final int COUNT_DETAILED_METADATA_TO_GET = 5;
private static final int COUNT_DETAILED_METADATA_TO_GET = 3;
private static final String BASE_BOOK_URL = "https://www.amazon.com/dp/";
private final AppSettingService appSettingService;
@@ -76,7 +76,6 @@ public class AmazonBookParser implements BookParser {
}
private LinkedList<String> getAmazonBookIds(Book book, FetchMetadataRequest request) {
log.info("Amazon: Querying metadata for ISBN: {}, Title: {}, Author: {}, FileName: {}", request.getIsbn(), request.getTitle(), request.getAuthor(), book.getFileName());
String queryUrl = buildQueryUrl(request, book);
if (queryUrl == null) {
log.error("Query URL is null, cannot proceed.");
@@ -194,6 +193,16 @@ public class AmazonBookParser implements BookParser {
}
private String buildQueryUrl(FetchMetadataRequest fetchMetadataRequest, Book book) {
// 1. Prefer ISBN if present
if (fetchMetadataRequest.getIsbn() != null && !fetchMetadataRequest.getIsbn().isEmpty()) {
String url = "https://www.amazon."
+ appSettingService.getAppSettings().getMetadataProviderSettings().getAmazon().getDomain()
+ "/s?k=" + fetchMetadataRequest.getIsbn();
log.info("Amazon Query URL (ISBN): {}", url);
return url;
}
// 2. Otherwise, fall back to title + author + filename
StringBuilder searchTerm = new StringBuilder();
String title = fetchMetadataRequest.getTitle();
@@ -231,8 +240,10 @@ public class AmazonBookParser implements BookParser {
}
String encodedSearchTerm = searchTerm.toString().replace(" ", "+");
String url = "https://www.amazon." + appSettingService.getAppSettings().getMetadataProviderSettings().getAmazon().getDomain() + "/s?k=" + encodedSearchTerm;
log.info("Query URL: {}", url);
String url = "https://www.amazon."
+ appSettingService.getAppSettings().getMetadataProviderSettings().getAmazon().getDomain()
+ "/s?k=" + encodedSearchTerm;
log.info("Amazon Query URL: {}", url);
return url;
}
@@ -37,7 +37,8 @@ public class GoodReadsParser implements BookParser {
private static final String BASE_SEARCH_URL = "https://www.goodreads.com/search?q=";
private static final String BASE_BOOK_URL = "https://www.goodreads.com/book/show/";
private static final int COUNT_DETAILED_METADATA_TO_GET = 5;
private static final String BASE_ISBN_URL = "https://www.goodreads.com/book/isbn/";
private static final int COUNT_DETAILED_METADATA_TO_GET = 3;
private final AppSettingService appSettingService;
@Override
@@ -52,6 +53,25 @@ public class GoodReadsParser implements BookParser {
@Override
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
String isbn = fetchMetadataRequest.getIsbn();
if (isbn != null && !isbn.isBlank()) {
log.info("Goodreads Query URL (ISBN): " + BASE_ISBN_URL + "{}", isbn);
Document doc = fetchDoc(BASE_ISBN_URL + isbn);
String ogUrl = Optional.ofNullable(doc.selectFirst("meta[property=og:url]"))
.map(e -> e.attr("content"))
.orElse(null);
if (ogUrl != null && !ogUrl.isBlank()) {
String goodreadsId = ogUrl.substring(ogUrl.lastIndexOf("/") + 1);
if (!goodreadsId.isBlank()) {
BookMetadata metadata = parseBookDetails(doc, goodreadsId);
if (metadata != null) {
return List.of(metadata);
}
}
}
}
List<BookMetadata> previews = fetchMetadataPreviews(book, fetchMetadataRequest).stream()
.limit(COUNT_DETAILED_METADATA_TO_GET)
.toList();
@@ -387,52 +407,69 @@ public class GoodReadsParser implements BookParser {
public String generateSearchUrl(String searchTerm) {
String encodedSearchTerm = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8);
return BASE_SEARCH_URL + encodedSearchTerm;
String url = BASE_SEARCH_URL + encodedSearchTerm;
log.info("Goodreads Query URL: {}", url);
return url;
}
public List<BookMetadata> fetchMetadataPreviews(Book book, FetchMetadataRequest request) {
String searchTerm = getSearchTerm(book, request);
if (searchTerm != null) {
log.info("GoodReads: Fetching metadata previews for: {}", searchTerm);
try {
String searchUrl = generateSearchUrl(searchTerm);
Elements previewBooks = fetchDoc(searchUrl).select("table.tableList").first().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) {
Set<String> authors = extractAuthorsPreview(previewBook);
if (queryAuthor != null && !queryAuthor.isBlank()) {
List<String> queryAuthorTokens = List.of(queryAuthor.toLowerCase().split("\\s+"));
boolean matches = authors.stream().flatMap(a -> Arrays.stream(a.toLowerCase().split("\\s+"))).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;
}
if (searchTerm == null || searchTerm.isEmpty()) {
log.info("GoodReads: No metadata previews found (no ISBN, title, or filename).");
return Collections.emptyList();
}
try {
String searchUrl = generateSearchUrl(searchTerm);
Elements previewBooks = fetchDoc(searchUrl)
.select("table.tableList")
.first()
.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) {
Set<String> authors = extractAuthorsPreview(previewBook);
// Author fuzzy match if author provided
if (queryAuthor != null && !queryAuthor.isBlank()) {
List<String> queryAuthorTokens = List.of(queryAuthor.toLowerCase().split("\\s+"));
boolean matches = authors.stream()
.flatMap(a -> Arrays.stream(a.toLowerCase().split("\\s+")))
.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)
.build();
metadataPreviews.add(previewMetadata);
}
Thread.sleep(Duration.ofSeconds(1));
return metadataPreviews;
} catch (Exception e) {
log.error("Error fetching metadata previews: {}", e.getMessage());
return Collections.emptyList();
BookMetadata previewMetadata = BookMetadata.builder()
.goodreadsId(String.valueOf(extractGoodReadsIdPreview(previewBook)))
.title(extractTitlePreview(previewBook))
.authors(authors)
.build();
metadataPreviews.add(previewMetadata);
}
Thread.sleep(Duration.ofSeconds(1));
return metadataPreviews;
} catch (Exception e) {
log.error("Error fetching metadata previews: {}", e.getMessage());
return Collections.emptyList();
}
log.info("GoodReads: No metadata previews found for title '{}'!", request.getTitle());
return Collections.emptyList();
}
private String getSearchTerm(Book book, FetchMetadataRequest request) {
@@ -41,18 +41,55 @@ public class GoogleParser implements BookParser {
@Override
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
// 1. If ISBN exists, prioritize it
if (fetchMetadataRequest.getIsbn() != null && !fetchMetadataRequest.getIsbn().isBlank()) {
return getMetadataListByIsbn(fetchMetadataRequest.getIsbn());
}
// 2. Otherwise fallback to existing title/author search
String searchTerm = getSearchTerm(book, fetchMetadataRequest);
return searchTerm != null ? getMetadataListByTerm(searchTerm) : List.of();
}
private List<BookMetadata> getMetadataListByIsbn(String isbn) {
try {
URI uri = UriComponentsBuilder.fromUriString(GOOGLE_BOOKS_API_URL)
.queryParam("q", "isbn:" + isbn.replace("-", ""))
.build()
.toUri();
log.info("Google Books API URL (ISBN): {}", uri);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return parseGoogleBooksApiResponse(response.body());
} else {
log.error("Failed to fetch metadata from Google Books API with ISBN. Status: {}, Response: {}",
response.statusCode(), response.body());
return List.of();
}
} catch (IOException | InterruptedException e) {
log.error("Error occurred while fetching metadata from Google Books API with ISBN", e);
return List.of();
}
}
public List<BookMetadata> getMetadataListByTerm(String term) {
log.info("Google Books: Fetching metadata for: {}", term);
try {
URI uri = UriComponentsBuilder.fromUriString(GOOGLE_BOOKS_API_URL)
.queryParam("q", term)
.build()
.toUri();
log.info("Google Books API URLx: {}", uri);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
@@ -87,6 +124,17 @@ public class GoogleParser implements BookParser {
GoogleBooksApiResponse.Item.VolumeInfo volumeInfo = item.getVolumeInfo();
Map<String, String> isbns = extractISBNs(volumeInfo.getIndustryIdentifiers());
String highResCover = Optional.ofNullable(volumeInfo.getImageLinks())
.map(links -> {
if (links.getExtraLarge() != null) return links.getExtraLarge();
if (links.getLarge() != null) return links.getLarge();
if (links.getMedium() != null) return links.getMedium();
if (links.getSmall() != null) return links.getSmall();
if (links.getThumbnail() != null) return links.getThumbnail();
return links.getSmallThumbnail();
})
.orElse(null);
return BookMetadata.builder()
.provider(MetadataProvider.Google)
.googleId(item.getId())
@@ -100,9 +148,7 @@ public class GoogleParser implements BookParser {
.isbn13(isbns.get("ISBN_13"))
.isbn10(isbns.get("ISBN_10"))
.pageCount(volumeInfo.getPageCount())
.thumbnailUrl(Optional.ofNullable(volumeInfo.getImageLinks())
.map(GoogleBooksApiResponse.Item.ImageLinks::getThumbnail)
.orElse(null))
.thumbnailUrl(highResCover)
.language(volumeInfo.getLanguage())
.build();
}
@@ -10,6 +10,7 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.apache.commons.text.similarity.FuzzyScore;
import java.util.Locale;
import java.math.BigDecimal;
@@ -26,11 +27,20 @@ public class HardcoverParser implements BookParser {
@Override
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
log.info("Hardcover: Fetching metadata for book {}", fetchMetadataRequest.getTitle());
List<GraphQLResponse.Hit> hits = hardcoverBookSearchService.searchBooks(fetchMetadataRequest.getTitle());
boolean searchByIsbn = fetchMetadataRequest.getIsbn() != null && !fetchMetadataRequest.getIsbn().isBlank();
List<GraphQLResponse.Hit> hits;
if (searchByIsbn) {
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());
}
if (hits == null || hits.isEmpty()) {
log.info("Hardcover: No results found for title '{}'", fetchMetadataRequest.getTitle());
log.info("Hardcover: No results found for {}", searchByIsbn ? "ISBN " + fetchMetadataRequest.getIsbn() : "title " + fetchMetadataRequest.getTitle());
return List.of();
}
@@ -39,11 +49,13 @@ public class HardcoverParser implements BookParser {
return hits.stream()
.filter(hit -> {
if (searchAuthor.isBlank()) return true;
if (searchByIsbn || searchAuthor.isBlank()) return true;
List<String> actualAuthorTokens = hit.getDocument().getAuthorNames().stream()
.flatMap(name -> List.of(name.toLowerCase().split("\\s+")).stream())
.toList();
List<String> searchAuthorTokens = List.of(searchAuthor.toLowerCase().split("\\s+"));
for (String actual : actualAuthorTokens) {
for (String query : searchAuthorTokens) {
int score = fuzzyScore.fuzzyScore(actual, query);
@@ -54,53 +66,45 @@ public class HardcoverParser implements BookParser {
}
return false;
})
.map(hit -> {
GraphQLResponse.Document doc = hit.getDocument();
BookMetadata metadata = new BookMetadata();
metadata.setHardcoverId(doc.getSlug());
metadata.setTitle(doc.getTitle());
metadata.setDescription(doc.getDescription());
metadata.setAuthors(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) {
.map(hit -> {
GraphQLResponse.Document doc = hit.getDocument();
BookMetadata metadata = new BookMetadata();
metadata.setHardcoverId(doc.getSlug());
metadata.setTitle(doc.getTitle());
metadata.setDescription(doc.getDescription());
metadata.setAuthors(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) {
BigDecimal roundedRating = BigDecimal.valueOf(doc.getRating()).setScale(2, RoundingMode.HALF_UP);
metadata.setHardcoverRating(roundedRating.doubleValue());
}
metadata.setHardcoverReviewCount(doc.getRatingsCount());
metadata.setPageCount(doc.getPages());
metadata.setPublishedDate(doc.getReleaseDate() != null ? LocalDate.parse(doc.getReleaseDate()) : null);
metadata.setCategories(doc.getGenres());
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);
metadata.setCategories(doc.getGenres());
if (doc.getIsbns() != null) {
metadata.setIsbn10(doc.getIsbns().stream()
.filter(isbn -> isbn.length() == 10)
.findFirst()
.orElse(null));
if (doc.getIsbns() != null) {
metadata.setIsbn10(doc.getIsbns().stream().filter(isbn -> isbn.length() == 10).findFirst().orElse(null));
metadata.setIsbn13(doc.getIsbns().stream().filter(isbn -> isbn.length() == 13).findFirst().orElse(null));
}
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;
}).toList();
metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null);
metadata.setProvider(MetadataProvider.Hardcover);
return metadata;
})
.toList();
}
@Override
@@ -9,44 +9,55 @@
} @else {
<form class="flex flex-col w-full h-full pt-2 min-w-full md:min-w-[60rem] pr-0 md:pr-2 pl-0 md:pl-2" [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="grid grid-cols-1 md:flex md:flex-row w-full gap-2 md:gap-4 md:items-end">
<div class="flex flex-col space-y-3">
<div class="grid grid-cols-1 md:flex md:flex-row w-full gap-2 md:gap-4 md:items-end">
<div class="flex flex-col gap-1 w-full max-w-full md:w-1/3">
<label for="provider">Providers</label>
<p-multiselect
id="provider"
class="w-full"
[filter]="false"
showToggleAll="false"
[options]="providers"
formControlName="provider"
placeholder="Select Providers">
</p-multiselect>
</div>
<div class="flex flex-col gap-1 w-full max-w-full md:w-3/12">
<label for="provider">Providers</label>
<p-multiselect
id="provider"
class="w-full"
[filter]="false"
showToggleAll="false"
[options]="providers"
formControlName="provider"
placeholder="Select Providers">
</p-multiselect>
</div>
<div class="flex flex-col gap-1 w-full max-w-full md:w-56">
<label for="isbn">ISBN</label>
<input pInputText formControlName="isbn" id="isbn" class="w-full" placeholder="ISBN-10 or ISBN-13"/>
</div>
<div class="flex flex-col gap-1 w-full max-w-full md:w-5/12">
<label for="title">Title</label>
<input pInputText formControlName="title" id="title" class="w-full"/>
</div>
<div class="flex flex-col gap-1 w-full max-w-full md:w-1/3">
<label for="title">Title</label>
<input pInputText formControlName="title" id="title" class="w-full"/>
</div>
<div class="flex flex-col gap-1 w-full max-w-full md:w-4/12">
<label for="author">Author</label>
<input pInputText formControlName="author" id="author" class="w-full"/>
</div>
<div class="flex flex-col gap-1 w-full max-w-full md:w-1/3">
<label for="author">Author</label>
<input pInputText formControlName="author" id="author" class="w-full"/>
</div>
<div class="flex flex-col gap-1 w-full sm:w-fit md:w-auto">
<label class="invisible md:visible h-0 md:h-auto">Search</label>
<div class="flex justify-center md:justify-start">
<p-button
label="Search"
type="submit"
outlined="true"
[disabled]="!isSearchEnabled || loading"
class="w-full sm:w-fit md:w-auto">
</p-button>
<div class="flex flex-col gap-1 w-full sm:w-fit md:w-auto">
<label class="invisible md:visible h-0 md:h-auto">Search</label>
<div class="flex justify-center md:justify-start">
<p-button
label="Search"
type="submit"
outlined="true"
[disabled]="!isSearchEnabled || loading"
class="w-full sm:w-fit md:w-auto">
</p-button>
</div>
</div>
</div>
<div class="text-sm text-gray-400 flex items-start gap-2">
<i class="pi pi-info-circle text-sky-600 mt-0.5"></i>
<span>
When an ISBN is provided, the search will use only the ISBN. If no ISBN is given, the search will fall back to Title and Author.
</span>
</div>
</div>
@if (loading) {
@@ -80,8 +91,12 @@
<div class="flex flex-col md:flex-row gap-2 md:gap-4 justify-between">
<p class="font-bold">{{ truncateText(metadata['title']!, 90) }}</p>
<div class="flex flex-wrap gap-2 text-sm">
@if (metadata['isbn10'] || metadata['asin']) {
<p>ISBN: {{ metadata['isbn10'] || metadata['asin'] }}</p>
@if (metadata['isbn10']) {
<p>ISBN10: {{ metadata['isbn10']}}</p>
<span class="hidden md:inline">|</span>
}
@if (metadata['isbn13']) {
<p>ISBN13: {{ metadata['isbn13']}}</p>
<span class="hidden md:inline">|</span>
}
<p>Published: {{ metadata['publishedDate'] }}</p>
@@ -60,7 +60,8 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
this.form = this.formBuilder.group({
provider: null,
title: [''],
author: ['']
author: [''],
isbn: ['']
});
}
@@ -105,7 +106,8 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
this.form.patchValue({
provider: this.providers,
title: book.metadata?.title ?? '',
author: book.metadata?.authors?.[0] ?? ''
author: book.metadata?.authors?.[0] ?? '',
isbn: book.metadata?.isbn10 ?? book.metadata?.isbn13 ?? ''
});
}
@@ -118,7 +120,8 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
get isSearchEnabled(): boolean {
const providerSelected = !!this.form.get('provider')?.value;
const title = this.form.get('title')?.value;
return providerSelected && title;
const isbn = this.form.get('isbn')?.value;
return providerSelected && (title || isbn);
}
onSubmit(): void {
@@ -131,7 +134,8 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy {
bookId: this.bookId,
providers: providerKeys,
title: this.form.get('title')?.value,
author: this.form.get('author')?.value
author: this.form.get('author')?.value,
isbn: this.form.get('isbn')?.value
};
this.loading = true;
@@ -2,5 +2,6 @@ export interface FetchMetadataRequest {
bookId: number,
providers: string[],
title: string,
author: string
author: string,
isbn: string
}
@@ -11,8 +11,8 @@
<div class="text-sm text-gray-400 flex items-start gap-2">
<i class="pi pi-exclamation-triangle text-yellow-500 mt-0.5"></i>
<span>
Automatically downloads metadata from your configured sources (Amazon, Goodreads, etc.) when files are added to the Bookdrop folder. Use with caution if adding many files at once as metadata fetching can take time.
</span>
Automatically downloads metadata from your configured sources (Amazon, Goodreads, etc.) when files are added to the Bookdrop folder. Use with caution if adding many files at once as metadata fetching can take time.
</span>
</div>
</div>
</div>