Merge branch 'develop' of github.com-personal:adityachandelgit/BookLore into develop
This commit is contained in:
+2
-2
@@ -72,8 +72,8 @@ public class MetadataController {
|
|||||||
.updateThumbnail(true)
|
.updateThumbnail(true)
|
||||||
.mergeCategories(mergeCategories)
|
.mergeCategories(mergeCategories)
|
||||||
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||||
.mergeMoods(true)
|
.mergeMoods(false)
|
||||||
.mergeTags(true)
|
.mergeTags(false)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
bookMetadataUpdater.setBookMetadata(context);
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
|
|||||||
+178
-42
@@ -38,10 +38,11 @@ public class AmazonBookParser implements BookParser {
|
|||||||
private static final Pattern SERIES_FORMAT_PATTERN = Pattern.compile("Book \\d+ of \\d+");
|
private static final Pattern SERIES_FORMAT_PATTERN = Pattern.compile("Book \\d+ of \\d+");
|
||||||
private static final Pattern SERIES_FORMAT_WITH_DECIMAL_PATTERN = Pattern.compile("Book \\d+(\\.\\d+)? of \\d+");
|
private static final Pattern SERIES_FORMAT_WITH_DECIMAL_PATTERN = Pattern.compile("Book \\d+(\\.\\d+)? of \\d+");
|
||||||
private static final Pattern PARENTHESES_WITH_WHITESPACE_PATTERN = Pattern.compile("\\s*\\(.*?\\)");
|
private static final Pattern PARENTHESES_WITH_WHITESPACE_PATTERN = Pattern.compile("\\s*\\(.*?\\)");
|
||||||
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-zA-Z0-9]");
|
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^\\p{L}\\p{M}0-9]");
|
||||||
private static final Pattern DP_SEPARATOR_PATTERN = Pattern.compile("/dp/");
|
private static final Pattern DP_SEPARATOR_PATTERN = Pattern.compile("/dp/");
|
||||||
// Pattern to extract country and date from strings like "Reviewed in ... on ..."
|
// Pattern to extract country and date from strings like "Reviewed in ... on ..." or Japanese format
|
||||||
private static final Pattern REVIEWED_IN_ON_PATTERN = Pattern.compile("Reviewed in (.+?) on (.+)");
|
private static final Pattern REVIEWED_IN_ON_PATTERN = Pattern.compile("(?i)(?:Reviewed in|Rezension aus|Beoordeeld in|Recensie uit|Commenté en|Recensito in|Revisado en)\\s+(.+?)\\s+(?:on|vom|op|le|il|el)\\s+(.+)");
|
||||||
|
private static final Pattern JAPANESE_REVIEW_DATE_PATTERN = Pattern.compile("(\\d{4}年\\d{1,2}月\\d{1,2}日).+");
|
||||||
|
|
||||||
private static final Map<String, LocaleInfo> DOMAIN_LOCALE_MAP = Map.ofEntries(
|
private static final Map<String, LocaleInfo> DOMAIN_LOCALE_MAP = Map.ofEntries(
|
||||||
Map.entry("com", new LocaleInfo("en-US,en;q=0.9", Locale.US)),
|
Map.entry("com", new LocaleInfo("en-US,en;q=0.9", Locale.US)),
|
||||||
@@ -58,7 +59,14 @@ public class AmazonBookParser implements BookParser {
|
|||||||
Map.entry("com.mx", new LocaleInfo("en-US,en;q=0.9,es;q=0.8", new Locale.Builder().setLanguage("es").setRegion("MX").build())),
|
Map.entry("com.mx", new LocaleInfo("en-US,en;q=0.9,es;q=0.8", new Locale.Builder().setLanguage("es").setRegion("MX").build())),
|
||||||
Map.entry("nl", new LocaleInfo("en-GB,en;q=0.9,nl;q=0.8", new Locale.Builder().setLanguage("nl").setRegion("NL").build())),
|
Map.entry("nl", new LocaleInfo("en-GB,en;q=0.9,nl;q=0.8", new Locale.Builder().setLanguage("nl").setRegion("NL").build())),
|
||||||
Map.entry("se", new LocaleInfo("en-GB,en;q=0.9,sv;q=0.8", new Locale.Builder().setLanguage("sv").setRegion("SE").build())),
|
Map.entry("se", new LocaleInfo("en-GB,en;q=0.9,sv;q=0.8", new Locale.Builder().setLanguage("sv").setRegion("SE").build())),
|
||||||
Map.entry("pl", new LocaleInfo("en-GB,en;q=0.9,pl;q=0.8", new Locale.Builder().setLanguage("pl").setRegion("PL").build()))
|
Map.entry("pl", new LocaleInfo("en-GB,en;q=0.9,pl;q=0.8", new Locale.Builder().setLanguage("pl").setRegion("PL").build())),
|
||||||
|
Map.entry("ae", new LocaleInfo("en-US,en;q=0.9,ar;q=0.8", new Locale.Builder().setLanguage("en").setRegion("AE").build())),
|
||||||
|
Map.entry("sa", new LocaleInfo("en-US,en;q=0.9,ar;q=0.8", new Locale.Builder().setLanguage("en").setRegion("SA").build())),
|
||||||
|
Map.entry("cn", new LocaleInfo("zh-CN,zh;q=0.9", Locale.CHINA)),
|
||||||
|
Map.entry("sg", new LocaleInfo("en-GB,en;q=0.9", new Locale.Builder().setLanguage("en").setRegion("SG").build())),
|
||||||
|
Map.entry("tr", new LocaleInfo("en-GB,en;q=0.9,tr;q=0.8", new Locale.Builder().setLanguage("tr").setRegion("TR").build())),
|
||||||
|
Map.entry("eg", new LocaleInfo("en-US,en;q=0.9,ar;q=0.8", new Locale.Builder().setLanguage("en").setRegion("EG").build())),
|
||||||
|
Map.entry("com.be", new LocaleInfo("en-GB,en;q=0.9,fr;q=0.8,nl;q=0.8", new Locale.Builder().setLanguage("fr").setRegion("BE").build()))
|
||||||
);
|
);
|
||||||
|
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
@@ -281,56 +289,104 @@ public class AmazonBookParser implements BookParser {
|
|||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getTitle(Document doc) {
|
private String getTextBySelectors(Document doc, String... selectors) {
|
||||||
Element titleElement = doc.getElementById("productTitle");
|
for (String selector : selectors) {
|
||||||
if (titleElement != null) {
|
try {
|
||||||
String fullTitle = titleElement.text();
|
Element element = doc.selectFirst(selector);
|
||||||
return fullTitle.split(":", 2)[0].trim();
|
if (element != null && !element.text().isBlank()) {
|
||||||
|
return element.text().trim();
|
||||||
}
|
}
|
||||||
log.warn("Failed to parse title: Element not found.");
|
} catch (Exception e) {
|
||||||
|
log.debug("Failed to extract text with selector '{}': {}", selector, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getTitle(Document doc) {
|
||||||
|
String title = getTextBySelectors(doc,
|
||||||
|
"#productTitle",
|
||||||
|
"#ebooksProductTitle",
|
||||||
|
"h1#title",
|
||||||
|
"span#productTitle"
|
||||||
|
);
|
||||||
|
if (title != null) {
|
||||||
|
return title.split(":", 2)[0].trim();
|
||||||
|
}
|
||||||
|
log.warn("Failed to parse title: No suitable element found.");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getSubtitle(Document doc) {
|
private String getSubtitle(Document doc) {
|
||||||
Element titleElement = doc.getElementById("productTitle");
|
String title = getTextBySelectors(doc,
|
||||||
if (titleElement != null) {
|
"#productTitle",
|
||||||
String fullTitle = titleElement.text();
|
"#ebooksProductTitle",
|
||||||
String[] parts = fullTitle.split(":", 2);
|
"h1#title",
|
||||||
|
"span#productTitle"
|
||||||
|
);
|
||||||
|
if (title != null) {
|
||||||
|
String[] parts = title.split(":", 2);
|
||||||
if (parts.length > 1) {
|
if (parts.length > 1) {
|
||||||
return parts[1].trim();
|
return parts[1].trim();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
log.warn("Failed to parse subtitle: No suitable element found.");
|
||||||
log.warn("Failed to parse subtitle: Element not found.");
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Set<String> getAuthors(Document doc) {
|
private Set<String> getAuthors(Document doc) {
|
||||||
|
Set<String> authors = new HashSet<>();
|
||||||
try {
|
try {
|
||||||
Element bylineDiv = doc.select("#bylineInfo_feature_div").first();
|
// Primary strategy: #bylineInfo_feature_div .author a
|
||||||
|
Element bylineDiv = doc.selectFirst("#bylineInfo_feature_div");
|
||||||
if (bylineDiv != null) {
|
if (bylineDiv != null) {
|
||||||
return bylineDiv
|
authors.addAll(bylineDiv.select(".author a").stream().map(Element::text).collect(Collectors.toSet()));
|
||||||
.select(".author a")
|
}
|
||||||
.stream()
|
|
||||||
.map(Element::text)
|
// Fallback: #bylineInfo .author a
|
||||||
.collect(Collectors.toSet());
|
if (authors.isEmpty()) {
|
||||||
|
Element bylineInfo = doc.selectFirst("#bylineInfo");
|
||||||
|
if (bylineInfo != null) {
|
||||||
|
authors.addAll(bylineInfo.select(".author a").stream().map(Element::text).collect(Collectors.toSet()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: simple .author a check (broadest)
|
||||||
|
if (authors.isEmpty()) {
|
||||||
|
authors.addAll(doc.select(".author a").stream().map(Element::text).collect(Collectors.toSet()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (authors.isEmpty()) {
|
||||||
|
log.warn("Failed to parse authors: No author elements found.");
|
||||||
}
|
}
|
||||||
log.warn("Failed to parse authors: Byline element not found.");
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to parse authors: {}", e.getMessage());
|
log.warn("Failed to parse authors: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return Set.of();
|
return authors;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getDescription(Document doc) {
|
private String getDescription(Document doc) {
|
||||||
try {
|
try {
|
||||||
|
// Primary: data-a-expander-name
|
||||||
Elements descriptionElements = doc.select("[data-a-expander-name=book_description_expander] .a-expander-content");
|
Elements descriptionElements = doc.select("[data-a-expander-name=book_description_expander] .a-expander-content");
|
||||||
if (!descriptionElements.isEmpty()) {
|
if (!descriptionElements.isEmpty()) {
|
||||||
String html = descriptionElements.getFirst().html();
|
String html = descriptionElements.getFirst().html();
|
||||||
html = html.replace("\n", "<br>");
|
html = html.replace("\n", "<br>");
|
||||||
return html;
|
return html;
|
||||||
}
|
}
|
||||||
return null;
|
|
||||||
|
// Fallback: #bookDescription_feature_div noscript (often contains the clean HTML)
|
||||||
|
Element noscriptDesc = doc.selectFirst("#bookDescription_feature_div noscript");
|
||||||
|
if (noscriptDesc != null) {
|
||||||
|
return noscriptDesc.html(); // usually clean HTML inside noscript
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: div.product-description
|
||||||
|
Element simpleDesc = doc.selectFirst("div.product-description");
|
||||||
|
if (simpleDesc != null) {
|
||||||
|
return simpleDesc.html();
|
||||||
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to parse description: {}", e.getMessage());
|
log.warn("Failed to parse description: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
@@ -338,29 +394,41 @@ public class AmazonBookParser implements BookParser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String getIsbn10(Document doc) {
|
private String getIsbn10(Document doc) {
|
||||||
|
// Strategy 1: RPI attribute
|
||||||
try {
|
try {
|
||||||
Element isbn10Element = doc.select("#rpi-attribute-book_details-isbn10 .rpi-attribute-value span").first();
|
Element isbn10Element = doc.select("#rpi-attribute-book_details-isbn10 .rpi-attribute-value span").first();
|
||||||
if (isbn10Element != null) {
|
if (isbn10Element != null) {
|
||||||
String rawIsbn = isbn10Element.text();
|
return ParserUtils.cleanIsbn(isbn10Element.text());
|
||||||
return ParserUtils.cleanIsbn(rawIsbn);
|
|
||||||
}
|
}
|
||||||
log.warn("Failed to parse isbn10: Element not found.");
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to parse isbn10: {}", e.getMessage());
|
log.debug("RPI ISBN-10 extraction failed: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy 2: Detail bullets
|
||||||
|
try {
|
||||||
|
return extractFromDetailBullets(doc, "ISBN-10");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("DetailBullets ISBN-10 extraction failed: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getIsbn13(Document doc) {
|
private String getIsbn13(Document doc) {
|
||||||
|
// Strategy 1: RPI attribute
|
||||||
try {
|
try {
|
||||||
Element isbn13Element = doc.select("#rpi-attribute-book_details-isbn13 .rpi-attribute-value span").first();
|
Element isbn13Element = doc.select("#rpi-attribute-book_details-isbn13 .rpi-attribute-value span").first();
|
||||||
if (isbn13Element != null) {
|
if (isbn13Element != null) {
|
||||||
String rawIsbn = isbn13Element.text();
|
return ParserUtils.cleanIsbn(isbn13Element.text());
|
||||||
return ParserUtils.cleanIsbn(rawIsbn);
|
|
||||||
}
|
}
|
||||||
log.warn("Failed to parse isbn13: Element not found.");
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to parse isbn13: {}", e.getMessage());
|
log.debug("RPI ISBN-13 extraction failed: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy 2: Detail bullets
|
||||||
|
try {
|
||||||
|
return extractFromDetailBullets(doc, "ISBN-13");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("DetailBullets ISBN-13 extraction failed: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -372,7 +440,19 @@ public class AmazonBookParser implements BookParser {
|
|||||||
Elements listItems = featureElement.select("li");
|
Elements listItems = featureElement.select("li");
|
||||||
for (Element listItem : listItems) {
|
for (Element listItem : listItems) {
|
||||||
Element boldText = listItem.selectFirst("span.a-text-bold");
|
Element boldText = listItem.selectFirst("span.a-text-bold");
|
||||||
if (boldText != null && boldText.text().contains("Publisher")) {
|
if (boldText != null) {
|
||||||
|
String header = boldText.text().toLowerCase();
|
||||||
|
// Check against known localized "Publisher" labels
|
||||||
|
if (header.contains("publisher") ||
|
||||||
|
header.contains("herausgeber") ||
|
||||||
|
header.contains("éditeur") ||
|
||||||
|
header.contains("editoriale") ||
|
||||||
|
header.contains("editorial") ||
|
||||||
|
header.contains("uitgever") ||
|
||||||
|
header.contains("wydawca") ||
|
||||||
|
header.contains("出版社") || // Japanese
|
||||||
|
header.contains("editora")) {
|
||||||
|
|
||||||
Element publisherSpan = boldText.nextElementSibling();
|
Element publisherSpan = boldText.nextElementSibling();
|
||||||
if (publisherSpan != null) {
|
if (publisherSpan != null) {
|
||||||
String fullPublisher = publisherSpan.text().trim();
|
String fullPublisher = publisherSpan.text().trim();
|
||||||
@@ -380,8 +460,9 @@ public class AmazonBookParser implements BookParser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
log.warn("Failed to parse publisher: Element 'detailBullets_feature_div' not found.");
|
log.debug("Failed to parse publisher: Element 'detailBullets_feature_div' not found.");
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to parse publisher: {}", e.getMessage());
|
log.warn("Failed to parse publisher: {}", e.getMessage());
|
||||||
@@ -390,19 +471,63 @@ public class AmazonBookParser implements BookParser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private LocalDate getPublicationDate(Document doc) {
|
private LocalDate getPublicationDate(Document doc) {
|
||||||
|
// Strategy 1: RPI attribute
|
||||||
try {
|
try {
|
||||||
Element publicationDateElement = doc.select("#rpi-attribute-book_details-publication_date .rpi-attribute-value span").first();
|
Element publicationDateElement = doc.select("#rpi-attribute-book_details-publication_date .rpi-attribute-value span").first();
|
||||||
if (publicationDateElement != null) {
|
if (publicationDateElement != null) {
|
||||||
String dateText = publicationDateElement.text();
|
String dateText = publicationDateElement.text();
|
||||||
LocalDate parsedDate = parseAmazonDate(dateText);
|
LocalDate parsedDate = parseAmazonDate(dateText);
|
||||||
if (parsedDate == null) {
|
if (parsedDate != null) return parsedDate;
|
||||||
log.warn("Failed to parse publication date: '{}', returning null", dateText);
|
|
||||||
}
|
}
|
||||||
return parsedDate;
|
|
||||||
}
|
|
||||||
log.warn("Failed to parse publishedDate: Element not found.");
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to parse publishedDate: {}", e.getMessage());
|
log.debug("RPI Publication Date extraction failed: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strategy 2: Detail bullets (look for specific date patterns in values)
|
||||||
|
try {
|
||||||
|
Element featureElement = doc.getElementById("detailBullets_feature_div");
|
||||||
|
if (featureElement != null) {
|
||||||
|
Elements listItems = featureElement.select("li");
|
||||||
|
for (Element listItem : listItems) {
|
||||||
|
// We look for any value that parses as a date, as the label varies wildly ("Publication date", "Seitenzahl"?? no, "Erscheinungsdatum", etc.)
|
||||||
|
// But usually it's associated with "Publisher" line sometimes: "Publisher: XYZ (Jan 1, 2020)"
|
||||||
|
Element boldText = listItem.selectFirst("span.a-text-bold");
|
||||||
|
Element valueSpan = boldText != null ? boldText.nextElementSibling() : null;
|
||||||
|
|
||||||
|
if (valueSpan != null) {
|
||||||
|
// Sometimes date is inside the value span, e.g. "January 1, 2020"
|
||||||
|
LocalDate d = parseAmazonDate(valueSpan.text());
|
||||||
|
if (d != null) return d;
|
||||||
|
|
||||||
|
// Sometimes it's in parentheses after publisher: "Publisher: Name (January 1, 2020)"
|
||||||
|
Matcher matcher = Pattern.compile("\\((.*?)\\)").matcher(valueSpan.text());
|
||||||
|
while (matcher.find()) {
|
||||||
|
LocalDate pd = parseAmazonDate(matcher.group(1));
|
||||||
|
if (pd != null) return pd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("DetailBullets Publication Date extraction failed: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String extractFromDetailBullets(Document doc, String keyPart) {
|
||||||
|
Element featureElement = doc.getElementById("detailBullets_feature_div");
|
||||||
|
if (featureElement != null) {
|
||||||
|
Elements listItems = featureElement.select("li");
|
||||||
|
for (Element listItem : listItems) {
|
||||||
|
Element boldText = listItem.selectFirst("span.a-text-bold");
|
||||||
|
if (boldText != null && boldText.text().contains(keyPart)) {
|
||||||
|
Element valueSpan = boldText.nextElementSibling();
|
||||||
|
if (valueSpan != null) {
|
||||||
|
return ParserUtils.cleanIsbn(valueSpan.text());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -568,6 +693,13 @@ public class AmazonBookParser implements BookParser {
|
|||||||
country = country.substring(4).trim();
|
country = country.substring(4).trim();
|
||||||
}
|
}
|
||||||
datePart = matcher.group(2).trim();
|
datePart = matcher.group(2).trim();
|
||||||
|
} else {
|
||||||
|
// Try Japanese format
|
||||||
|
Matcher japaneseMatcher = JAPANESE_REVIEW_DATE_PATTERN.matcher(fullDateText);
|
||||||
|
if (japaneseMatcher.find()) {
|
||||||
|
datePart = japaneseMatcher.group(1);
|
||||||
|
country = "日本";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
LocalDate localDate = parseReviewDate(datePart, localeInfo);
|
LocalDate localDate = parseReviewDate(datePart, localeInfo);
|
||||||
@@ -735,7 +867,11 @@ public class AmazonBookParser implements BookParser {
|
|||||||
"MMM. d, yyyy",
|
"MMM. d, yyyy",
|
||||||
"d MMM yyyy",
|
"d MMM yyyy",
|
||||||
"d MMM. yyyy",
|
"d MMM. yyyy",
|
||||||
"d. MMM yyyy"
|
"d. MMM yyyy",
|
||||||
|
// Japanese date patterns
|
||||||
|
"yyyy/M/d",
|
||||||
|
"yyyy/MM/dd",
|
||||||
|
"yyyy年M月d日"
|
||||||
};
|
};
|
||||||
|
|
||||||
for (String pattern : patterns) {
|
for (String pattern : patterns) {
|
||||||
|
|||||||
+73
@@ -0,0 +1,73 @@
|
|||||||
|
package com.adityachandel.booklore.controller;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||||
|
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||||
|
import com.adityachandel.booklore.model.MetadataUpdateContext;
|
||||||
|
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
|
||||||
|
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||||
|
import com.adityachandel.booklore.repository.BookRepository;
|
||||||
|
import com.adityachandel.booklore.service.metadata.*;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class MetadataControllerTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private BookMetadataService bookMetadataService;
|
||||||
|
@Mock
|
||||||
|
private BookMetadataUpdater bookMetadataUpdater;
|
||||||
|
@Mock
|
||||||
|
private AuthenticationService authenticationService;
|
||||||
|
@Mock
|
||||||
|
private BookMetadataMapper bookMetadataMapper;
|
||||||
|
@Mock
|
||||||
|
private MetadataMatchService metadataMatchService;
|
||||||
|
@Mock
|
||||||
|
private DuckDuckGoCoverService duckDuckGoCoverService;
|
||||||
|
@Mock
|
||||||
|
private BookRepository bookRepository;
|
||||||
|
@Mock
|
||||||
|
private MetadataManagementService metadataManagementService;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private MetadataController metadataController;
|
||||||
|
|
||||||
|
private MetadataUpdateContext captureContextFromUpdate() {
|
||||||
|
long bookId = 1L;
|
||||||
|
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder().build();
|
||||||
|
BookEntity bookEntity = new BookEntity();
|
||||||
|
bookEntity.setId(bookId);
|
||||||
|
bookEntity.setMetadata(new BookMetadataEntity());
|
||||||
|
|
||||||
|
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
|
||||||
|
when(bookMetadataMapper.toBookMetadata(any(), anyBoolean())).thenReturn(new BookMetadata());
|
||||||
|
|
||||||
|
metadataController.updateMetadata(wrapper, bookId, true);
|
||||||
|
|
||||||
|
ArgumentCaptor<MetadataUpdateContext> captor = ArgumentCaptor.forClass(MetadataUpdateContext.class);
|
||||||
|
verify(bookMetadataUpdater).setBookMetadata(captor.capture());
|
||||||
|
return captor.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateMetadata_shouldDisableMergingForTagsAndMoods() {
|
||||||
|
MetadataUpdateContext context = captureContextFromUpdate();
|
||||||
|
|
||||||
|
assertFalse(context.isMergeTags(), "mergeTags should be false to allow deletion of tags");
|
||||||
|
assertFalse(context.isMergeMoods(), "mergeMoods should be false to allow deletion of moods");
|
||||||
|
}
|
||||||
|
}
|
||||||
+262
@@ -0,0 +1,262 @@
|
|||||||
|
package com.adityachandel.booklore.service.metadata;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.MetadataUpdateContext;
|
||||||
|
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
|
||||||
|
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||||
|
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||||
|
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.MoodEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.TagEntity;
|
||||||
|
import com.adityachandel.booklore.model.enums.MetadataReplaceMode;
|
||||||
|
import com.adityachandel.booklore.repository.*;
|
||||||
|
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||||
|
import com.adityachandel.booklore.service.file.FileMoveService;
|
||||||
|
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
|
||||||
|
import com.adityachandel.booklore.util.FileService;
|
||||||
|
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.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class BookMetadataUpdaterTest {
|
||||||
|
|
||||||
|
@Mock private AuthorRepository authorRepository;
|
||||||
|
@Mock private CategoryRepository categoryRepository;
|
||||||
|
@Mock private MoodRepository moodRepository;
|
||||||
|
@Mock private TagRepository tagRepository;
|
||||||
|
@Mock private BookRepository bookRepository;
|
||||||
|
@Mock private FileService fileService;
|
||||||
|
@Mock private MetadataMatchService metadataMatchService;
|
||||||
|
@Mock private AppSettingService appSettingService;
|
||||||
|
@Mock private MetadataWriterFactory metadataWriterFactory;
|
||||||
|
@Mock private BookReviewUpdateService bookReviewUpdateService;
|
||||||
|
@Mock private FileMoveService fileMoveService;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private BookMetadataUpdater bookMetadataUpdater;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
AppSettings appSettings = new AppSettings();
|
||||||
|
appSettings.setMetadataPersistenceSettings(new MetadataPersistenceSettings());
|
||||||
|
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setBookMetadata_withMergeTagsFalse_shouldReplaceTags() {
|
||||||
|
BookEntity bookEntity = new BookEntity();
|
||||||
|
bookEntity.setId(1L);
|
||||||
|
BookMetadataEntity metadataEntity = new BookMetadataEntity();
|
||||||
|
|
||||||
|
Set<TagEntity> existingTags = new HashSet<>();
|
||||||
|
existingTags.add(TagEntity.builder().name("Tag1").build());
|
||||||
|
existingTags.add(TagEntity.builder().name("Tag2").build());
|
||||||
|
metadataEntity.setTags(existingTags);
|
||||||
|
bookEntity.setMetadata(metadataEntity);
|
||||||
|
|
||||||
|
BookMetadata newMetadata = new BookMetadata();
|
||||||
|
newMetadata.setTags(Set.of("Tag1"));
|
||||||
|
|
||||||
|
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder()
|
||||||
|
.metadata(newMetadata)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||||
|
.bookEntity(bookEntity)
|
||||||
|
.metadataUpdateWrapper(wrapper)
|
||||||
|
.mergeTags(false)
|
||||||
|
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
when(tagRepository.findByName("Tag1")).thenReturn(Optional.of(TagEntity.builder().name("Tag1").build()));
|
||||||
|
|
||||||
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
|
|
||||||
|
assertEquals(1, bookEntity.getMetadata().getTags().size());
|
||||||
|
assertTrue(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag1")));
|
||||||
|
assertFalse(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag2")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setBookMetadata_withMergeTagsFalse_andEmptyIncomingSet_shouldClearAllTags() {
|
||||||
|
BookEntity bookEntity = new BookEntity();
|
||||||
|
bookEntity.setId(1L);
|
||||||
|
BookMetadataEntity metadataEntity = new BookMetadataEntity();
|
||||||
|
|
||||||
|
Set<TagEntity> existingTags = new HashSet<>();
|
||||||
|
existingTags.add(TagEntity.builder().name("Tag1").build());
|
||||||
|
existingTags.add(TagEntity.builder().name("Tag2").build());
|
||||||
|
metadataEntity.setTags(existingTags);
|
||||||
|
bookEntity.setMetadata(metadataEntity);
|
||||||
|
|
||||||
|
BookMetadata newMetadata = new BookMetadata();
|
||||||
|
newMetadata.setTags(Collections.emptySet());
|
||||||
|
|
||||||
|
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder()
|
||||||
|
.metadata(newMetadata)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||||
|
.bookEntity(bookEntity)
|
||||||
|
.metadataUpdateWrapper(wrapper)
|
||||||
|
.mergeTags(false)
|
||||||
|
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
|
|
||||||
|
assertTrue(bookEntity.getMetadata().getTags().isEmpty(), "All tags should be cleared when incoming set is empty");
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
void setBookMetadata_withMergeTagsTrue_shouldMergeTags() {
|
||||||
|
BookEntity bookEntity = new BookEntity();
|
||||||
|
bookEntity.setId(1L);
|
||||||
|
BookMetadataEntity metadataEntity = new BookMetadataEntity();
|
||||||
|
|
||||||
|
Set<TagEntity> existingTags = new HashSet<>();
|
||||||
|
existingTags.add(TagEntity.builder().name("Tag1").build());
|
||||||
|
existingTags.add(TagEntity.builder().name("Tag2").build());
|
||||||
|
metadataEntity.setTags(existingTags);
|
||||||
|
bookEntity.setMetadata(metadataEntity);
|
||||||
|
|
||||||
|
BookMetadata newMetadata = new BookMetadata();
|
||||||
|
newMetadata.setTags(Set.of("Tag3"));
|
||||||
|
|
||||||
|
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder()
|
||||||
|
.metadata(newMetadata)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||||
|
.bookEntity(bookEntity)
|
||||||
|
.metadataUpdateWrapper(wrapper)
|
||||||
|
.mergeTags(true)
|
||||||
|
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
when(tagRepository.findByName("Tag3")).thenReturn(Optional.of(TagEntity.builder().name("Tag3").build()));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(3, bookEntity.getMetadata().getTags().size()); // Tag1, Tag2, Tag3
|
||||||
|
assertTrue(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag1")));
|
||||||
|
assertTrue(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag2")));
|
||||||
|
assertTrue(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag3")));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
void setBookMetadata_withMergeMoodsFalse_shouldReplaceMoods() {
|
||||||
|
BookEntity bookEntity = new BookEntity();
|
||||||
|
bookEntity.setId(1L);
|
||||||
|
BookMetadataEntity metadataEntity = new BookMetadataEntity();
|
||||||
|
|
||||||
|
Set<MoodEntity> existingMoods = new HashSet<>();
|
||||||
|
existingMoods.add(MoodEntity.builder().name("Mood1").build());
|
||||||
|
existingMoods.add(MoodEntity.builder().name("Mood2").build());
|
||||||
|
metadataEntity.setMoods(existingMoods);
|
||||||
|
bookEntity.setMetadata(metadataEntity);
|
||||||
|
|
||||||
|
BookMetadata newMetadata = new BookMetadata();
|
||||||
|
newMetadata.setMoods(Set.of("Mood1"));
|
||||||
|
|
||||||
|
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder()
|
||||||
|
.metadata(newMetadata)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||||
|
.bookEntity(bookEntity)
|
||||||
|
.metadataUpdateWrapper(wrapper)
|
||||||
|
.mergeMoods(false)
|
||||||
|
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
when(moodRepository.findByName("Mood1")).thenReturn(Optional.of(MoodEntity.builder().name("Mood1").build()));
|
||||||
|
|
||||||
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertEquals(1, bookEntity.getMetadata().getMoods().size());
|
||||||
|
assertTrue(bookEntity.getMetadata().getMoods().stream().anyMatch(m -> m.getName().equals("Mood1")));
|
||||||
|
assertFalse(bookEntity.getMetadata().getMoods().stream().anyMatch(m -> m.getName().equals("Mood2")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setBookMetadata_withMergeMoodsFalse_andEmptyIncomingSet_shouldClearAllMoods() {
|
||||||
|
BookEntity bookEntity = new BookEntity();
|
||||||
|
bookEntity.setId(1L);
|
||||||
|
BookMetadataEntity metadataEntity = new BookMetadataEntity();
|
||||||
|
|
||||||
|
Set<MoodEntity> existingMoods = new HashSet<>();
|
||||||
|
existingMoods.add(MoodEntity.builder().name("Mood1").build());
|
||||||
|
existingMoods.add(MoodEntity.builder().name("Mood2").build());
|
||||||
|
metadataEntity.setMoods(existingMoods);
|
||||||
|
bookEntity.setMetadata(metadataEntity);
|
||||||
|
|
||||||
|
BookMetadata newMetadata = new BookMetadata();
|
||||||
|
newMetadata.setMoods(Collections.emptySet());
|
||||||
|
|
||||||
|
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder()
|
||||||
|
.metadata(newMetadata)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||||
|
.bookEntity(bookEntity)
|
||||||
|
.metadataUpdateWrapper(wrapper)
|
||||||
|
.mergeMoods(false)
|
||||||
|
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
|
|
||||||
|
assertTrue(bookEntity.getMetadata().getMoods().isEmpty(), "All moods should be cleared when incoming set is empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setBookMetadata_withMergeMoodsTrue_shouldMergeMoods() {
|
||||||
|
BookEntity bookEntity = new BookEntity();
|
||||||
|
bookEntity.setId(1L);
|
||||||
|
BookMetadataEntity metadataEntity = new BookMetadataEntity();
|
||||||
|
|
||||||
|
Set<MoodEntity> existingMoods = new HashSet<>();
|
||||||
|
existingMoods.add(MoodEntity.builder().name("Mood1").build());
|
||||||
|
existingMoods.add(MoodEntity.builder().name("Mood2").build());
|
||||||
|
metadataEntity.setMoods(existingMoods);
|
||||||
|
bookEntity.setMetadata(metadataEntity);
|
||||||
|
|
||||||
|
BookMetadata newMetadata = new BookMetadata();
|
||||||
|
newMetadata.setMoods(Set.of("Mood3"));
|
||||||
|
|
||||||
|
MetadataUpdateWrapper wrapper = MetadataUpdateWrapper.builder()
|
||||||
|
.metadata(newMetadata)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||||
|
.bookEntity(bookEntity)
|
||||||
|
.metadataUpdateWrapper(wrapper)
|
||||||
|
.mergeMoods(true)
|
||||||
|
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
when(moodRepository.findByName("Mood3")).thenReturn(Optional.of(MoodEntity.builder().name("Mood3").build()));
|
||||||
|
|
||||||
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
|
|
||||||
|
assertEquals(3, bookEntity.getMetadata().getMoods().size()); // Mood1, Mood2, Mood3
|
||||||
|
assertTrue(bookEntity.getMetadata().getMoods().stream().anyMatch(m -> m.getName().equals("Mood1")));
|
||||||
|
assertTrue(bookEntity.getMetadata().getMoods().stream().anyMatch(m -> m.getName().equals("Mood2")));
|
||||||
|
assertTrue(bookEntity.getMetadata().getMoods().stream().anyMatch(m -> m.getName().equals("Mood3")));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user