Replace arrow-based author reordering with CDK drag chips and persist author sort order (#3167) (#3175)

This commit is contained in:
ACX
2026-03-04 18:29:53 -07:00
committed by GitHub
parent 3bef84d102
commit 9c249fff1d
73 changed files with 901 additions and 304 deletions
@@ -38,11 +38,11 @@ public interface BookMapper {
@Mapping(source = "bookFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles") @Mapping(source = "bookFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles")
Book toBookWithDescription(BookEntity bookEntity, @Context boolean includeDescription); Book toBookWithDescription(BookEntity bookEntity, @Context boolean includeDescription);
default Set<String> mapAuthors(Set<AuthorEntity> authors) { default List<String> mapAuthors(List<AuthorEntity> authors) {
if (authors == null) return null; if (authors == null) return null;
return authors.stream() return authors.stream()
.map(AuthorEntity::getName) .map(AuthorEntity::getName)
.collect(Collectors.toSet()); .toList();
} }
default Set<String> mapCategories(Set<CategoryEntity> categories) { default Set<String> mapCategories(Set<CategoryEntity> categories) {
@@ -87,9 +87,9 @@ public interface BookMapperV2 {
} }
@Named("mapAuthors") @Named("mapAuthors")
default Set<String> mapAuthors(Set<AuthorEntity> authors) { default List<String> mapAuthors(List<AuthorEntity> authors) {
return authors == null ? Set.of() : return authors == null ? List.of() :
authors.stream().map(AuthorEntity::getName).collect(Collectors.toSet()); authors.stream().map(AuthorEntity::getName).toList();
} }
@Named("mapCategories") @Named("mapCategories")
@@ -71,13 +71,13 @@ public interface MobileBookMapper {
MobileBookDetail toDetail(BookEntity book, UserBookProgressEntity progress, UserBookFileProgressEntity fileProgress); MobileBookDetail toDetail(BookEntity book, UserBookProgressEntity progress, UserBookFileProgressEntity fileProgress);
@Named("mapAuthors") @Named("mapAuthors")
default List<String> mapAuthors(Set<AuthorEntity> authors) { default List<String> mapAuthors(List<AuthorEntity> authors) {
if (authors == null || authors.isEmpty()) { if (authors == null || authors.isEmpty()) {
return Collections.emptyList(); return Collections.emptyList();
} }
return authors.stream() return authors.stream()
.map(AuthorEntity::getName) .map(AuthorEntity::getName)
.collect(Collectors.toList()); .toList();
} }
@Named("mapCategories") @Named("mapCategories")
@@ -2,10 +2,10 @@ package org.booklore.model;
import lombok.Data; import lombok.Data;
import java.util.Set; import java.util.List;
@Data @Data
public class UploadedFileMetadata { public class UploadedFileMetadata {
private String title; private String title;
private Set<String> authors; private List<String> authors;
} }
@@ -60,7 +60,7 @@ public class BookMetadata {
private String externalUrl; private String externalUrl;
private Instant coverUpdatedOn; private Instant coverUpdatedOn;
private Instant audiobookCoverUpdatedOn; private Instant audiobookCoverUpdatedOn;
private Set<String> authors; private List<String> authors;
private Set<String> categories; private Set<String> categories;
private Set<String> moods; private Set<String> moods;
private Set<String> tags; private Set<String> tags;
@@ -3,6 +3,7 @@ package org.booklore.model.dto;
import lombok.*; import lombok.*;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.List;
import java.util.Set; import java.util.Set;
@Getter @Getter
@@ -37,6 +38,6 @@ public class EpubMetadata {
private String googleId; private String googleId;
private String ranobedbId; private String ranobedbId;
private Double ranobedbRating; private Double ranobedbRating;
private Set<String> authors; private List<String> authors;
private Set<String> categories; private Set<String> categories;
} }
@@ -3,13 +3,14 @@ package org.booklore.model.dto.request;
import lombok.Data; import lombok.Data;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.List;
import java.util.Set; import java.util.Set;
@Data @Data
public class BulkMetadataUpdateRequest { public class BulkMetadataUpdateRequest {
private Set<Long> bookIds; private Set<Long> bookIds;
private Set<String> authors; private List<String> authors;
private boolean clearAuthors; private boolean clearAuthors;
private String publisher; private String publisher;
@@ -24,7 +24,7 @@ public class GoogleBooksApiResponse {
public static class VolumeInfo { public static class VolumeInfo {
private String title; private String title;
private String subtitle; private String subtitle;
private Set<String> authors; private List<String> authors;
private String publisher; private String publisher;
private String publishedDate; private String publishedDate;
private String description; private String description;
@@ -8,6 +8,7 @@ import lombok.NoArgsConstructor;
import org.booklore.model.dto.ComicMetadata; import org.booklore.model.dto.ComicMetadata;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.List;
import java.util.Set; import java.util.Set;
@Data @Data
@@ -18,7 +19,7 @@ import java.util.Set;
public class SidecarBookMetadata { public class SidecarBookMetadata {
private String title; private String title;
private String subtitle; private String subtitle;
private Set<String> authors; private List<String> authors;
private String publisher; private String publisher;
private LocalDate publishedDate; private LocalDate publishedDate;
private String description; private String description;
@@ -9,7 +9,9 @@ import org.hibernate.annotations.FetchMode;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
@Entity @Entity
@@ -369,7 +371,8 @@ public class BookMetadataEntity {
joinColumns = @JoinColumn(name = "book_id"), joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id")) inverseJoinColumns = @JoinColumn(name = "author_id"))
@Fetch(FetchMode.SUBSELECT) @Fetch(FetchMode.SUBSELECT)
private Set<AuthorEntity> authors; @OrderColumn(name = "sort_order")
private List<AuthorEntity> authors;
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable( @JoinTable(
@@ -137,10 +137,10 @@ public class BookCreatorService {
.forEach(catEntity -> bookEntity.getMetadata().getCategories().add(catEntity)); .forEach(catEntity -> bookEntity.getMetadata().getCategories().add(catEntity));
} }
public void addAuthorsToBook(Set<String> authors, BookEntity bookEntity) { public void addAuthorsToBook(Collection<String> authors, BookEntity bookEntity) {
if (authors == null || authors.isEmpty()) return; if (authors == null || authors.isEmpty()) return;
if (bookEntity.getMetadata().getAuthors() == null) { if (bookEntity.getMetadata().getAuthors() == null) {
bookEntity.getMetadata().setAuthors(new HashSet<>()); bookEntity.getMetadata().setAuthors(new ArrayList<>());
} }
authors.stream() authors.stream()
.map(authorName -> truncate(authorName, 255)) .map(authorName -> truncate(authorName, 255))
@@ -26,8 +26,10 @@ import org.springframework.transaction.annotation.Transactional;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.time.Instant; import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@@ -160,7 +162,7 @@ public class BookFileDetachmentService {
copy.setContentRating(source.getContentRating()); copy.setContentRating(source.getContentRating());
if (source.getAuthors() != null) { if (source.getAuthors() != null) {
copy.setAuthors(new HashSet<>(source.getAuthors())); copy.setAuthors(new ArrayList<>(source.getAuthors()));
} }
if (source.getCategories() != null) { if (source.getCategories() != null) {
copy.setCategories(new HashSet<>(source.getCategories())); copy.setCategories(new HashSet<>(source.getCategories()));
@@ -27,6 +27,7 @@ import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException; import java.time.format.DateTimeParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
@Slf4j @Slf4j
@@ -69,7 +70,7 @@ public class PhysicalBookService {
bookEntity.setMetadata(metadata); bookEntity.setMetadata(metadata);
if (request.getAuthors() != null && !request.getAuthors().isEmpty()) { if (request.getAuthors() != null && !request.getAuthors().isEmpty()) {
addAuthorsToBook(new HashSet<>(request.getAuthors()), bookEntity); addAuthorsToBook(new ArrayList<>(request.getAuthors()), bookEntity);
} }
if (request.getCategories() != null && !request.getCategories().isEmpty()) { if (request.getCategories() != null && !request.getCategories().isEmpty()) {
@@ -122,9 +123,9 @@ public class PhysicalBookService {
return cleaned.length() == 10 ? cleaned : null; return cleaned.length() == 10 ? cleaned : null;
} }
private void addAuthorsToBook(Set<String> authors, BookEntity bookEntity) { private void addAuthorsToBook(List<String> authors, BookEntity bookEntity) {
if (bookEntity.getMetadata().getAuthors() == null) { if (bookEntity.getMetadata().getAuthors() == null) {
bookEntity.getMetadata().setAuthors(new HashSet<>()); bookEntity.getMetadata().setAuthors(new ArrayList<>());
} }
authors.stream() authors.stream()
.map(authorName -> truncate(authorName, 255)) .map(authorName -> truncate(authorName, 255))
@@ -120,6 +120,22 @@ public class BookdropBulkEditService {
metadataHelper.updateFetchedMetadata(file, currentMetadata); metadataHelper.updateFetchedMetadata(file, currentMetadata);
} }
private void updateArrayField(String fieldName, Set<String> enabledFields,
List<String> currentValue, List<String> newValue,
java.util.function.Consumer<List<String>> setter, boolean mergeArrays) {
if (enabledFields.contains(fieldName) && newValue != null) {
if (mergeArrays && currentValue != null) {
List<String> merged = new ArrayList<>(currentValue);
for (String v : newValue) {
if (!merged.contains(v)) merged.add(v);
}
setter.accept(merged);
} else {
setter.accept(newValue);
}
}
}
private void updateArrayField(String fieldName, Set<String> enabledFields, private void updateArrayField(String fieldName, Set<String> enabledFields,
Set<String> currentValue, Set<String> newValue, Set<String> currentValue, Set<String> newValue,
java.util.function.Consumer<Set<String>> setter, boolean mergeArrays) { java.util.function.Consumer<Set<String>> setter, boolean mergeArrays) {
@@ -430,9 +430,9 @@ public class FilenamePatternExtractor {
} }
} }
private Set<String> parseAuthors(String value) { private List<String> parseAuthors(String value) {
String[] parts = PATTERN.split(value); String[] parts = PATTERN.split(value);
Set<String> authors = new LinkedHashSet<>(); List<String> authors = new ArrayList<>();
for (String part : parts) { for (String part : parts) {
String trimmed = part.trim(); String trimmed = part.trim();
if (!trimmed.isEmpty()) { if (!trimmed.isEmpty()) {
@@ -241,37 +241,45 @@ public class BookMetadataUpdater {
private void updateAuthorsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge, MetadataReplaceMode replaceMode) { private void updateAuthorsIfNeeded(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, boolean merge, MetadataReplaceMode replaceMode) {
if (Boolean.TRUE.equals(e.getAuthorsLocked())) return; if (Boolean.TRUE.equals(e.getAuthorsLocked())) return;
e.setAuthors(Optional.ofNullable(e.getAuthors()).orElseGet(HashSet::new)); e.setAuthors(Optional.ofNullable(e.getAuthors()).orElseGet(ArrayList::new));
if (clear.isAuthors()) { if (clear.isAuthors()) {
e.getAuthors().clear(); e.getAuthors().clear();
return; return;
} }
Set<String> authorNames = Optional.ofNullable(m.getAuthors()).orElse(Collections.emptySet()); List<String> authorNames = Optional.ofNullable(m.getAuthors()).orElse(Collections.emptyList());
if (authorNames.isEmpty()) { if (authorNames.isEmpty()) {
if (replaceMode == MetadataReplaceMode.REPLACE_ALL) e.getAuthors().clear(); if (replaceMode == MetadataReplaceMode.REPLACE_ALL) e.getAuthors().clear();
return; return;
} }
Set<AuthorEntity> newAuthors = authorNames.stream() List<AuthorEntity> newAuthors = authorNames.stream()
.filter(name -> name != null && !name.isBlank()) .filter(name -> name != null && !name.isBlank())
.map(name -> authorRepository.findByName(name) .map(name -> authorRepository.findByName(name)
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(name).build()))) .orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(name).build())))
.collect(Collectors.toSet()); .toList();
if (newAuthors.isEmpty()) return; if (newAuthors.isEmpty()) return;
if (replaceMode == MetadataReplaceMode.REPLACE_ALL || replaceMode == MetadataReplaceMode.REPLACE_WHEN_PROVIDED) { if (replaceMode == MetadataReplaceMode.REPLACE_ALL || replaceMode == MetadataReplaceMode.REPLACE_WHEN_PROVIDED) {
if (!merge) e.getAuthors().clear(); if (!merge) e.getAuthors().clear();
e.getAuthors().addAll(newAuthors); for (AuthorEntity author : newAuthors) {
if (!e.getAuthors().contains(author)) {
e.getAuthors().add(author);
}
}
e.updateSearchText(); e.updateSearchText();
} else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING && e.getAuthors().isEmpty()) { } else if (replaceMode == MetadataReplaceMode.REPLACE_MISSING && e.getAuthors().isEmpty()) {
e.getAuthors().addAll(newAuthors); e.getAuthors().addAll(newAuthors);
e.updateSearchText(); e.updateSearchText();
} else if (replaceMode == null) { } else if (replaceMode == null) {
if (!merge) e.getAuthors().clear(); if (!merge) e.getAuthors().clear();
e.getAuthors().addAll(newAuthors); for (AuthorEntity author : newAuthors) {
if (!e.getAuthors().contains(author)) {
e.getAuthors().add(author);
}
}
e.updateSearchText(); e.updateSearchText();
} }
} }
@@ -2,9 +2,9 @@ package org.booklore.service.metadata;
import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.BookMetadata;
import java.util.Set; import java.util.Collection;
@FunctionalInterface @FunctionalInterface
interface FieldValueExtractorList { interface FieldValueExtractorList {
Set<String> extract(BookMetadata metadata); Collection<String> extract(BookMetadata metadata);
} }
@@ -675,7 +675,7 @@ public class MetadataRefreshService {
if (refreshOptions.isMergeCategories()) { if (refreshOptions.isMergeCategories()) {
metadata.setCategories(getAllCategories(metadataMap, fieldOptions.getCategories(), BookMetadata::getCategories)); metadata.setCategories(getAllCategories(metadataMap, fieldOptions.getCategories(), BookMetadata::getCategories));
} else { } else {
metadata.setCategories(resolveFieldAsList(metadataMap, fieldOptions.getCategories(), BookMetadata::getCategories)); metadata.setCategories(resolveFieldAsSet(metadataMap, fieldOptions.getCategories(), BookMetadata::getCategories));
} }
} else if (isReplaceAll && existingMetadata != null) { } else if (isReplaceAll && existingMetadata != null) {
metadata.setCategories(existingMetadata.getCategories()); metadata.setCategories(existingMetadata.getCategories());
@@ -704,8 +704,16 @@ public class MetadataRefreshService {
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, Objects::nonNull); return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, Objects::nonNull);
} }
protected Set<String> resolveFieldAsList (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor){ protected List<String> resolveFieldAsList (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor){
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, (value) -> value != null && !value.isEmpty()); Collection<String> result = resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, (value) -> value != null && !value.isEmpty());
if (result == null) return null;
return result instanceof List<String> list ? list : new ArrayList<>(result);
}
protected Set<String> resolveFieldAsSet (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor){
Collection<String> result = resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, (value) -> value != null && !value.isEmpty());
if (result == null) return null;
return result instanceof Set<String> set ? set : new HashSet<>(result);
} }
private <T > T resolveFieldWithProviders(Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function < BookMetadata, T > extractor, Predicate < T > isValidValue) { private <T > T resolveFieldWithProviders(Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function < BookMetadata, T > extractor, Predicate < T > isValidValue) {
@@ -744,7 +752,7 @@ public class MetadataRefreshService {
for (MetadataProvider provider : providers) { for (MetadataProvider provider : providers) {
if (provider != null && metadataMap.containsKey(provider)) { if (provider != null && metadataMap.containsKey(provider)) {
Set<String> extracted = fieldValueExtractor.extract(metadataMap.get(provider)); Collection<String> extracted = fieldValueExtractor.extract(metadataMap.get(provider));
if (extracted != null) { if (extracted != null) {
uniqueCategories.addAll(extracted); uniqueCategories.addAll(extracted);
} }
@@ -88,7 +88,7 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor {
String albumArtist = tag.getFirst(FieldKey.ALBUM_ARTIST); String albumArtist = tag.getFirst(FieldKey.ALBUM_ARTIST);
String artist = tag.getFirst(FieldKey.ARTIST); String artist = tag.getFirst(FieldKey.ARTIST);
Set<String> authors = new HashSet<>(); List<String> authors = new ArrayList<>();
if (StringUtils.isNotBlank(albumArtist)) { if (StringUtils.isNotBlank(albumArtist)) {
authors.add(albumArtist); authors.add(albumArtist);
} else if (StringUtils.isNotBlank(artist)) { } else if (StringUtils.isNotBlank(artist)) {
@@ -223,8 +223,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
} }
} }
Set<String> authors = new HashSet<>(); List<String> authors = new ArrayList<>(splitValues(getTextContent(document, "Writer")));
authors.addAll(splitValues(getTextContent(document, "Writer")));
if (!authors.isEmpty()) { if (!authors.isEmpty()) {
builder.authors(authors); builder.authors(authors);
} }
@@ -243,8 +243,8 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
Map<String, String> creatorsById = new HashMap<>(); Map<String, String> creatorsById = new HashMap<>();
Map<String, String> creatorRoleById = new HashMap<>(); Map<String, String> creatorRoleById = new HashMap<>();
Map<String, Set<String>> creatorsByRole = new HashMap<>(); Map<String, List<String>> creatorsByRole = new HashMap<>();
creatorsByRole.put("aut", new HashSet<>()); creatorsByRole.put("aut", new ArrayList<>());
Map<String, String> titlesById = new HashMap<>(); Map<String, String> titlesById = new HashMap<>();
Map<String, String> titleTypeById = new HashMap<>(); Map<String, String> titleTypeById = new HashMap<>();
@@ -346,7 +346,7 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
case "creator" -> { case "creator" -> {
String role = el.getAttributeNS(OPF_NS, "role"); String role = el.getAttributeNS(OPF_NS, "role");
if (StringUtils.isNotBlank(role)) { if (StringUtils.isNotBlank(role)) {
creatorsByRole.computeIfAbsent(role, k -> new HashSet<>()).add(text); creatorsByRole.computeIfAbsent(role, k -> new ArrayList<>()).add(text);
} else { } else {
String id = el.getAttribute("id"); String id = el.getAttribute("id");
if (StringUtils.isNotBlank(id)) { if (StringUtils.isNotBlank(id)) {
@@ -449,7 +449,7 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
String id = entry.getKey(); String id = entry.getKey();
String value = entry.getValue(); String value = entry.getValue();
String role = creatorRoleById.getOrDefault(id, "aut"); String role = creatorRoleById.getOrDefault(id, "aut");
creatorsByRole.computeIfAbsent(role, k -> new HashSet<>()).add(value); creatorsByRole.computeIfAbsent(role, k -> new ArrayList<>()).add(value);
} }
builderMeta.authors(creatorsByRole.get("aut")); builderMeta.authors(creatorsByRole.get("aut"));
@@ -16,8 +16,10 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Base64; import java.util.Base64;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -96,7 +98,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
Document doc = builder.parse(inputStream); Document doc = builder.parse(inputStream);
BookMetadata.BookMetadataBuilder metadataBuilder = BookMetadata.builder(); BookMetadata.BookMetadataBuilder metadataBuilder = BookMetadata.builder();
Set<String> authors = new HashSet<>(); List<String> authors = new ArrayList<>();
Set<String> categories = new HashSet<>(); Set<String> categories = new HashSet<>();
// Extract title-info (main metadata section) // Extract title-info (main metadata section)
@@ -128,7 +130,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
} }
private void extractTitleInfo(Element titleInfo, BookMetadata.BookMetadataBuilder builder, private void extractTitleInfo(Element titleInfo, BookMetadata.BookMetadataBuilder builder,
Set<String> authors, Set<String> categories) { List<String> authors, Set<String> categories) {
// Extract genres (categories) // Extract genres (categories)
NodeList genres = titleInfo.getElementsByTagNameNS(FB2_NAMESPACE, "genre"); NodeList genres = titleInfo.getElementsByTagNameNS(FB2_NAMESPACE, "genre");
for (int i = 0; i < genres.getLength(); i++) { for (int i = 0; i < genres.getLength(); i++) {
@@ -89,7 +89,7 @@ public abstract class MobiBaseMetadataExtractor implements FileMetadataExtractor
} }
BookMetadata.BookMetadataBuilder builder = BookMetadata.builder(); BookMetadata.BookMetadataBuilder builder = BookMetadata.builder();
Set<String> authors = new HashSet<>(); List<String> authors = new ArrayList<>();
Set<String> categories = new HashSet<>(); Set<String> categories = new HashSet<>();
// Extract title // Extract title
@@ -87,7 +87,7 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
} }
if (StringUtils.isNotBlank(info.getAuthor())) { if (StringUtils.isNotBlank(info.getAuthor())) {
Set<String> authors = parseAuthors(info.getAuthor()); List<String> authors = parseAuthors(info.getAuthor());
if (!authors.isEmpty()) { if (!authors.isEmpty()) {
metadataBuilder.authors(authors); metadataBuilder.authors(authors);
} }
@@ -271,12 +271,12 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
builder.language(language); builder.language(language);
} }
Set<String> creators = xpathEvaluateMultiple(xpath, doc, "//dc:creator/rdf:Seq/rdf:li/text()"); List<String> creators = xpathEvaluateMultiple(xpath, doc, "//dc:creator/rdf:Seq/rdf:li/text()");
if (!creators.isEmpty()) { if (!creators.isEmpty()) {
builder.authors(creators); builder.authors(creators);
} }
Set<String> subjects = xpathEvaluateMultiple(xpath, doc, "//dc:subject/rdf:Bag/rdf:li/text()"); Set<String> subjects = new HashSet<>(xpathEvaluateMultiple(xpath, doc, "//dc:subject/rdf:Bag/rdf:li/text()"));
if (!subjects.isEmpty()) { if (!subjects.isEmpty()) {
Set<String> knownNonCategories = new HashSet<>(); Set<String> knownNonCategories = new HashSet<>();
@@ -543,12 +543,12 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
return ids; return ids;
} }
private Set<String> parseAuthors(String authorString) { private List<String> parseAuthors(String authorString) {
if (authorString == null) return Collections.emptySet(); if (authorString == null) return Collections.emptyList();
return Arrays.stream(COMMA_AMPERSAND_PATTERN.split(authorString)) return Arrays.stream(COMMA_AMPERSAND_PATTERN.split(authorString))
.map(String::trim) .map(String::trim)
.filter(StringUtils::isNotBlank) .filter(StringUtils::isNotBlank)
.collect(Collectors.toSet()); .toList();
} }
private LocalDate convertCalendarToLocalDate(Calendar calendar) { private LocalDate convertCalendarToLocalDate(Calendar calendar) {
@@ -566,9 +566,9 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
return result == null ? "" : result.trim(); return result == null ? "" : result.trim();
} }
private Set<String> xpathEvaluateMultiple(XPath xpath, Document doc, String expression) throws XPathExpressionException { private List<String> xpathEvaluateMultiple(XPath xpath, Document doc, String expression) throws XPathExpressionException {
NodeList nodes = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); NodeList nodes = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
Set<String> results = new HashSet<>(); List<String> results = new ArrayList<>();
if (nodes != null) { if (nodes != null) {
for (int i = 0; i < nodes.getLength(); i++) { for (int i = 0; i < nodes.getLength(); i++) {
String text = nodes.item(i).getNodeValue(); String text = nodes.item(i).getNodeValue();
@@ -288,7 +288,7 @@ public class AmazonBookParser implements BookParser, DetailedMetadataProvider {
.provider(MetadataProvider.Amazon) .provider(MetadataProvider.Amazon)
.title(titleInfo.title()) .title(titleInfo.title())
.subtitle(titleInfo.subtitle()) .subtitle(titleInfo.subtitle())
.authors(new HashSet<>(getAuthors(doc))) .authors(new ArrayList<>(getAuthors(doc)))
.categories(new HashSet<>(getBestSellerCategories(doc))) .categories(new HashSet<>(getBestSellerCategories(doc)))
.description(cleanDescriptionHtml(getDescription(doc))) .description(cleanDescriptionHtml(getDescription(doc)))
.seriesName(seriesInfo.name()) .seriesName(seriesInfo.name())
@@ -380,23 +380,23 @@ public class AmazonBookParser implements BookParser, DetailedMetadataProvider {
return new TitleInfo(title, subtitle); return new TitleInfo(title, subtitle);
} }
private Set<String> getAuthors(Document doc) { private List<String> getAuthors(Document doc) {
Set<String> authors = new HashSet<>(); List<String> authors = new ArrayList<>();
try { try {
Element bylineDiv = doc.selectFirst("#bylineInfo_feature_div"); Element bylineDiv = doc.selectFirst("#bylineInfo_feature_div");
if (bylineDiv != null) { if (bylineDiv != null) {
authors.addAll(bylineDiv.select(".author a").stream().map(Element::text).collect(Collectors.toSet())); authors.addAll(bylineDiv.select(".author a").stream().map(Element::text).toList());
} }
if (authors.isEmpty()) { if (authors.isEmpty()) {
Element bylineInfo = doc.selectFirst("#bylineInfo"); Element bylineInfo = doc.selectFirst("#bylineInfo");
if (bylineInfo != null) { if (bylineInfo != null) {
authors.addAll(bylineInfo.select(".author a").stream().map(Element::text).collect(Collectors.toSet())); authors.addAll(bylineInfo.select(".author a").stream().map(Element::text).toList());
} }
} }
if (authors.isEmpty()) { if (authors.isEmpty()) {
authors.addAll(doc.select(".author a").stream().map(Element::text).collect(Collectors.toSet())); authors.addAll(doc.select(".author a").stream().map(Element::text).toList());
} }
if (authors.isEmpty()) { if (authors.isEmpty()) {
@@ -121,7 +121,7 @@ public class AudibleParser implements BookParser, DetailedMetadataProvider {
Element container = findProductContainer(link); Element container = findProductContainer(link);
String thumbnailUrl = extractPreviewThumbnail(container, link); String thumbnailUrl = extractPreviewThumbnail(container, link);
Set<String> authors = extractPreviewAuthors(container); List<String> authors = extractPreviewAuthors(container);
String narrator = extractPreviewNarrator(container); String narrator = extractPreviewNarrator(container);
BookMetadata.BookMetadataBuilder builder = BookMetadata.builder() BookMetadata.BookMetadataBuilder builder = BookMetadata.builder()
@@ -173,8 +173,8 @@ public class AudibleParser implements BookParser, DetailedMetadataProvider {
return null; return null;
} }
private Set<String> extractPreviewAuthors(Element container) { private List<String> extractPreviewAuthors(Element container) {
Set<String> authors = new LinkedHashSet<>(); List<String> authors = new ArrayList<>();
if (container == null) return authors; if (container == null) return authors;
for (Element authorLink : container.select("a[href*='/author/']")) { for (Element authorLink : container.select("a[href*='/author/']")) {
@@ -319,7 +319,7 @@ public class AudibleParser implements BookParser, DetailedMetadataProvider {
} }
} }
Set<String> authors = extractPersonNames(audiobookNode, "author"); List<String> authors = extractPersonNames(audiobookNode, "author");
String narrator = extractFirstPersonName(audiobookNode, "readBy"); String narrator = extractFirstPersonName(audiobookNode, "readBy");
String publisher = getJsonString(audiobookNode, "publisher"); String publisher = getJsonString(audiobookNode, "publisher");
String description = getJsonString(audiobookNode, "description"); String description = getJsonString(audiobookNode, "description");
@@ -445,8 +445,8 @@ public class AudibleParser implements BookParser, DetailedMetadataProvider {
return fieldNode.asText(null); return fieldNode.asText(null);
} }
private Set<String> extractPersonNames(JsonNode node, String field) { private List<String> extractPersonNames(JsonNode node, String field) {
Set<String> names = new HashSet<>(); List<String> names = new ArrayList<>();
if (node == null) return names; if (node == null) return names;
JsonNode fieldNode = node.path(field); JsonNode fieldNode = node.path(field);
@@ -580,7 +580,7 @@ public class ComicvineBookParser implements BookParser, DetailedMetadataProvider
} }
String volumeName = comic.getVolume() != null ? comic.getVolume().getName() : null; String volumeName = comic.getVolume() != null ? comic.getVolume().getName() : null;
Set<String> authors = extractAuthors(comic.getPersonCredits()); List<String> authors = extractAuthors(comic.getPersonCredits());
String formattedTitle = formatTitle(volumeName, comic.getIssueNumber(), comic.getName()); String formattedTitle = formatTitle(volumeName, comic.getIssueNumber(), comic.getName());
String dateToUse = comic.getStoreDate() != null ? comic.getStoreDate() : comic.getCoverDate(); String dateToUse = comic.getStoreDate() != null ? comic.getStoreDate() : comic.getCoverDate();
@@ -622,7 +622,7 @@ public class ComicvineBookParser implements BookParser, DetailedMetadataProvider
} }
private BookMetadata buildVolumeMetadata(Comic volume) { private BookMetadata buildVolumeMetadata(Comic volume) {
Set<String> authors = extractAuthors(volume.getPersonCredits()); List<String> authors = extractAuthors(volume.getPersonCredits());
return BookMetadata.builder() return BookMetadata.builder()
.provider(MetadataProvider.Comicvine) .provider(MetadataProvider.Comicvine)
@@ -772,14 +772,14 @@ public class ComicvineBookParser implements BookParser, DetailedMetadataProvider
return title; return title;
} }
private Set<String> extractAuthors(List<Comic.PersonCredit> personCredits) { private List<String> extractAuthors(List<Comic.PersonCredit> personCredits) {
if (personCredits == null || personCredits.isEmpty()) { if (personCredits == null || personCredits.isEmpty()) {
return Collections.emptySet(); return Collections.emptyList();
} }
Set<String> writerRoles = Set.of("writer", "script", "story", "plotter", "plot"); Set<String> writerRoles = Set.of("writer", "script", "story", "plotter", "plot");
Set<String> authors = personCredits.stream() List<String> authors = personCredits.stream()
.filter(pc -> { .filter(pc -> {
if (pc.getRole() == null) return false; if (pc.getRole() == null) return false;
String role = pc.getRole().toLowerCase(); String role = pc.getRole().toLowerCase();
@@ -787,7 +787,7 @@ public class ComicvineBookParser implements BookParser, DetailedMetadataProvider
}) })
.map(Comic.PersonCredit::getName) .map(Comic.PersonCredit::getName)
.filter(name -> name != null && !name.isEmpty()) .filter(name -> name != null && !name.isEmpty())
.collect(Collectors.toSet()); .toList();
if (authors.isEmpty()) { if (authors.isEmpty()) {
List<String> allRoles = personCredits.stream() List<String> allRoles = personCredits.stream()
@@ -799,7 +799,7 @@ public class ComicvineBookParser implements BookParser, DetailedMetadataProvider
.filter(pc -> pc.getRole() != null && pc.getRole().toLowerCase().contains("creator")) .filter(pc -> pc.getRole() != null && pc.getRole().toLowerCase().contains("creator"))
.map(Comic.PersonCredit::getName) .map(Comic.PersonCredit::getName)
.filter(name -> name != null && !name.isEmpty()) .filter(name -> name != null && !name.isEmpty())
.collect(Collectors.toSet()); .toList();
} }
return authors; return authors;
@@ -177,7 +177,7 @@ public class DoubanBookParser implements BookParser {
// Extract abstract information // Extract abstract information
String abstractText = item.get("abstract").asText(); String abstractText = item.get("abstract").asText();
Set<String> authors = Set.of(); List<String> authors = List.of();
String publisher = null; String publisher = null;
String pubDate = null; String pubDate = null;
@@ -189,12 +189,12 @@ public class DoubanBookParser implements BookParser {
authors = Arrays.stream(parts, 0, parts.length - 3) authors = Arrays.stream(parts, 0, parts.length - 3)
.map(String::trim) .map(String::trim)
.filter(s -> !s.isEmpty()) .filter(s -> !s.isEmpty())
.collect(Collectors.toSet()); .toList();
publisher = parts[parts.length - 3].trim(); publisher = parts[parts.length - 3].trim();
pubDate = parts[parts.length - 2].trim(); pubDate = parts[parts.length - 2].trim();
} else if (parts.length >= 2) { } else if (parts.length >= 2) {
// Fallback for shorter abstracts // Fallback for shorter abstracts
authors = Set.of(parts[1].trim()); authors = List.of(parts[1].trim());
if (parts.length >= 3) { if (parts.length >= 3) {
publisher = parts[2].trim(); publisher = parts[2].trim();
} }
@@ -279,7 +279,7 @@ public class DoubanBookParser implements BookParser {
.provider(MetadataProvider.Douban) .provider(MetadataProvider.Douban)
.title(getTitle(doc)) .title(getTitle(doc))
.subtitle(getSubtitle(doc)) .subtitle(getSubtitle(doc))
.authors(new HashSet<>(getAuthors(doc))) .authors(new ArrayList<>(getAuthors(doc)))
.categories(new HashSet<>(getCategories(doc))) .categories(new HashSet<>(getCategories(doc)))
.description(cleanDescriptionHtml(getDescription(doc))) .description(cleanDescriptionHtml(getDescription(doc)))
.seriesName(getSeriesName(doc)) .seriesName(getSeriesName(doc))
@@ -359,8 +359,8 @@ public class DoubanBookParser implements BookParser {
return null; return null;
} }
private Set<String> getAuthors(Document doc) { private List<String> getAuthors(Document doc) {
Set<String> authors = new HashSet<>(); List<String> authors = new ArrayList<>();
try { try {
Element infoElement = doc.selectFirst("#info"); Element infoElement = doc.selectFirst("#info");
if (infoElement != null) { if (infoElement != null) {
@@ -386,7 +386,7 @@ public class DoubanBookParser implements BookParser {
} catch (Exception e) { } catch (Exception e) {
log.warn("Failed to parse authors: {}", e.getMessage()); log.warn("Failed to parse authors: {}", e.getMessage());
} }
return authors.isEmpty() ? Set.of() : authors; return authors.isEmpty() ? List.of() : authors;
} }
private String getDescription(Document doc) { private String getDescription(Document doc) {
@@ -194,7 +194,7 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
String contributorKey = findKeyByPrefix(keySet, "Contributor:kca"); String contributorKey = findKeyByPrefix(keySet, "Contributor:kca");
String contributorName = getJsonStringField(apolloStateJson, contributorKey, "name"); String contributorName = getJsonStringField(apolloStateJson, contributorKey, "name");
if (contributorName != null) { if (contributorName != null) {
builder.authors(Set.of(contributorName)); builder.authors(List.of(contributorName));
} }
} }
@@ -479,7 +479,7 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
String queryAuthor = request.getAuthor(); String queryAuthor = request.getAuthor();
for (Element previewBook : previewBooks) { for (Element previewBook : previewBooks) {
Set<String> authors = extractAuthorsPreview(previewBook); List<String> authors = extractAuthorsPreview(previewBook);
if (queryAuthor != null && !queryAuthor.isBlank()) { if (queryAuthor != null && !queryAuthor.isBlank()) {
List<String> queryAuthorTokens = List.of(WHITESPACE_PATTERN.split(queryAuthor.toLowerCase())); List<String> queryAuthorTokens = List.of(WHITESPACE_PATTERN.split(queryAuthor.toLowerCase()));
@@ -549,8 +549,8 @@ public class GoodReadsParser implements BookParser, DetailedMetadataProvider {
return null; return null;
} }
private Set<String> extractAuthorsPreview(Element book) { private List<String> extractAuthorsPreview(Element book) {
Set<String> authors = new HashSet<>(); List<String> authors = new ArrayList<>();
try { try {
Elements authorsElement = book.select("a.authorName"); Elements authorsElement = book.select("a.authorName");
for (Element authorElement : authorsElement) { for (Element authorElement : authorsElement) {
@@ -392,15 +392,15 @@ public class GoogleParser implements BookParser {
return WHITESPACE_PATTERN.matcher(title.trim()).replaceAll(" "); return WHITESPACE_PATTERN.matcher(title.trim()).replaceAll(" ");
} }
private Set<String> cleanAuthors(Set<String> authors) { private List<String> cleanAuthors(List<String> authors) {
if (authors == null || authors.isEmpty()) { if (authors == null || authors.isEmpty()) {
return Set.of(); return List.of();
} }
return authors.stream() return authors.stream()
.filter(Objects::nonNull) .filter(Objects::nonNull)
.filter(author -> !author.isBlank()) .filter(author -> !author.isBlank())
.map(String::trim) .map(String::trim)
.collect(Collectors.toCollection(LinkedHashSet::new)); .toList();
} }
private Set<String> cleanCategories(Set<String> categories) { private Set<String> cleanCategories(Set<String> categories) {
@@ -178,7 +178,7 @@ public class HardcoverParser implements BookParser {
metadata.setDescription(doc.getDescription()); metadata.setDescription(doc.getDescription());
if (doc.getAuthorNames() != null) { if (doc.getAuthorNames() != null) {
metadata.setAuthors(Set.copyOf(doc.getAuthorNames())); metadata.setAuthors(List.copyOf(doc.getAuthorNames()));
} }
mapSeriesInfo(doc, metadata); mapSeriesInfo(doc, metadata);
@@ -226,7 +226,7 @@ public class HardcoverParser implements BookParser {
.filter(Objects::nonNull) .filter(Objects::nonNull)
.map(GraphQLResponse.Author::getName) .map(GraphQLResponse.Author::getName)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(Collectors.toSet())); .toList());
} }
if (book.getFeaturedBookSeries() != null && book.getFeaturedBookSeries().getSeries() != null) { if (book.getFeaturedBookSeries() != null && book.getFeaturedBookSeries().getSeries() != null) {
@@ -399,7 +399,7 @@ public class LubimyCzytacParser implements BookParser {
// Author(s) - can be single Person or array of Person objects // Author(s) - can be single Person or array of Person objects
if (root.has("author")) { if (root.has("author")) {
try { try {
Set<String> authors = new HashSet<>(); List<String> authors = new ArrayList<>();
JsonNode authorNode = root.get("author"); JsonNode authorNode = root.get("author");
if (authorNode.isArray()) { if (authorNode.isArray()) {
@@ -225,11 +225,11 @@ public class RanobeDbParser implements BookParser {
.findFirst() .findFirst()
.orElse(-1); .orElse(-1);
HashSet<String> authors = book.getEditions().stream() List<String> authors = book.getEditions().stream()
.flatMap(edition -> edition.getStaff().stream()) .flatMap(edition -> edition.getStaff().stream())
.filter(staff -> RanobedbBookResponse.RoleType.AUTHOR.equals(staff.getRoleType())) .filter(staff -> RanobedbBookResponse.RoleType.AUTHOR.equals(staff.getRoleType()))
.map(staff -> staff.getRomaji() != null ? staff.getRomaji() : staff.getName()) .map(staff -> staff.getRomaji() != null ? staff.getRomaji() : staff.getName())
.collect(Collectors.toCollection(HashSet::new)); .toList();
HashSet<String> genres = book.getSeries() != null ? book.getSeries().getTags().stream() HashSet<String> genres = book.getSeries() != null ? book.getSeries().getTags().stream()
.filter(tag -> RanobedbBookResponse.TagType.GENRE.equals(tag.getTtype())) .filter(tag -> RanobedbBookResponse.TagType.GENRE.equals(tag.getTtype()))
@@ -10,6 +10,7 @@ import org.springframework.util.StringUtils;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.Instant; import java.time.Instant;
import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -145,11 +146,11 @@ public class SidecarMetadataMapper {
return baseName + ".cover.jpg"; return baseName + ".cover.jpg";
} }
private Set<String> extractNames(Set<AuthorEntity> entities) { private List<String> extractNames(List<AuthorEntity> entities) {
if (entities == null) return null; if (entities == null) return null;
return entities.stream() return entities.stream()
.map(AuthorEntity::getName) .map(AuthorEntity::getName)
.collect(Collectors.toSet()); .toList();
} }
private Set<String> extractCategoryNames(Set<CategoryEntity> entities) { private Set<String> extractCategoryNames(Set<CategoryEntity> entities) {
@@ -970,11 +970,11 @@ public class EpubMetadataWriter implements MetadataWriter {
} }
if (metadata.getAgeRating() != null) { if (metadata.getAgeRating() != null) {
metadataElement.appendChild(createBookloreMetaElement(doc, "age_rating", String.valueOf(metadata.getAgeRating()))); metadataElement.appendChild(createBookloreMetaElement(doc, "age_rating", String.valueOf(metadata.getAgeRating()), epub3));
} }
if (StringUtils.isNotBlank(metadata.getContentRating())) { if (StringUtils.isNotBlank(metadata.getContentRating())) {
metadataElement.appendChild(createBookloreMetaElement(doc, "content_rating", metadata.getContentRating())); metadataElement.appendChild(createBookloreMetaElement(doc, "content_rating", metadata.getContentRating(), epub3));
} }
} }
@@ -62,7 +62,7 @@ public class BookSimilarityService {
return round(score, 5); return round(score, 5);
} }
private Set<String> extractNames(Set<?> entities) { private Set<String> extractNames(Collection<?> entities) {
if (entities == null) return Collections.emptySet(); if (entities == null) return Collections.emptySet();
Set<String> names = new HashSet<>(); Set<String> names = new HashSet<>();
for (Object obj : entities) { for (Object obj : entities) {
@@ -52,13 +52,26 @@ public class MetadataChangeDetector {
private record CollectionFieldDescriptor( private record CollectionFieldDescriptor(
String name, String name,
Function<BookMetadata, Set<String>> dtoValueGetter, Function<BookMetadata, ? extends Collection<String>> dtoValueGetter,
Function<BookMetadataEntity, Set<?>> entityValueGetter, Function<BookMetadataEntity, ? extends Collection<?>> entityValueGetter,
Function<BookMetadata, Boolean> dtoLockGetter, Function<BookMetadata, Boolean> dtoLockGetter,
Function<BookMetadataEntity, Boolean> entityLockGetter, Function<BookMetadataEntity, Boolean> entityLockGetter,
Predicate<MetadataClearFlags> clearFlagGetter, Predicate<MetadataClearFlags> clearFlagGetter,
boolean includedInFileWrite boolean includedInFileWrite,
boolean orderSensitive
) { ) {
CollectionFieldDescriptor(
String name,
Function<BookMetadata, ? extends Collection<String>> dtoValueGetter,
Function<BookMetadataEntity, ? extends Collection<?>> entityValueGetter,
Function<BookMetadata, Boolean> dtoLockGetter,
Function<BookMetadataEntity, Boolean> entityLockGetter,
Predicate<MetadataClearFlags> clearFlagGetter,
boolean includedInFileWrite
) {
this(name, dtoValueGetter, entityValueGetter, dtoLockGetter, entityLockGetter, clearFlagGetter, includedInFileWrite, false);
}
boolean isUnlocked(BookMetadataEntity entity) { boolean isUnlocked(BookMetadataEntity entity) {
return !isTrue(entityLockGetter.apply(entity)); return !isTrue(entityLockGetter.apply(entity));
} }
@@ -67,11 +80,16 @@ public class MetadataChangeDetector {
return clearFlagGetter.test(flags); return clearFlagGetter.test(flags);
} }
Set<String> getNewValue(BookMetadata dto) { Object getNewValue(BookMetadata dto) {
return dtoValueGetter.apply(dto); Collection<String> values = dtoValueGetter.apply(dto);
if (values == null) return null;
return orderSensitive ? new ArrayList<>(values) : new HashSet<>(values);
} }
Set<String> getOldValue(BookMetadataEntity entity) { Object getOldValue(BookMetadataEntity entity) {
if (orderSensitive) {
return toNameList(entityValueGetter.apply(entity));
}
return toNameSet(entityValueGetter.apply(entity)); return toNameSet(entityValueGetter.apply(entity));
} }
@@ -231,7 +249,7 @@ public class MetadataChangeDetector {
new CollectionFieldDescriptor("authors", new CollectionFieldDescriptor("authors",
BookMetadata::getAuthors, BookMetadataEntity::getAuthors, BookMetadata::getAuthors, BookMetadataEntity::getAuthors,
BookMetadata::getAuthorsLocked, BookMetadataEntity::getAuthorsLocked, BookMetadata::getAuthorsLocked, BookMetadataEntity::getAuthorsLocked,
MetadataClearFlags::isAuthors, true), MetadataClearFlags::isAuthors, true, true),
new CollectionFieldDescriptor("categories", new CollectionFieldDescriptor("categories",
BookMetadata::getCategories, BookMetadataEntity::getCategories, BookMetadata::getCategories, BookMetadataEntity::getCategories,
BookMetadata::getCategoriesLocked, BookMetadataEntity::getCategoriesLocked, BookMetadata::getCategoriesLocked, BookMetadataEntity::getCategoriesLocked,
@@ -377,7 +395,22 @@ public class MetadataChangeDetector {
return !Objects.equals(normNew, normOld); return !Objects.equals(normNew, normOld);
} }
private static Set<String> toNameSet(Set<?> entities) { private static List<String> toNameList(Collection<?> entities) {
if (entities == null) {
return Collections.emptyList();
}
return entities.stream()
.map(e -> switch (e) {
case AuthorEntity author -> author.getName();
case CategoryEntity category -> category.getName();
case MoodEntity mood -> mood.getName();
case TagEntity tag -> tag.getName();
default -> e.toString();
})
.toList();
}
private static Set<String> toNameSet(Collection<?> entities) {
if (entities == null) { if (entities == null) {
return Collections.emptySet(); return Collections.emptySet();
} }
@@ -0,0 +1,19 @@
ALTER TABLE book_metadata_author_mapping
ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0;
-- Assign unique sort_order per book for existing rows
SET @prev_book := 0;
SET @pos := 0;
UPDATE book_metadata_author_mapping
SET sort_order = (@pos := IF(@prev_book = book_id, @pos + 1, 0)),
book_id = (@prev_book := book_id)
ORDER BY book_id, author_id;
-- Change PK from (book_id, author_id) to (book_id, sort_order)
ALTER TABLE book_metadata_author_mapping
DROP PRIMARY KEY,
ADD PRIMARY KEY (book_id, sort_order);
-- Keep an index on author_id for reverse lookups
CREATE INDEX IF NOT EXISTS idx_author_mapping_author_id ON book_metadata_author_mapping (book_id, author_id);
@@ -8,7 +8,7 @@ import org.booklore.util.PathPatternResolver;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.LinkedHashSet; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -38,12 +38,12 @@ class PathPatternResolverTest {
when(metadata.getAuthors()).thenReturn(null); when(metadata.getAuthors()).thenReturn(null);
} else { } else {
AtomicLong idCounter = new AtomicLong(1); AtomicLong idCounter = new AtomicLong(1);
LinkedHashSet<AuthorEntity> authorEntities = authors.stream().map(name -> { ArrayList<AuthorEntity> authorEntities = authors.stream().map(name -> {
AuthorEntity a = new AuthorEntity(); AuthorEntity a = new AuthorEntity();
a.setId(idCounter.getAndIncrement()); a.setId(idCounter.getAndIncrement());
a.setName(name); a.setName(name);
return a; return a;
}).collect(Collectors.toCollection(LinkedHashSet::new)); }).collect(Collectors.toCollection(ArrayList::new));
when(metadata.getAuthors()).thenReturn(authorEntities); when(metadata.getAuthors()).thenReturn(authorEntities);
} }
@@ -46,7 +46,7 @@ public class BookMetadataMapperTest {
entity.setHardcoverId("hc-id"); entity.setHardcoverId("hc-id");
entity.setHardcoverRating(4.5); entity.setHardcoverRating(4.5);
entity.setGoodreadsId("gr-id"); entity.setGoodreadsId("gr-id");
entity.setAuthors(new java.util.HashSet<>()); entity.setAuthors(new java.util.ArrayList<>());
entity.setCategories(new java.util.HashSet<>()); entity.setCategories(new java.util.HashSet<>());
entity.setMoods(new java.util.HashSet<>()); entity.setMoods(new java.util.HashSet<>());
entity.setTags(new java.util.HashSet<>()); entity.setTags(new java.util.HashSet<>());
@@ -463,7 +463,7 @@ class MobileSeriesServiceTest {
.seriesName(seriesName) .seriesName(seriesName)
.seriesNumber(seriesNumber) .seriesNumber(seriesNumber)
.coverUpdatedOn(Instant.now()) .coverUpdatedOn(Instant.now())
.authors(Set.of(author)) .authors(List.of(author))
.build(); .build();
BookFileEntity bookFile = BookFileEntity.builder() BookFileEntity bookFile = BookFileEntity.builder()
@@ -2,7 +2,7 @@ package org.booklore.model.entity;
import org.booklore.util.BookUtils; import org.booklore.util.BookUtils;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.Set; import java.util.List;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
class BookMetadataEntityTest { class BookMetadataEntityTest {
@@ -12,7 +12,7 @@ class BookMetadataEntityTest {
BookMetadataEntity metadata = new BookMetadataEntity(); BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("Jo Nesbø Book"); metadata.setTitle("Jo Nesbø Book");
metadata.setSubtitle("Murder Mystery"); metadata.setSubtitle("Murder Mystery");
metadata.setAuthors(Set.of(AuthorEntity.builder().name("Jo Nesbø").build())); metadata.setAuthors(List.of(AuthorEntity.builder().name("Jo Nesbø").build()));
metadata.updateSearchText(); metadata.updateSearchText();
@@ -27,7 +27,7 @@ class BookMetadataEntityTest {
void updateSearchText_normalizesAuthorWithDiacritics() { void updateSearchText_normalizesAuthorWithDiacritics() {
BookMetadataEntity metadata = new BookMetadataEntity(); BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("The Snowman"); metadata.setTitle("The Snowman");
metadata.setAuthors(Set.of(AuthorEntity.builder().name("Jo Nesbø").build())); metadata.setAuthors(List.of(AuthorEntity.builder().name("Jo Nesbø").build()));
metadata.updateSearchText(); metadata.updateSearchText();
@@ -44,7 +44,7 @@ class BookMetadataEntityTest {
metadata.setTitle("Müller's Café"); metadata.setTitle("Müller's Café");
metadata.setSubtitle("À la française"); metadata.setSubtitle("À la française");
metadata.setSeriesName("José's Stories"); metadata.setSeriesName("José's Stories");
metadata.setAuthors(Set.of( metadata.setAuthors(List.of(
AuthorEntity.builder().name("François Müller").build(), AuthorEntity.builder().name("François Müller").build(),
AuthorEntity.builder().name("José García").build() AuthorEntity.builder().name("José García").build()
)); ));
@@ -160,7 +160,7 @@ class BookMetadataEntityTest {
void searchSimulation_withDiacritics() { void searchSimulation_withDiacritics() {
BookMetadataEntity metadata = new BookMetadataEntity(); BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("The Bat"); metadata.setTitle("The Bat");
metadata.setAuthors(Set.of(AuthorEntity.builder().name("Jo Nesbø").build())); metadata.setAuthors(List.of(AuthorEntity.builder().name("Jo Nesbø").build()));
metadata.updateSearchText(); metadata.updateSearchText();
String storedSearchText = metadata.getSearchText(); String storedSearchText = metadata.getSearchText();
@@ -1031,13 +1031,13 @@ class BookRuleEvaluatorServiceIntegrationTest {
BookEntity book1 = createBook("Mistborn"); BookEntity book1 = createBook("Mistborn");
AuthorEntity author1 = AuthorEntity.builder().name("Brandon Sanderson").build(); AuthorEntity author1 = AuthorEntity.builder().name("Brandon Sanderson").build();
em.persist(author1); em.persist(author1);
book1.getMetadata().setAuthors(new HashSet<>(Set.of(author1))); book1.getMetadata().setAuthors(new ArrayList<>(List.of(author1)));
em.merge(book1.getMetadata()); em.merge(book1.getMetadata());
BookEntity book2 = createBook("It"); BookEntity book2 = createBook("It");
AuthorEntity author2 = AuthorEntity.builder().name("Stephen King").build(); AuthorEntity author2 = AuthorEntity.builder().name("Stephen King").build();
em.persist(author2); em.persist(author2);
book2.getMetadata().setAuthors(new HashSet<>(Set.of(author2))); book2.getMetadata().setAuthors(new ArrayList<>(List.of(author2)));
em.merge(book2.getMetadata()); em.merge(book2.getMetadata());
em.flush(); em.flush();
em.clear(); em.clear();
@@ -1089,7 +1089,7 @@ class BookRuleEvaluatorServiceIntegrationTest {
BookEntity withAuthors = createBook("With Authors Book"); BookEntity withAuthors = createBook("With Authors Book");
AuthorEntity author = AuthorEntity.builder().name("Test Author").build(); AuthorEntity author = AuthorEntity.builder().name("Test Author").build();
em.persist(author); em.persist(author);
withAuthors.getMetadata().setAuthors(new HashSet<>(Set.of(author))); withAuthors.getMetadata().setAuthors(new ArrayList<>(List.of(author)));
em.merge(withAuthors.getMetadata()); em.merge(withAuthors.getMetadata());
em.flush(); em.flush();
em.clear(); em.clear();
@@ -1106,7 +1106,7 @@ class BookRuleEvaluatorServiceIntegrationTest {
BookEntity withAuthors = createBook("With Authors Book"); BookEntity withAuthors = createBook("With Authors Book");
AuthorEntity author = AuthorEntity.builder().name("Test Author 2").build(); AuthorEntity author = AuthorEntity.builder().name("Test Author 2").build();
em.persist(author); em.persist(author);
withAuthors.getMetadata().setAuthors(new HashSet<>(Set.of(author))); withAuthors.getMetadata().setAuthors(new ArrayList<>(List.of(author)));
em.merge(withAuthors.getMetadata()); em.merge(withAuthors.getMetadata());
em.flush(); em.flush();
em.clear(); em.clear();
@@ -1160,19 +1160,19 @@ class BookRuleEvaluatorServiceIntegrationTest {
BookEntity bookA = createBook("Book A"); BookEntity bookA = createBook("Book A");
AuthorEntity authorA = AuthorEntity.builder().name("Author A").build(); AuthorEntity authorA = AuthorEntity.builder().name("Author A").build();
em.persist(authorA); em.persist(authorA);
bookA.getMetadata().setAuthors(new HashSet<>(Set.of(authorA))); bookA.getMetadata().setAuthors(new ArrayList<>(List.of(authorA)));
em.merge(bookA.getMetadata()); em.merge(bookA.getMetadata());
BookEntity bookB = createBook("Book B"); BookEntity bookB = createBook("Book B");
AuthorEntity authorB = AuthorEntity.builder().name("Author B").build(); AuthorEntity authorB = AuthorEntity.builder().name("Author B").build();
em.persist(authorB); em.persist(authorB);
bookB.getMetadata().setAuthors(new HashSet<>(Set.of(authorB))); bookB.getMetadata().setAuthors(new ArrayList<>(List.of(authorB)));
em.merge(bookB.getMetadata()); em.merge(bookB.getMetadata());
BookEntity bookC = createBook("Book C"); BookEntity bookC = createBook("Book C");
AuthorEntity authorC = AuthorEntity.builder().name("Author C").build(); AuthorEntity authorC = AuthorEntity.builder().name("Author C").build();
em.persist(authorC); em.persist(authorC);
bookC.getMetadata().setAuthors(new HashSet<>(Set.of(authorC))); bookC.getMetadata().setAuthors(new ArrayList<>(List.of(authorC)));
em.merge(bookC.getMetadata()); em.merge(bookC.getMetadata());
em.flush(); em.flush();
em.clear(); em.clear();
@@ -1187,19 +1187,19 @@ class BookRuleEvaluatorServiceIntegrationTest {
BookEntity bookA = createBook("Book A2"); BookEntity bookA = createBook("Book A2");
AuthorEntity authorA = AuthorEntity.builder().name("Author A2").build(); AuthorEntity authorA = AuthorEntity.builder().name("Author A2").build();
em.persist(authorA); em.persist(authorA);
bookA.getMetadata().setAuthors(new HashSet<>(Set.of(authorA))); bookA.getMetadata().setAuthors(new ArrayList<>(List.of(authorA)));
em.merge(bookA.getMetadata()); em.merge(bookA.getMetadata());
BookEntity bookB = createBook("Book B2"); BookEntity bookB = createBook("Book B2");
AuthorEntity authorB = AuthorEntity.builder().name("Author B2").build(); AuthorEntity authorB = AuthorEntity.builder().name("Author B2").build();
em.persist(authorB); em.persist(authorB);
bookB.getMetadata().setAuthors(new HashSet<>(Set.of(authorB))); bookB.getMetadata().setAuthors(new ArrayList<>(List.of(authorB)));
em.merge(bookB.getMetadata()); em.merge(bookB.getMetadata());
BookEntity bookC = createBook("Book C2"); BookEntity bookC = createBook("Book C2");
AuthorEntity authorC = AuthorEntity.builder().name("Author C2").build(); AuthorEntity authorC = AuthorEntity.builder().name("Author C2").build();
em.persist(authorC); em.persist(authorC);
bookC.getMetadata().setAuthors(new HashSet<>(Set.of(authorC))); bookC.getMetadata().setAuthors(new ArrayList<>(List.of(authorC)));
em.merge(bookC.getMetadata()); em.merge(bookC.getMetadata());
em.flush(); em.flush();
em.clear(); em.clear();
@@ -1216,13 +1216,13 @@ class BookRuleEvaluatorServiceIntegrationTest {
AuthorEntity authorY = AuthorEntity.builder().name("Author Y").build(); AuthorEntity authorY = AuthorEntity.builder().name("Author Y").build();
em.persist(authorX); em.persist(authorX);
em.persist(authorY); em.persist(authorY);
bookBoth.getMetadata().setAuthors(new HashSet<>(Set.of(authorX, authorY))); bookBoth.getMetadata().setAuthors(new ArrayList<>(List.of(authorX, authorY)));
em.merge(bookBoth.getMetadata()); em.merge(bookBoth.getMetadata());
BookEntity bookOne = createBook("Book One Author"); BookEntity bookOne = createBook("Book One Author");
AuthorEntity authorX2 = AuthorEntity.builder().name("Author X2").build(); AuthorEntity authorX2 = AuthorEntity.builder().name("Author X2").build();
em.persist(authorX2); em.persist(authorX2);
bookOne.getMetadata().setAuthors(new HashSet<>(Set.of(authorX2))); bookOne.getMetadata().setAuthors(new ArrayList<>(List.of(authorX2)));
em.merge(bookOne.getMetadata()); em.merge(bookOne.getMetadata());
em.flush(); em.flush();
em.clear(); em.clear();
@@ -1598,7 +1598,7 @@ class BookRuleEvaluatorServiceIntegrationTest {
BookEntity withAuthors = createBook("With Authors"); BookEntity withAuthors = createBook("With Authors");
AuthorEntity author = AuthorEntity.builder().name("Test Author MP").build(); AuthorEntity author = AuthorEntity.builder().name("Test Author MP").build();
em.persist(author); em.persist(author);
withAuthors.getMetadata().setAuthors(new HashSet<>(Set.of(author))); withAuthors.getMetadata().setAuthors(new ArrayList<>(List.of(author)));
em.merge(withAuthors.getMetadata()); em.merge(withAuthors.getMetadata());
BookEntity noAuthors = createBook("No Authors"); BookEntity noAuthors = createBook("No Authors");
@@ -1615,7 +1615,7 @@ class BookRuleEvaluatorServiceIntegrationTest {
BookEntity withAuthors = createBook("With Authors"); BookEntity withAuthors = createBook("With Authors");
AuthorEntity author = AuthorEntity.builder().name("Test Author MP2").build(); AuthorEntity author = AuthorEntity.builder().name("Test Author MP2").build();
em.persist(author); em.persist(author);
withAuthors.getMetadata().setAuthors(new HashSet<>(Set.of(author))); withAuthors.getMetadata().setAuthors(new ArrayList<>(List.of(author)));
em.merge(withAuthors.getMetadata()); em.merge(withAuthors.getMetadata());
BookEntity noAuthors = createBook("No Authors"); BookEntity noAuthors = createBook("No Authors");
@@ -14,7 +14,9 @@ import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@@ -173,7 +175,7 @@ class BookCreatorServiceTest {
@Test @Test
void addAuthorsToBook_existingAuthorsOnEntity_appendsWithoutOverwriting() { void addAuthorsToBook_existingAuthorsOnEntity_appendsWithoutOverwriting() {
AuthorEntity existingAuthor = AuthorEntity.builder().name("Existing").build(); AuthorEntity existingAuthor = AuthorEntity.builder().name("Existing").build();
bookEntity.getMetadata().setAuthors(new HashSet<>(Set.of(existingAuthor))); bookEntity.getMetadata().setAuthors(new ArrayList<>(List.of(existingAuthor)));
AuthorEntity newAuthor = AuthorEntity.builder().name("New Author").build(); AuthorEntity newAuthor = AuthorEntity.builder().name("New Author").build();
when(authorRepository.findByName("New Author")).thenReturn(Optional.of(newAuthor)); when(authorRepository.findByName("New Author")).thenReturn(Optional.of(newAuthor));
@@ -61,7 +61,7 @@ class DuplicateDetectionServiceTest {
.bookType(fileType) .bookType(fileType)
.build(); .build();
Set<AuthorEntity> authors = new HashSet<>(); List<AuthorEntity> authors = new ArrayList<>();
if (authorName != null) { if (authorName != null) {
authors.add(AuthorEntity.builder().id(id * 10).name(authorName).build()); authors.add(AuthorEntity.builder().id(id * 10).name(authorName).build());
} }
@@ -388,9 +388,9 @@ class DuplicateDetectionServiceTest {
@Test @Test
void skipsBooksWithNoAuthors() { void skipsBooksWithNoAuthors() {
BookEntity book1 = createBook(BookFileType.EPUB, "Orphan Book", null); BookEntity book1 = createBook(BookFileType.EPUB, "Orphan Book", null);
book1.getMetadata().setAuthors(new HashSet<>()); book1.getMetadata().setAuthors(new ArrayList<>());
BookEntity book2 = createBook(BookFileType.MOBI, "Orphan Book", null); BookEntity book2 = createBook(BookFileType.MOBI, "Orphan Book", null);
book2.getMetadata().setAuthors(new HashSet<>()); book2.getMetadata().setAuthors(new ArrayList<>());
stubBooks(book1, book2); stubBooks(book1, book2);
List<DuplicateGroup> result = service.findDuplicates(onlyTitleAuthor()); List<DuplicateGroup> result = service.findDuplicates(onlyTitleAuthor());
@@ -438,7 +438,7 @@ class DuplicateDetectionServiceTest {
void requiresAtLeastTwoBooksWithAuthorsInTitleGroup() { void requiresAtLeastTwoBooksWithAuthorsInTitleGroup() {
BookEntity book1 = createBook(BookFileType.EPUB, "Solo Title", "Author A"); BookEntity book1 = createBook(BookFileType.EPUB, "Solo Title", "Author A");
BookEntity book2 = createBook(BookFileType.MOBI, "Solo Title", null); BookEntity book2 = createBook(BookFileType.MOBI, "Solo Title", null);
book2.getMetadata().setAuthors(new HashSet<>()); book2.getMetadata().setAuthors(new ArrayList<>());
stubBooks(book1, book2); stubBooks(book1, book2);
List<DuplicateGroup> result = service.findDuplicates(onlyTitleAuthor()); List<DuplicateGroup> result = service.findDuplicates(onlyTitleAuthor());
@@ -87,7 +87,7 @@ class BookdropBulkEditServiceTest {
@Test @Test
void bulkEdit_WithArrayFieldsMergeMode_ShouldMergeArrays() { void bulkEdit_WithArrayFieldsMergeMode_ShouldMergeArrays() {
BookMetadata existingMetadata = new BookMetadata(); BookMetadata existingMetadata = new BookMetadata();
existingMetadata.setAuthors(new LinkedHashSet<>(List.of("Author 1"))); existingMetadata.setAuthors(new ArrayList<>(List.of("Author 1")));
existingMetadata.setCategories(new LinkedHashSet<>(List.of("Category 1"))); existingMetadata.setCategories(new LinkedHashSet<>(List.of("Category 1")));
when(metadataHelper.getCurrentMetadata(any())).thenReturn(existingMetadata); when(metadataHelper.getCurrentMetadata(any())).thenReturn(existingMetadata);
@@ -100,7 +100,7 @@ class BookdropBulkEditServiceTest {
.thenReturn(List.of(file)); .thenReturn(List.of(file));
BookMetadata updates = new BookMetadata(); BookMetadata updates = new BookMetadata();
updates.setAuthors(new LinkedHashSet<>(List.of("Author 2"))); updates.setAuthors(new ArrayList<>(List.of("Author 2")));
updates.setCategories(new LinkedHashSet<>(List.of("Category 2"))); updates.setCategories(new LinkedHashSet<>(List.of("Category 2")));
BookdropBulkEditRequest request = new BookdropBulkEditRequest(); BookdropBulkEditRequest request = new BookdropBulkEditRequest();
@@ -129,7 +129,7 @@ class BookdropBulkEditServiceTest {
@Test @Test
void bulkEdit_WithArrayFieldsReplaceMode_ShouldReplaceArrays() { void bulkEdit_WithArrayFieldsReplaceMode_ShouldReplaceArrays() {
BookMetadata existingMetadata = new BookMetadata(); BookMetadata existingMetadata = new BookMetadata();
existingMetadata.setAuthors(new LinkedHashSet<>(List.of("Author 1"))); existingMetadata.setAuthors(new ArrayList<>(List.of("Author 1")));
when(metadataHelper.getCurrentMetadata(any())).thenReturn(existingMetadata); when(metadataHelper.getCurrentMetadata(any())).thenReturn(existingMetadata);
@@ -141,7 +141,7 @@ class BookdropBulkEditServiceTest {
.thenReturn(List.of(file)); .thenReturn(List.of(file));
BookMetadata updates = new BookMetadata(); BookMetadata updates = new BookMetadata();
updates.setAuthors(new LinkedHashSet<>(List.of("Author 2"))); updates.setAuthors(new ArrayList<>(List.of("Author 2")));
BookdropBulkEditRequest request = new BookdropBulkEditRequest(); BookdropBulkEditRequest request = new BookdropBulkEditRequest();
request.setFields(updates); request.setFields(updates);
@@ -83,7 +83,7 @@ class FilenamePatternExtractorTest {
BookMetadata result = extractor.extractFromFilename(filename, pattern); BookMetadata result = extractor.extractFromFilename(filename, pattern);
assertNotNull(result); assertNotNull(result);
assertEquals(Set.of("John Smith"), result.getAuthors()); assertEquals(List.of("John Smith"), result.getAuthors());
assertEquals("The Lost City", result.getTitle()); assertEquals("The Lost City", result.getTitle());
} }
@@ -288,7 +288,7 @@ class FilenamePatternExtractorTest {
assertEquals("Chronicles of Earth", result.getSeriesName()); assertEquals("Chronicles of Earth", result.getSeriesName());
assertEquals(7.0f, result.getSeriesNumber()); assertEquals(7.0f, result.getSeriesNumber());
assertEquals("The Final Battle", result.getTitle()); assertEquals("The Final Battle", result.getTitle());
assertEquals(Set.of("John Smith"), result.getAuthors()); assertEquals(List.of("John Smith"), result.getAuthors());
} }
@Test @Test
@@ -299,7 +299,7 @@ class FilenamePatternExtractorTest {
BookMetadata result = extractor.extractFromFilename(filename, pattern); BookMetadata result = extractor.extractFromFilename(filename, pattern);
assertNotNull(result); assertNotNull(result);
assertEquals(Set.of("John Smith"), result.getAuthors()); assertEquals(List.of("John Smith"), result.getAuthors());
assertEquals("The Lost City", result.getTitle()); assertEquals("The Lost City", result.getTitle());
assertEquals(1949, result.getPublishedDate().getYear()); assertEquals(1949, result.getPublishedDate().getYear());
} }
@@ -312,7 +312,7 @@ class FilenamePatternExtractorTest {
BookMetadata result = extractor.extractFromFilename(filename, pattern); BookMetadata result = extractor.extractFromFilename(filename, pattern);
assertNotNull(result); assertNotNull(result);
assertEquals(Set.of("Smith", "John R."), result.getAuthors()); assertEquals(List.of("Smith", "John R."), result.getAuthors());
assertEquals("The Lost City", result.getTitle()); assertEquals("The Lost City", result.getTitle());
} }
@@ -354,7 +354,7 @@ class FilenamePatternExtractorTest {
assertEquals("Chronicles of Earth", result.getSeriesName()); assertEquals("Chronicles of Earth", result.getSeriesName());
assertEquals(1.0f, result.getSeriesNumber()); assertEquals(1.0f, result.getSeriesNumber());
assertEquals("The Beginning", result.getTitle()); assertEquals("The Beginning", result.getTitle());
assertEquals(Set.of("John Smith"), result.getAuthors()); assertEquals(List.of("John Smith"), result.getAuthors());
} }
// ===== New Placeholder Tests ===== // ===== New Placeholder Tests =====
@@ -666,7 +666,7 @@ class FilenamePatternExtractorTest {
assertNotNull(result); assertNotNull(result);
assertEquals("The Lost City", result.getTitle()); assertEquals("The Lost City", result.getTitle());
assertEquals(Set.of("John Smith"), result.getAuthors()); assertEquals(List.of("John Smith"), result.getAuthors());
} }
@Test @Test
@@ -360,7 +360,7 @@ class BookCoverServiceTest {
void generatesCoverWithTitleAndAuthor() { void generatesCoverWithTitleAndAuthor() {
BookEntity book = buildBook(1L, false); BookEntity book = buildBook(1L, false);
AuthorEntity author = AuthorEntity.builder().name("Jane Doe").build(); AuthorEntity author = AuthorEntity.builder().name("Jane Doe").build();
book.getMetadata().setAuthors(Set.of(author)); book.getMetadata().setAuthors(List.of(author));
book.setBookFiles(new ArrayList<>()); book.setBookFiles(new ArrayList<>());
when(bookRepository.findById(1L)).thenReturn(Optional.of(book)); when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(coverImageGenerator.generateCover("Test Book", "Jane Doe")).thenReturn(new byte[]{1, 2, 3}); when(coverImageGenerator.generateCover("Test Book", "Jane Doe")).thenReturn(new byte[]{1, 2, 3});
@@ -598,7 +598,7 @@ class BookCoverServiceTest {
void successfullyGeneratesCustomAudiobookCover() { void successfullyGeneratesCustomAudiobookCover() {
BookEntity book = buildBookWithAudiobookLock(1L, false); BookEntity book = buildBookWithAudiobookLock(1L, false);
AuthorEntity author = AuthorEntity.builder().name("Author Name").build(); AuthorEntity author = AuthorEntity.builder().name("Author Name").build();
book.getMetadata().setAuthors(Set.of(author)); book.getMetadata().setAuthors(List.of(author));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book)); when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(coverImageGenerator.generateSquareCover("Test Audiobook", "Author Name")).thenReturn(new byte[]{1, 2}); when(coverImageGenerator.generateSquareCover("Test Audiobook", "Author Name")).thenReturn(new byte[]{1, 2});
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of()); when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
@@ -986,7 +986,7 @@ class BookCoverServiceTest {
@Test @Test
void returnsNullForEmptyAuthors() { void returnsNullForEmptyAuthors() {
BookEntity book = buildBook(1L, false); BookEntity book = buildBook(1L, false);
book.getMetadata().setAuthors(new HashSet<>()); book.getMetadata().setAuthors(new ArrayList<>());
when(bookRepository.findById(1L)).thenReturn(Optional.of(book)); when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(coverImageGenerator.generateCover("Test Book", null)).thenReturn(new byte[]{1}); when(coverImageGenerator.generateCover("Test Book", null)).thenReturn(new byte[]{1});
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of()); when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
@@ -999,7 +999,7 @@ class BookCoverServiceTest {
@Test @Test
void joinsMultipleAuthorNames() { void joinsMultipleAuthorNames() {
BookEntity book = buildBook(1L, false); BookEntity book = buildBook(1L, false);
Set<AuthorEntity> authors = new LinkedHashSet<>(); List<AuthorEntity> authors = new ArrayList<>();
authors.add(AuthorEntity.builder().name("Alice").build()); authors.add(AuthorEntity.builder().name("Alice").build());
authors.add(AuthorEntity.builder().name("Bob").build()); authors.add(AuthorEntity.builder().name("Bob").build());
book.getMetadata().setAuthors(authors); book.getMetadata().setAuthors(authors);
@@ -67,7 +67,7 @@ class BookMetadataUpdaterTest {
metadataEntity = BookMetadataEntity.builder() metadataEntity = BookMetadataEntity.builder()
.bookId(1L) .bookId(1L)
.title("Original Title") .title("Original Title")
.authors(new HashSet<>()) .authors(new ArrayList<>())
.categories(new HashSet<>()) .categories(new HashSet<>())
.moods(new HashSet<>()) .moods(new HashSet<>())
.tags(new HashSet<>()) .tags(new HashSet<>())
@@ -331,12 +331,12 @@ class BookMetadataUpdaterTest {
@Test @Test
void setBookMetadata_authorsReplaceAll_replacesExisting() { void setBookMetadata_authorsReplaceAll_replacesExisting() {
AuthorEntity existing = AuthorEntity.builder().id(1L).name("Old Author").build(); AuthorEntity existing = AuthorEntity.builder().id(1L).name("Old Author").build();
metadataEntity.setAuthors(new HashSet<>(Set.of(existing))); metadataEntity.setAuthors(new ArrayList<>(List.of(existing)));
AuthorEntity newAuthor = AuthorEntity.builder().id(2L).name("New Author").build(); AuthorEntity newAuthor = AuthorEntity.builder().id(2L).name("New Author").build();
when(authorRepository.findByName("New Author")).thenReturn(Optional.of(newAuthor)); when(authorRepository.findByName("New Author")).thenReturn(Optional.of(newAuthor));
BookMetadata newMeta = BookMetadata.builder().title("T").authors(Set.of("New Author")).build(); BookMetadata newMeta = BookMetadata.builder().title("T").authors(List.of("New Author")).build();
MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_ALL); MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_ALL);
try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) { try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) {
@@ -351,9 +351,9 @@ class BookMetadataUpdaterTest {
@Test @Test
void setBookMetadata_authorsReplaceMissing_skipsWhenExistingAuthorsPresent() { void setBookMetadata_authorsReplaceMissing_skipsWhenExistingAuthorsPresent() {
AuthorEntity existing = AuthorEntity.builder().id(1L).name("Existing").build(); AuthorEntity existing = AuthorEntity.builder().id(1L).name("Existing").build();
metadataEntity.setAuthors(new HashSet<>(Set.of(existing))); metadataEntity.setAuthors(new ArrayList<>(List.of(existing)));
BookMetadata newMeta = BookMetadata.builder().title("T").authors(Set.of("New Author")).build(); BookMetadata newMeta = BookMetadata.builder().title("T").authors(List.of("New Author")).build();
MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_MISSING); MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_MISSING);
try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) { try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) {
@@ -367,11 +367,11 @@ class BookMetadataUpdaterTest {
@Test @Test
void setBookMetadata_authorsReplaceMissing_addsWhenEmpty() { void setBookMetadata_authorsReplaceMissing_addsWhenEmpty() {
metadataEntity.setAuthors(new HashSet<>()); metadataEntity.setAuthors(new ArrayList<>());
AuthorEntity newAuthor = AuthorEntity.builder().id(2L).name("New").build(); AuthorEntity newAuthor = AuthorEntity.builder().id(2L).name("New").build();
when(authorRepository.findByName("New")).thenReturn(Optional.of(newAuthor)); when(authorRepository.findByName("New")).thenReturn(Optional.of(newAuthor));
BookMetadata newMeta = BookMetadata.builder().title("T").authors(Set.of("New")).build(); BookMetadata newMeta = BookMetadata.builder().title("T").authors(List.of("New")).build();
MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_MISSING); MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_MISSING);
try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) { try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) {
@@ -387,9 +387,9 @@ class BookMetadataUpdaterTest {
void setBookMetadata_authorsLocked_notUpdated() { void setBookMetadata_authorsLocked_notUpdated() {
metadataEntity.setAuthorsLocked(true); metadataEntity.setAuthorsLocked(true);
AuthorEntity existing = AuthorEntity.builder().id(1L).name("Locked").build(); AuthorEntity existing = AuthorEntity.builder().id(1L).name("Locked").build();
metadataEntity.setAuthors(new HashSet<>(Set.of(existing))); metadataEntity.setAuthors(new ArrayList<>(List.of(existing)));
BookMetadata newMeta = BookMetadata.builder().title("T").authors(Set.of("New Author")).build(); BookMetadata newMeta = BookMetadata.builder().title("T").authors(List.of("New Author")).build();
MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_ALL); MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_ALL);
try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) { try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) {
@@ -404,7 +404,7 @@ class BookMetadataUpdaterTest {
@Test @Test
void setBookMetadata_clearAuthors_clearsSet() { void setBookMetadata_clearAuthors_clearsSet() {
AuthorEntity existing = AuthorEntity.builder().id(1L).name("Author").build(); AuthorEntity existing = AuthorEntity.builder().id(1L).name("Author").build();
metadataEntity.setAuthors(new HashSet<>(Set.of(existing))); metadataEntity.setAuthors(new ArrayList<>(List.of(existing)));
BookMetadata newMeta = BookMetadata.builder().title("T").build(); BookMetadata newMeta = BookMetadata.builder().title("T").build();
MetadataClearFlags clearFlags = new MetadataClearFlags(); MetadataClearFlags clearFlags = new MetadataClearFlags();
@@ -528,9 +528,9 @@ class BookMetadataUpdaterTest {
@Test @Test
void setBookMetadata_authorsReplaceAll_emptyNewAuthors_clearsExisting() { void setBookMetadata_authorsReplaceAll_emptyNewAuthors_clearsExisting() {
AuthorEntity existing = AuthorEntity.builder().id(1L).name("Author").build(); AuthorEntity existing = AuthorEntity.builder().id(1L).name("Author").build();
metadataEntity.setAuthors(new HashSet<>(Set.of(existing))); metadataEntity.setAuthors(new ArrayList<>(List.of(existing)));
BookMetadata newMeta = BookMetadata.builder().title("T").authors(Set.of()).build(); BookMetadata newMeta = BookMetadata.builder().title("T").authors(List.of()).build();
MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_ALL); MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_ALL);
try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) { try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) {
@@ -544,12 +544,12 @@ class BookMetadataUpdaterTest {
@Test @Test
void setBookMetadata_createsNewAuthorWhenNotFound() { void setBookMetadata_createsNewAuthorWhenNotFound() {
metadataEntity.setAuthors(new HashSet<>()); metadataEntity.setAuthors(new ArrayList<>());
AuthorEntity created = AuthorEntity.builder().id(5L).name("Brand New").build(); AuthorEntity created = AuthorEntity.builder().id(5L).name("Brand New").build();
when(authorRepository.findByName("Brand New")).thenReturn(Optional.empty()); when(authorRepository.findByName("Brand New")).thenReturn(Optional.empty());
when(authorRepository.save(any(AuthorEntity.class))).thenReturn(created); when(authorRepository.save(any(AuthorEntity.class))).thenReturn(created);
BookMetadata newMeta = BookMetadata.builder().title("T").authors(Set.of("Brand New")).build(); BookMetadata newMeta = BookMetadata.builder().title("T").authors(List.of("Brand New")).build();
MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_ALL); MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_ALL);
try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) { try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) {
@@ -1460,12 +1460,12 @@ class BookMetadataUpdaterTest {
@Test @Test
void authors_nullReplaceMode_noMerge_replacesExisting() { void authors_nullReplaceMode_noMerge_replacesExisting() {
AuthorEntity existing = AuthorEntity.builder().id(1L).name("Old").build(); AuthorEntity existing = AuthorEntity.builder().id(1L).name("Old").build();
metadataEntity.setAuthors(new HashSet<>(Set.of(existing))); metadataEntity.setAuthors(new ArrayList<>(List.of(existing)));
AuthorEntity newAuthor = AuthorEntity.builder().id(2L).name("New").build(); AuthorEntity newAuthor = AuthorEntity.builder().id(2L).name("New").build();
when(authorRepository.findByName("New")).thenReturn(Optional.of(newAuthor)); when(authorRepository.findByName("New")).thenReturn(Optional.of(newAuthor));
BookMetadata newMeta = BookMetadata.builder().title("T").authors(Set.of("New")).build(); BookMetadata newMeta = BookMetadata.builder().title("T").authors(List.of("New")).build();
MetadataUpdateContext context = buildContext(newMeta, null); MetadataUpdateContext context = buildContext(newMeta, null);
try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) { try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) {
@@ -65,7 +65,7 @@ class MetadataManagementServiceTest {
when(authorRepository.save(targetAuthor)).thenReturn(targetAuthor); when(authorRepository.save(targetAuthor)).thenReturn(targetAuthor);
when(authorRepository.findByNameIgnoreCase("Old Author")).thenReturn(Optional.of(oldAuthor)); when(authorRepository.findByNameIgnoreCase("Old Author")).thenReturn(Optional.of(oldAuthor));
Set<AuthorEntity> authors = new HashSet<>(List.of(oldAuthor)); List<AuthorEntity> authors = new ArrayList<>(List.of(oldAuthor));
BookMetadataEntity metadata = BookMetadataEntity.builder().authors(authors).build(); BookMetadataEntity metadata = BookMetadataEntity.builder().authors(authors).build();
when(bookMetadataRepository.findAllByAuthorsContaining(oldAuthor)).thenReturn(List.of(metadata)); when(bookMetadataRepository.findAllByAuthorsContaining(oldAuthor)).thenReturn(List.of(metadata));
@@ -86,7 +86,7 @@ class MetadataManagementServiceTest {
when(authorRepository.save(any(AuthorEntity.class))).thenReturn(newAuthor); when(authorRepository.save(any(AuthorEntity.class))).thenReturn(newAuthor);
when(authorRepository.findByNameIgnoreCase("Old")).thenReturn(Optional.of(oldAuthor)); when(authorRepository.findByNameIgnoreCase("Old")).thenReturn(Optional.of(oldAuthor));
Set<AuthorEntity> authors = new HashSet<>(List.of(oldAuthor)); List<AuthorEntity> authors = new ArrayList<>(List.of(oldAuthor));
BookMetadataEntity metadata = BookMetadataEntity.builder().authors(authors).build(); BookMetadataEntity metadata = BookMetadataEntity.builder().authors(authors).build();
when(bookMetadataRepository.findAllByAuthorsContaining(oldAuthor)).thenReturn(List.of(metadata)); when(bookMetadataRepository.findAllByAuthorsContaining(oldAuthor)).thenReturn(List.of(metadata));
@@ -234,7 +234,7 @@ class MetadataManagementServiceTest {
.libraryPath(libraryPath) .libraryPath(libraryPath)
.build(); .build();
BookMetadataEntity metadata = BookMetadataEntity.builder() BookMetadataEntity metadata = BookMetadataEntity.builder()
.authors(new HashSet<>(List.of(oldAuthor))) .authors(new ArrayList<>(List.of(oldAuthor)))
.book(book) .book(book)
.build(); .build();
book.setMetadata(metadata); book.setMetadata(metadata);
@@ -295,7 +295,7 @@ class MetadataManagementServiceTest {
.libraryPath(libraryPath) .libraryPath(libraryPath)
.build(); .build();
BookMetadataEntity metadata = BookMetadataEntity.builder() BookMetadataEntity metadata = BookMetadataEntity.builder()
.authors(new HashSet<>(List.of(oldAuthor))) .authors(new ArrayList<>(List.of(oldAuthor)))
.book(book) .book(book)
.build(); .build();
book.setMetadata(metadata); book.setMetadata(metadata);
@@ -322,7 +322,7 @@ class MetadataManagementServiceTest {
AuthorEntity author = AuthorEntity.builder().id(1L).name("Author1").build(); AuthorEntity author = AuthorEntity.builder().id(1L).name("Author1").build();
when(authorRepository.findByName("Author1")).thenReturn(Optional.of(author)); when(authorRepository.findByName("Author1")).thenReturn(Optional.of(author));
Set<AuthorEntity> authors = new HashSet<>(List.of(author)); List<AuthorEntity> authors = new ArrayList<>(List.of(author));
BookMetadataEntity metadata = BookMetadataEntity.builder().authors(authors).build(); BookMetadataEntity metadata = BookMetadataEntity.builder().authors(authors).build();
when(bookMetadataRepository.findAllByAuthorsContaining(author)).thenReturn(List.of(metadata)); when(bookMetadataRepository.findAllByAuthorsContaining(author)).thenReturn(List.of(metadata));
@@ -531,7 +531,7 @@ class MetadataManagementServiceTest {
.libraryPath(libraryPath) .libraryPath(libraryPath)
.build(); .build();
BookMetadataEntity metadata = BookMetadataEntity.builder() BookMetadataEntity metadata = BookMetadataEntity.builder()
.authors(new HashSet<>(List.of(oldAuthor))) .authors(new ArrayList<>(List.of(oldAuthor)))
.book(book) .book(book)
.build(); .build();
book.setMetadata(metadata); book.setMetadata(metadata);
@@ -18,6 +18,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -153,7 +154,7 @@ class MetadataMatchServiceTest {
BookMetadataEntity metadata = BookMetadataEntity.builder() BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Title") .title("Title")
.description("Desc") .description("Desc")
.authors(Set.of(AuthorEntity.builder().name("Author").build())) .authors(List.of(AuthorEntity.builder().name("Author").build()))
.build(); .build();
BookEntity book = bookWith(metadata); BookEntity book = bookWith(metadata);
@@ -171,7 +172,7 @@ class MetadataMatchServiceTest {
.title("Title") .title("Title")
.subtitle("Subtitle") .subtitle("Subtitle")
.description("Description") .description("Description")
.authors(Set.of(AuthorEntity.builder().name("Author").build())) .authors(List.of(AuthorEntity.builder().name("Author").build()))
.publisher("Publisher") .publisher("Publisher")
.publishedDate(LocalDate.now()) .publishedDate(LocalDate.now())
.seriesName("Series") .seriesName("Series")
@@ -261,7 +262,7 @@ class MetadataMatchServiceTest {
.build(); .build();
stubWeights(weights); stubWeights(weights);
BookEntity book = bookWith(BookMetadataEntity.builder().authors(new HashSet<>()).build()); BookEntity book = bookWith(BookMetadataEntity.builder().authors(new ArrayList<>()).build());
assertThat(service.calculateMatchScore(book)).isEqualTo(0f); assertThat(service.calculateMatchScore(book)).isEqualTo(0f);
} }
} }
@@ -367,7 +368,7 @@ class MetadataMatchServiceTest {
stubWeights(weights); stubWeights(weights);
BookEntity book = bookWith(BookMetadataEntity.builder() BookEntity book = bookWith(BookMetadataEntity.builder()
.authors(new HashSet<>()) .authors(new ArrayList<>())
.authorsLocked(true) .authorsLocked(true)
.build()); .build());
@@ -587,7 +587,7 @@ class MetadataRefreshServiceTest {
@Test @Test
void resolveFieldAsList_returnsNullWhenFieldProviderNull() { void resolveFieldAsList_returnsNullWhenFieldProviderNull() {
Map<MetadataProvider, BookMetadata> metadataMap = new HashMap<>(); Map<MetadataProvider, BookMetadata> metadataMap = new HashMap<>();
Set<String> result = service.resolveFieldAsList(metadataMap, null, BookMetadata::getCategories); List<String> result = service.resolveFieldAsList(metadataMap, null, BookMetadata::getCategories);
assertThat(result).isNull(); assertThat(result).isNull();
} }
@@ -602,7 +602,7 @@ class MetadataRefreshServiceTest {
.p2(MetadataProvider.Google) .p2(MetadataProvider.Google)
.build(); .build();
Set<String> result = service.resolveFieldAsList(metadataMap, fp, BookMetadata::getCategories); List<String> result = service.resolveFieldAsList(metadataMap, fp, BookMetadata::getCategories);
assertThat(result).containsExactly("Cat"); assertThat(result).containsExactly("Cat");
} }
@@ -1048,7 +1048,7 @@ class MetadataRefreshServiceTest {
.subtitle("Sub") .subtitle("Sub")
.description("Desc") .description("Desc")
.publisher("Pub") .publisher("Pub")
.authors(Set.of("Auth")) .authors(List.of("Auth"))
.publishedDate(java.time.LocalDate.of(2020, 1, 1)) .publishedDate(java.time.LocalDate.of(2020, 1, 1))
.seriesName("Series") .seriesName("Series")
.seriesNumber(1.0f) .seriesNumber(1.0f)
@@ -1092,7 +1092,7 @@ class MetadataRefreshServiceTest {
metadataMap.put(MetadataProvider.Amazon, BookMetadata.builder() metadataMap.put(MetadataProvider.Amazon, BookMetadata.builder()
.subtitle("Amazon Sub") .subtitle("Amazon Sub")
.description("Amazon Desc") .description("Amazon Desc")
.authors(Set.of("Author A")) .authors(List.of("Author A"))
.publisher("Amazon Pub") .publisher("Amazon Pub")
.publishedDate(java.time.LocalDate.of(2021, 6, 15)) .publishedDate(java.time.LocalDate.of(2021, 6, 15))
.seriesName("Amazon Series") .seriesName("Amazon Series")
@@ -23,8 +23,10 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
@@ -93,7 +95,7 @@ class CbxMetadataWriterTest {
meta.setPageCount(42); meta.setPageCount(42);
meta.setLanguage("en"); meta.setLanguage("en");
Set<AuthorEntity> authors = new HashSet<>(); List<AuthorEntity> authors = new ArrayList<>();
AuthorEntity aliceAuthor = new AuthorEntity(); AuthorEntity aliceAuthor = new AuthorEntity();
aliceAuthor.setId(1L); aliceAuthor.setId(1L);
aliceAuthor.setName("Alice"); aliceAuthor.setName("Alice");
@@ -28,6 +28,7 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Collections; import java.util.Collections;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
@@ -70,7 +71,7 @@ class EpubMetadataWriterTest {
metadata.setTitle("Test Book"); metadata.setTitle("Test Book");
AuthorEntity author = new AuthorEntity(); AuthorEntity author = new AuthorEntity();
author.setName("Test Author"); author.setName("Test Author");
metadata.setAuthors(Collections.singleton(author)); metadata.setAuthors(List.of(author));
bookEntity = new BookEntity(); bookEntity = new BookEntity();
LibraryPathEntity libraryPath = new LibraryPathEntity(); LibraryPathEntity libraryPath = new LibraryPathEntity();
@@ -174,7 +175,7 @@ class EpubMetadataWriterTest {
newMeta.setTitle("Updated Title"); newMeta.setTitle("Updated Title");
AuthorEntity author = new AuthorEntity(); AuthorEntity author = new AuthorEntity();
author.setName("Updated Author"); author.setName("Updated Author");
newMeta.setAuthors(Collections.singleton(author)); newMeta.setAuthors(List.of(author));
writer.saveMetadataToFile(epubFile, newMeta, null, new MetadataClearFlags()); writer.saveMetadataToFile(epubFile, newMeta, null, new MetadataClearFlags());
String contentAfterFirstSave = readOpfContent(epubFile); String contentAfterFirstSave = readOpfContent(epubFile);
@@ -25,8 +25,10 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@@ -87,7 +89,7 @@ class PdfMetadataWriterTest {
meta.setLanguage("en"); meta.setLanguage("en");
meta.setPageCount(754); meta.setPageCount(754);
Set<AuthorEntity> authors = new HashSet<>(); List<AuthorEntity> authors = new ArrayList<>();
AuthorEntity author = new AuthorEntity(); AuthorEntity author = new AuthorEntity();
author.setName("Jason C McDonald"); author.setName("Jason C McDonald");
authors.add(author); authors.add(author);
@@ -143,7 +143,7 @@ class OpdsFeedServiceTest {
.addedOn(FIXED_INSTANT) .addedOn(FIXED_INSTANT)
.metadata(BookMetadata.builder() .metadata(BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Author A")) .authors(List.of("Author A"))
.publisher("Publisher X") .publisher("Publisher X")
.language("en") .language("en")
.categories(Set.of("Fiction")) .categories(Set.of("Fiction"))
@@ -50,7 +50,7 @@ import static org.mockito.Mockito.*;
class FileUploadServiceTest { class FileUploadServiceTest {
public static final Set<String> LONG_AUTHOR_LIST = new LinkedHashSet<>(List.of( public static final List<String> LONG_AUTHOR_LIST = new ArrayList<>(List.of(
"梁思成", "叶嘉莹", "厉以宁", "萧乾", "冯友兰", "费孝通", "李济", "侯仁之", "汤一介", "温源宁", "梁思成", "叶嘉莹", "厉以宁", "萧乾", "冯友兰", "费孝通", "李济", "侯仁之", "汤一介", "温源宁",
"胡适", "吴青", "李照国", "蒋梦麟", "汪荣祖", "邢玉瑞", "《中华思想文化术语》编委会", "胡适", "吴青", "李照国", "蒋梦麟", "汪荣祖", "邢玉瑞", "《中华思想文化术语》编委会",
"北京大学政策法规研究室", "(美)艾恺(Guy S. Alitto)", "顾毓琇", "陈从周", "北京大学政策法规研究室", "(美)艾恺(Guy S. Alitto)", "顾毓琇", "陈从周",
@@ -6,8 +6,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.CsvSource;
import java.util.HashSet; import java.util.ArrayList;
import java.util.Set; import java.util.List;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@@ -21,7 +21,7 @@ class BookUtilsTest {
metadata.setTitle("Harry Potter"); metadata.setTitle("Harry Potter");
metadata.setSubtitle("Philosopher's Stone"); metadata.setSubtitle("Philosopher's Stone");
metadata.setSeriesName("Harry Potter Series"); metadata.setSeriesName("Harry Potter Series");
metadata.setAuthors(Set.of(AuthorEntity.builder().name("J.K. Rowling").build())); metadata.setAuthors(List.of(AuthorEntity.builder().name("J.K. Rowling").build()));
String searchText = BookUtils.buildSearchText(metadata); String searchText = BookUtils.buildSearchText(metadata);
@@ -228,7 +228,7 @@ class BookUtilsTest {
metadata.setTitle("The Snowman"); metadata.setTitle("The Snowman");
metadata.setSubtitle("A Harry Hole Novel"); metadata.setSubtitle("A Harry Hole Novel");
metadata.setSeriesName("Harry Hole"); metadata.setSeriesName("Harry Hole");
metadata.setAuthors(Set.of(AuthorEntity.builder().name("Jo Nesbø").build())); metadata.setAuthors(List.of(AuthorEntity.builder().name("Jo Nesbø").build()));
String searchText = BookUtils.buildSearchText(metadata); String searchText = BookUtils.buildSearchText(metadata);
@@ -245,7 +245,7 @@ class BookUtilsTest {
void testSearchMatchingWithAndWithoutDiacritics() { void testSearchMatchingWithAndWithoutDiacritics() {
BookMetadataEntity metadata = new BookMetadataEntity(); BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("Misère"); metadata.setTitle("Misère");
metadata.setAuthors(Set.of(AuthorEntity.builder().name("François Müller").build())); metadata.setAuthors(List.of(AuthorEntity.builder().name("François Müller").build()));
String storedSearchText = BookUtils.buildSearchText(metadata); String storedSearchText = BookUtils.buildSearchText(metadata);
@@ -311,7 +311,7 @@ class BookUtilsTest {
void testBuildSearchText_withAuthorHavingNullName() { void testBuildSearchText_withAuthorHavingNullName() {
BookMetadataEntity metadata = new BookMetadataEntity(); BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("Test Book"); metadata.setTitle("Test Book");
Set<AuthorEntity> authors = new HashSet<>(); List<AuthorEntity> authors = new ArrayList<>();
authors.add(AuthorEntity.builder().name("Valid Author").build()); authors.add(AuthorEntity.builder().name("Valid Author").build());
authors.add(AuthorEntity.builder().name(null).build()); // Author with null name authors.add(AuthorEntity.builder().name(null).build()); // Author with null name
metadata.setAuthors(authors); metadata.setAuthors(authors);
@@ -327,7 +327,7 @@ class BookUtilsTest {
void testBuildSearchText_withEmptyAuthorsSet() { void testBuildSearchText_withEmptyAuthorsSet() {
BookMetadataEntity metadata = new BookMetadataEntity(); BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("Test Book"); metadata.setTitle("Test Book");
metadata.setAuthors(new HashSet<>()); // Empty set metadata.setAuthors(new ArrayList<>()); // Empty list
String searchText = BookUtils.buildSearchText(metadata); String searchText = BookUtils.buildSearchText(metadata);
@@ -11,6 +11,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -84,7 +85,7 @@ public class MetadataChangeDetectorTest {
.moodsLocked(false) .moodsLocked(false)
.tagsLocked(false) .tagsLocked(false)
.reviewsLocked(false) .reviewsLocked(false)
.authors(Set.of( .authors(List.of(
AuthorEntity.builder().id(1L).name("Author One").build(), AuthorEntity.builder().id(1L).name("Author One").build(),
AuthorEntity.builder().id(2L).name("Author Two").build() AuthorEntity.builder().id(2L).name("Author Two").build()
)) ))
@@ -157,7 +158,7 @@ public class MetadataChangeDetectorTest {
.moodsLocked(false) .moodsLocked(false)
.tagsLocked(false) .tagsLocked(false)
.reviewsLocked(false) .reviewsLocked(false)
.authors(Set.of("Author One", "Author Two")) .authors(List.of("Author One", "Author Two"))
.categories(Set.of("Fiction", "Mystery")) .categories(Set.of("Fiction", "Mystery"))
.moods(Set.of("Dark", "Suspenseful")) .moods(Set.of("Dark", "Suspenseful"))
.tags(Set.of("Thriller", "Bestseller")) .tags(Set.of("Thriller", "Bestseller"))
@@ -332,7 +333,7 @@ public class MetadataChangeDetectorTest {
.title("Original Title") .title("Original Title")
.subtitle("Original Subtitle") .subtitle("Original Subtitle")
.publisher("Original Publisher") .publisher("Original Publisher")
.authors(Set.of()) // empty set, this is what we're testing .authors(List.of()) // empty set, this is what we're testing
.authorsLocked(false) .authorsLocked(false)
.categories(Set.of("Fiction")) .categories(Set.of("Fiction"))
.categoriesLocked(false) .categoriesLocked(false)
@@ -362,7 +363,7 @@ public class MetadataChangeDetectorTest {
BookMetadataEntity testExisting = BookMetadataEntity.builder() BookMetadataEntity testExisting = BookMetadataEntity.builder()
.bookId(1L) .bookId(1L)
.title("Test Title") .title("Test Title")
.authors(Set.of()) // empty set, what we're testing .authors(List.of()) // empty set, what we're testing
.authorsLocked(false) .authorsLocked(false)
.categories(Set.of(CategoryEntity.builder().id(1L).name("Fiction").build())) .categories(Set.of(CategoryEntity.builder().id(1L).name("Fiction").build()))
.categoriesLocked(false) .categoriesLocked(false)
@@ -506,13 +507,11 @@ public class MetadataChangeDetectorTest {
} }
@Test @Test
void testAuthorsSetComparison_isOrderInsensitive() { void testAuthorsComparison_isOrderSensitive() {
// Change order of authors in newMeta newMeta.setAuthors(List.of("Author Two", "Author One"));
newMeta.setAuthors(Set.of("Author Two", "Author One"));
// existingMeta has Set.of("Author One", "Author Two") from setup
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertFalse(result, "Authors set comparison should be order insensitive"); assertTrue(result, "Authors comparison should be order sensitive");
} }
@Test @Test
@@ -562,7 +561,7 @@ public class MetadataChangeDetectorTest {
@Test @Test
void testHasValueChangesForFileWrite_includesAuthors() { void testHasValueChangesForFileWrite_includesAuthors() {
newMeta.setAuthors(Set.of("New Author")); newMeta.setAuthors(List.of("New Author"));
boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags); boolean result = MetadataChangeDetector.hasValueChangesForFileWrite(newMeta, existingMeta, clearFlags);
assertTrue(result, "Authors change should trigger file write"); assertTrue(result, "Authors change should trigger file write");
} }
@@ -603,15 +602,15 @@ public class MetadataChangeDetectorTest {
} }
@Test @Test
void testIsDifferent_whenAuthorsSetOrderChanges_returnsFalse() { void testIsDifferent_whenAuthorsOrderChanges_returnsTrue() {
newMeta.setAuthors(Set.of("Author Two", "Author One")); newMeta.setAuthors(List.of("Author Two", "Author One"));
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertFalse(result, "Should return false when only author order changes"); assertTrue(result, "Should return true when author order changes");
} }
@Test @Test
void testIsDifferent_whenAuthorsSetContentChanges_returnsTrue() { void testIsDifferent_whenAuthorsSetContentChanges_returnsTrue() {
newMeta.setAuthors(Set.of("Author One", "Author Three")); // Different author newMeta.setAuthors(List.of("Author One", "Author Three")); // Different author
boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags); boolean result = MetadataChangeDetector.isDifferent(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when author set content changes"); assertTrue(result, "Should return true when author set content changes");
} }
@@ -638,15 +637,15 @@ public class MetadataChangeDetectorTest {
} }
@Test @Test
void testHasValueChanges_whenAuthorsSetOrderChanges_returnsFalse() { void testHasValueChanges_whenAuthorsOrderChanges_returnsTrue() {
newMeta.setAuthors(Set.of("Author Two", "Author One")); newMeta.setAuthors(List.of("Author Two", "Author One"));
boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags); boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags);
assertFalse(result, "Should return false when only author order changes"); assertTrue(result, "Should return true when author order changes");
} }
@Test @Test
void testHasValueChanges_whenMultipleCollectionsChange_returnsTrue() { void testHasValueChanges_whenMultipleCollectionsChange_returnsTrue() {
newMeta.setAuthors(Set.of("New Author")); newMeta.setAuthors(List.of("New Author"));
newMeta.setCategories(Set.of("New Category")); newMeta.setCategories(Set.of("New Category"));
boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags); boolean result = MetadataChangeDetector.hasValueChanges(newMeta, existingMeta, clearFlags);
assertTrue(result, "Should return true when multiple collections change"); assertTrue(result, "Should return true when multiple collections change");
@@ -673,7 +672,7 @@ public class MetadataChangeDetectorTest {
BookMetadataEntity testExisting = BookMetadataEntity.builder() BookMetadataEntity testExisting = BookMetadataEntity.builder()
.bookId(1L) .bookId(1L)
.title("Test") .title("Test")
.authors(Set.of()) .authors(List.of())
.authorsLocked(false) .authorsLocked(false)
.categories(Set.of()) .categories(Set.of())
.categoriesLocked(false) .categoriesLocked(false)
@@ -10,9 +10,8 @@ import org.junit.jupiter.api.Test;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.LinkedHashSet; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@@ -23,7 +22,7 @@ class PathPatternResolverTest {
private static final int MAX_FILENAME_BYTES = 245; // From PathPatternResolver.MAX_FILESYSTEM_COMPONENT_BYTES private static final int MAX_FILENAME_BYTES = 245; // From PathPatternResolver.MAX_FILESYSTEM_COMPONENT_BYTES
private static final Charset FILENAME_CHARSET = StandardCharsets.UTF_8; private static final Charset FILENAME_CHARSET = StandardCharsets.UTF_8;
public static final Set<String> LONG_AUTHOR_LIST = new LinkedHashSet<>(List.of( public static final List<String> LONG_AUTHOR_LIST = new ArrayList<>(List.of(
"梁思成", "叶嘉莹", "厉以宁", "萧乾", "冯友兰", "费孝通", "李济", "侯仁之", "汤一介", "温源宁", "梁思成", "叶嘉莹", "厉以宁", "萧乾", "冯友兰", "费孝通", "李济", "侯仁之", "汤一介", "温源宁",
"胡适", "吴青", "李照国", "蒋梦麟", "汪荣祖", "邢玉瑞", "《中华思想文化术语》编委会", "胡适", "吴青", "李照国", "蒋梦麟", "汪荣祖", "邢玉瑞", "《中华思想文化术语》编委会",
"北京大学政策法规研究室", "(美)艾恺(Guy S. Alitto)", "顾毓琇", "陈从周", "北京大学政策法规研究室", "(美)艾恺(Guy S. Alitto)", "顾毓琇", "陈从周",
@@ -89,7 +88,7 @@ class PathPatternResolverTest {
void testResolvePattern_multiplePlaceholders() { void testResolvePattern_multiplePlaceholders() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Test Book") .title("Test Book")
.authors(Set.of("John Doe", "Jane Smith")) .authors(List.of("John Doe", "Jane Smith"))
.publishedDate(LocalDate.of(2023, 5, 15)) .publishedDate(LocalDate.of(2023, 5, 15))
.build(); .build();
@@ -103,7 +102,7 @@ class PathPatternResolverTest {
@Test @Test
void testResolvePattern_authorsList() { void testResolvePattern_authorsList() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.authors(Set.of("Author One", "Author Two")) .authors(List.of("Author One", "Author Two"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "original.pdf");
@@ -142,7 +141,7 @@ class PathPatternResolverTest {
void testResolvePattern_optionalBlock_allPresent() { void testResolvePattern_optionalBlock_allPresent() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Author Name")) .authors(List.of("Author Name"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}< - {authors}>", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{title}< - {authors}>", "original.pdf");
@@ -261,7 +260,7 @@ class PathPatternResolverTest {
void testResolvePattern_emptyAuthors() { void testResolvePattern_emptyAuthors() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of()) .authors(List.of())
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{title}< - {authors}>", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{title}< - {authors}>", "original.pdf");
@@ -330,7 +329,7 @@ class PathPatternResolverTest {
void testResolvePattern_complexPattern() { void testResolvePattern_complexPattern() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("The Great Book") .title("The Great Book")
.authors(Set.of("John Doe", "Jane Smith")) .authors(List.of("John Doe", "Jane Smith"))
.seriesName("Awesome Series") .seriesName("Awesome Series")
.seriesNumber(3.0f) .seriesNumber(3.0f)
.publishedDate(LocalDate.of(2023, 5, 15)) .publishedDate(LocalDate.of(2023, 5, 15))
@@ -374,7 +373,7 @@ class PathPatternResolverTest {
@Test @Test
void testResolvePattern_authorsWithinLimit() { void testResolvePattern_authorsWithinLimit() {
Set<String> authors = Set.of("John Doe", "Jane Smith", "Bob Wilson"); List<String> authors = List.of("John Doe", "Jane Smith", "Bob Wilson");
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Test Book") .title("Test Book")
@@ -390,7 +389,7 @@ class PathPatternResolverTest {
@Test @Test
@DisplayName("Should apply author truncation in various pattern contexts") @DisplayName("Should apply author truncation in various pattern contexts")
void testResolvePattern_appliesAuthorTruncation() { void testResolvePattern_appliesAuthorTruncation() {
Set<String> shortAuthorList = new LinkedHashSet<>(List.of("John Doe", "Jane Smith")); List<String> shortAuthorList = new ArrayList<>(List.of("John Doe", "Jane Smith"));
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Test") .title("Test")
@@ -429,7 +428,7 @@ class PathPatternResolverTest {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Test") .title("Test")
.authors(Set.of(veryLongAuthor)) .authors(List.of(veryLongAuthor))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "test.epub"); String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "test.epub");
@@ -503,7 +502,7 @@ class PathPatternResolverTest {
void testResolvePattern_removesTrailingDots() { void testResolvePattern_removesTrailingDots() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Author Name Jr.")) .authors(List.of("Author Name Jr."))
.build(); .build();
// Pattern: {authors}/{title} // Pattern: {authors}/{title}
@@ -527,7 +526,7 @@ class PathPatternResolverTest {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title.") .title("Book Title.")
.seriesName("Series.") .seriesName("Series.")
.authors(Set.of("Author.")) .authors(List.of("Author."))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors}/{series}/{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors}/{series}/{title}", "original.pdf");
@@ -572,7 +571,7 @@ class PathPatternResolverTest {
void testResolvePattern_extensionNotInPattern() { void testResolvePattern_extensionNotInPattern() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Author Name")) .authors(List.of("Author Name"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors} - {title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors} - {title}", "original.pdf");
@@ -683,7 +682,7 @@ class PathPatternResolverTest {
String veryLongAuthor = "A".repeat(300); // Very long single author String veryLongAuthor = "A".repeat(300); // Very long single author
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Test") .title("Test")
.authors(Set.of(veryLongAuthor)) .authors(List.of(veryLongAuthor))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "test.epub"); String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "test.epub");
@@ -701,7 +700,7 @@ class PathPatternResolverTest {
void testResolvePattern_multipleTrailingDots() { void testResolvePattern_multipleTrailingDots() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title...") .title("Book Title...")
.authors(Set.of("Author Name...")) .authors(List.of("Author Name..."))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors}/{title}", "test.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors}/{title}", "test.pdf");
@@ -742,7 +741,7 @@ class PathPatternResolverTest {
void testResolvePattern_optionalBlockAllPresent() { void testResolvePattern_optionalBlockAllPresent() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Title") .title("Title")
.authors(Set.of("Author")) .authors(List.of("Author"))
.seriesName("Series") .seriesName("Series")
.build(); .build();
@@ -815,7 +814,7 @@ class PathPatternResolverTest {
String veryLongFirstAuthor = "某".repeat(100); // ~300 bytes String veryLongFirstAuthor = "某".repeat(100); // ~300 bytes
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Test") .title("Test")
.authors(Set.of(veryLongFirstAuthor, "Second Author")) .authors(List.of(veryLongFirstAuthor, "Second Author"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "test.epub"); String result = PathPatternResolver.resolvePattern(metadata, "{authors}", "test.epub");
@@ -922,7 +921,7 @@ class PathPatternResolverTest {
void testElseClause_fallbackWithPlaceholders() { void testElseClause_fallbackWithPlaceholders() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("John Doe")) .authors(List.of("John Doe"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "<{series}/{seriesIndex} - {title}|{title}>", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "<{series}/{seriesIndex} - {title}|{title}>", "original.pdf");
@@ -959,7 +958,7 @@ class PathPatternResolverTest {
void testElseClause_mixedBlocks() { void testElseClause_mixedBlocks() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Author")) .authors(List.of("Author"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "<{series}|Standalone>/<{year} - >{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "<{series}|Standalone>/<{year} - >{title}", "original.pdf");
@@ -974,7 +973,7 @@ class PathPatternResolverTest {
void testModifier_firstMultipleAuthors() { void testModifier_firstMultipleAuthors() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(new LinkedHashSet<>(List.of("Patrick Rothfuss", "Brandon Sanderson"))) .authors(new ArrayList<>(List.of("Patrick Rothfuss", "Brandon Sanderson")))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors:first}/{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors:first}/{title}", "original.pdf");
@@ -987,7 +986,7 @@ class PathPatternResolverTest {
void testModifier_firstSingleAuthor() { void testModifier_firstSingleAuthor() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Patrick Rothfuss")) .authors(List.of("Patrick Rothfuss"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors:first}/{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors:first}/{title}", "original.pdf");
@@ -1000,7 +999,7 @@ class PathPatternResolverTest {
void testModifier_sort() { void testModifier_sort() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Patrick Rothfuss")) .authors(List.of("Patrick Rothfuss"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors:sort}/{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors:sort}/{title}", "original.pdf");
@@ -1013,7 +1012,7 @@ class PathPatternResolverTest {
void testModifier_sortSingleWord() { void testModifier_sortSingleWord() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Plato")) .authors(List.of("Plato"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors:sort}/{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors:sort}/{title}", "original.pdf");
@@ -1038,7 +1037,7 @@ class PathPatternResolverTest {
void testModifier_initialAuthors() { void testModifier_initialAuthors() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Patrick Rothfuss")) .authors(List.of("Patrick Rothfuss"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors:initial}/{authors:sort}/{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors:initial}/{authors:sort}/{title}", "original.pdf");
@@ -1087,7 +1086,7 @@ class PathPatternResolverTest {
void testModifier_insideElseClause() { void testModifier_insideElseClause() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Patrick Rothfuss")) .authors(List.of("Patrick Rothfuss"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "<{series}|{authors:sort}>/{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "<{series}|{authors:sort}>/{title}", "original.pdf");
@@ -1100,7 +1099,7 @@ class PathPatternResolverTest {
void testModifier_inOptionalBlock() { void testModifier_inOptionalBlock() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Patrick Rothfuss")) .authors(List.of("Patrick Rothfuss"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "<{authors:sort}/>{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "<{authors:sort}/>{title}", "original.pdf");
@@ -1115,7 +1114,7 @@ class PathPatternResolverTest {
void testModifier_sortThreeWordName() { void testModifier_sortThreeWordName() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Mary Jane Watson")) .authors(List.of("Mary Jane Watson"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors:sort}/{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors:sort}/{title}", "original.pdf");
@@ -1128,7 +1127,7 @@ class PathPatternResolverTest {
void testModifier_initialSingleWordAuthor() { void testModifier_initialSingleWordAuthor() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Plato")) .authors(List.of("Plato"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors:initial}/{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors:initial}/{title}", "original.pdf");
@@ -1168,7 +1167,7 @@ class PathPatternResolverTest {
void testElseClause_multipleBlocks() { void testElseClause_multipleBlocks() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Author")) .authors(List.of("Author"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, String result = PathPatternResolver.resolvePattern(metadata,
@@ -1210,7 +1209,7 @@ class PathPatternResolverTest {
void testModifier_inPrimarySideOfElseClause() { void testModifier_inPrimarySideOfElseClause() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Patrick Rothfuss")) .authors(List.of("Patrick Rothfuss"))
.seriesName("My Series") .seriesName("My Series")
.build(); .build();
@@ -1225,7 +1224,7 @@ class PathPatternResolverTest {
void testModifier_chainedDifferentFields() { void testModifier_chainedDifferentFields() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Patrick Rothfuss")) .authors(List.of("Patrick Rothfuss"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, String result = PathPatternResolver.resolvePattern(metadata,
@@ -1252,7 +1251,7 @@ class PathPatternResolverTest {
void testModifier_firstWithManyAuthors() { void testModifier_firstWithManyAuthors() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(new LinkedHashSet<>(List.of("Alice", "Bob", "Carol", "Dave"))) .authors(new ArrayList<>(List.of("Alice", "Bob", "Carol", "Dave")))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, "{authors:first}/{title}", "original.pdf"); String result = PathPatternResolver.resolvePattern(metadata, "{authors:first}/{title}", "original.pdf");
@@ -1265,7 +1264,7 @@ class PathPatternResolverTest {
void testModifier_withElseClauseAndExtension() { void testModifier_withElseClauseAndExtension() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("My Book") .title("My Book")
.authors(Set.of("Jane Doe")) .authors(List.of("Jane Doe"))
.build(); .build();
String result = PathPatternResolver.resolvePattern(metadata, String result = PathPatternResolver.resolvePattern(metadata,
@@ -1306,7 +1305,7 @@ class PathPatternResolverTest {
void testElseClause_existingPatternsUnchanged() { void testElseClause_existingPatternsUnchanged() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of("Author")) .authors(List.of("Author"))
.seriesName("Series") .seriesName("Series")
.seriesNumber(1f) .seriesNumber(1f)
.publishedDate(LocalDate.of(2023, 1, 1)) .publishedDate(LocalDate.of(2023, 1, 1))
@@ -1323,7 +1322,7 @@ class PathPatternResolverTest {
void testResolvePattern_removesLeadingSlash_whenFirstComponentIsEmpty() { void testResolvePattern_removesLeadingSlash_whenFirstComponentIsEmpty() {
BookMetadata metadata = BookMetadata.builder() BookMetadata metadata = BookMetadata.builder()
.title("Book Title") .title("Book Title")
.authors(Set.of()) // Empty authors .authors(List.of()) // Empty authors
.build(); .build();
// Pattern implies a subdirectory, but authors is missing // Pattern implies a subdirectory, but authors is missing
@@ -182,19 +182,45 @@
<div class="meta-row field-{{field.controlName}}"> <div class="meta-row field-{{field.controlName}}">
<label for="{{field.controlName}}" class="field-label">{{ field.label }}</label> <label for="{{field.controlName}}" class="field-label">{{ field.label }}</label>
<div class="meta-fields"> <div class="meta-fields">
<p-autoComplete @if (field.controlName === 'authors') {
size="small" <div class="author-chips-container dest full-width"
formControlName="{{field.controlName}}" cdkDropList cdkDropListOrientation="mixed"
[multiple]="true" (cdkDropListDropped)="dropAuthor($event)"
[typeahead]="false" [ngClass]="{ 'changed': isValueChanged('authors') }">
[dropdown]="false" @for (author of metadataForm.get('authors')!.value; track $index) {
[forceSelection]="false" <span class="author-chip" [class.main-author]="$index === 0" cdkDrag>
class="dest full-width" @if ($index === 0) { <span class="main-author-badge">m</span> }
[ngClass]="{ {{ author }}
'changed': isValueChanged(field.controlName), <i class="pi pi-times author-chip-remove" (click)="removeAuthor($index)"></i>
}" </span>
(onBlur)="onAutoCompleteBlur(field.controlName, $event)" }
/> <p-autoComplete
class="author-add-input"
[(ngModel)]="authorInputValue"
[ngModelOptions]="{ standalone: true }"
size="small"
[forceSelection]="false"
[dropdown]="false"
(onKeyUp)="onAuthorInputKeyUp($event)"
(onSelect)="onAuthorInputSelect($event)"
placeholder="Add author..."
/>
</div>
} @else {
<p-autoComplete
size="small"
formControlName="{{field.controlName}}"
[multiple]="true"
[typeahead]="false"
[dropdown]="false"
[forceSelection]="false"
class="dest full-width"
[ngClass]="{
'changed': isValueChanged(field.controlName),
}"
(onBlur)="onAutoCompleteBlur(field.controlName, $event)"
/>
}
<p-button <p-button
size="small" size="small"
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')" [icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')"
@@ -406,19 +432,45 @@
<div class="meta-row field-{{field.controlName}}"> <div class="meta-row field-{{field.controlName}}">
<label for="{{field.controlName}}" class="field-label field-label--fixed">{{ field.label }}</label> <label for="{{field.controlName}}" class="field-label field-label--fixed">{{ field.label }}</label>
<div class="field-input-row"> <div class="field-input-row">
<p-autoComplete @if (field.controlName === 'authors') {
size="small" <div class="author-chips-container full-width"
formControlName="{{field.controlName}}" cdkDropList cdkDropListOrientation="mixed"
[multiple]="true" (cdkDropListDropped)="dropAuthor($event)"
[typeahead]="false" [ngClass]="{ 'changed': isValueChanged('authors') }">
[dropdown]="false" @for (author of metadataForm.get('authors')!.value; track $index) {
[forceSelection]="false" <span class="author-chip" [class.main-author]="$index === 0" cdkDrag>
class="full-width" @if ($index === 0) { <span class="main-author-badge">m</span> }
[ngClass]="{ {{ author }}
'changed': isValueChanged(field.controlName), <i class="pi pi-times author-chip-remove" (click)="removeAuthor($index)"></i>
}" </span>
(onBlur)="onAutoCompleteBlur(field.controlName, $event)" }
/> <p-autoComplete
class="author-add-input"
[(ngModel)]="authorInputValue"
[ngModelOptions]="{ standalone: true }"
size="small"
[forceSelection]="false"
[dropdown]="false"
(onKeyUp)="onAuthorInputKeyUp($event)"
(onSelect)="onAuthorInputSelect($event)"
placeholder="Add author..."
/>
</div>
} @else {
<p-autoComplete
size="small"
formControlName="{{field.controlName}}"
[multiple]="true"
[typeahead]="false"
[dropdown]="false"
[forceSelection]="false"
class="full-width"
[ngClass]="{
'changed': isValueChanged(field.controlName),
}"
(onBlur)="onAutoCompleteBlur(field.controlName, $event)"
/>
}
<p-button <p-button
size="small" size="small"
icon="pi pi-refresh" icon="pi pi-refresh"
@@ -410,3 +410,77 @@ textarea.changed,
} }
} }
} }
.author-chips-container {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.375rem;
padding: 0.375rem;
min-height: 2.25rem;
border: 1px solid var(--p-inputtext-border-color);
border-radius: 6px;
background: var(--p-inputtext-background);
}
.author-add-input {
flex: 1 1 6rem;
min-width: 6rem;
::ng-deep input {
border: none !important;
background: transparent !important;
padding: 0.25rem;
box-shadow: none !important;
outline: none !important;
}
}
.author-chip {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0.25rem 0.5rem;
border-radius: 1rem;
background: var(--p-chip-background);
color: var(--p-chip-color);
font-size: 0.875rem;
cursor: grab;
user-select: none;
}
.main-author-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1rem;
height: 1rem;
border-radius: 50%;
background: var(--p-primary-color);
color: var(--p-primary-contrast-color);
font-size: 0.6rem;
font-weight: 700;
flex-shrink: 0;
}
.author-chip-remove {
font-size: 0.65rem;
cursor: pointer;
opacity: 0.6;
padding: 0.15rem;
&:hover { opacity: 1; }
}
.cdk-drag-preview {
box-sizing: border-box;
border-radius: 1rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.cdk-drag-placeholder {
opacity: 0.4;
}
.cdk-drag-animating {
transition: transform 200ms ease;
}
@@ -13,6 +13,8 @@ import {AutoComplete} from 'primeng/autocomplete';
import {Image} from 'primeng/image'; import {Image} from 'primeng/image';
import {LazyLoadImageModule} from 'ng-lazyload-image'; import {LazyLoadImageModule} from 'ng-lazyload-image';
import {ConfirmationService} from 'primeng/api'; import {ConfirmationService} from 'primeng/api';
import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/drag-drop';
import {AutoCompleteSelectEvent} from 'primeng/autocomplete';
import {DatePicker} from 'primeng/datepicker'; import {DatePicker} from 'primeng/datepicker';
import {ALL_METADATA_FIELDS, getArrayFields, getBottomFields, getTextareaFields, MetadataFieldConfig} from '../../../../shared/metadata'; import {ALL_METADATA_FIELDS, getArrayFields, getBottomFields, getTextareaFields, MetadataFieldConfig} from '../../../../shared/metadata';
import {MetadataUtilsService} from '../../../../shared/metadata'; import {MetadataUtilsService} from '../../../../shared/metadata';
@@ -35,6 +37,8 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
LazyLoadImageModule, LazyLoadImageModule,
DatePicker, DatePicker,
TranslocoDirective, TranslocoDirective,
CdkDropList,
CdkDrag,
], ],
templateUrl: './bookdrop-file-metadata-picker.component.html', templateUrl: './bookdrop-file-metadata-picker.component.html',
styleUrl: './bookdrop-file-metadata-picker.component.scss' styleUrl: './bookdrop-file-metadata-picker.component.scss'
@@ -57,6 +61,8 @@ export class BookdropFileMetadataPickerComponent implements OnInit {
@Output() metadataCopied = new EventEmitter<boolean>(); @Output() metadataCopied = new EventEmitter<boolean>();
authorInputValue = '';
private enabledProviderFields: MetadataProviderSpecificFields | null = null; private enabledProviderFields: MetadataProviderSpecificFields | null = null;
metadataFieldsTop: MetadataFieldConfig[] = ALL_METADATA_FIELDS.filter(f => metadataFieldsTop: MetadataFieldConfig[] = ALL_METADATA_FIELDS.filter(f =>
@@ -135,6 +141,44 @@ export class BookdropFileMetadataPickerComponent implements OnInit {
} }
} }
dropAuthor(event: CdkDragDrop<string[]>) {
const authors = [...(this.metadataForm.get('authors')?.value ?? [])];
moveItemInArray(authors, event.previousIndex, event.currentIndex);
this.metadataForm.get('authors')?.setValue(authors);
this.metadataForm.get('authors')?.markAsDirty();
}
removeAuthor(index: number) {
const authors = [...(this.metadataForm.get('authors')?.value ?? [])];
authors.splice(index, 1);
this.metadataForm.get('authors')?.setValue(authors);
this.metadataForm.get('authors')?.markAsDirty();
}
onAuthorInputKeyUp(event: KeyboardEvent) {
if (event.key === 'Enter') {
const value = this.authorInputValue?.trim();
if (value) {
const authors = this.metadataForm.get('authors')?.value || [];
if (!authors.includes(value)) {
this.metadataForm.get('authors')?.setValue([...authors, value]);
this.metadataForm.get('authors')?.markAsDirty();
}
this.authorInputValue = '';
}
}
}
onAuthorInputSelect(event: AutoCompleteSelectEvent) {
const authors = (this.metadataForm.get('authors')?.value as string[]) || [];
const value = event.value as string;
if (!authors.includes(value)) {
this.metadataForm.get('authors')?.setValue([...authors, value]);
this.metadataForm.get('authors')?.markAsDirty();
}
setTimeout(() => this.authorInputValue = '');
}
onAutoCompleteBlur(fieldName: string, event: Event): void { onAutoCompleteBlur(fieldName: string, event: Event): void {
const target = event.target as HTMLInputElement; const target = event.target as HTMLInputElement;
const inputValue = target?.value?.trim(); const inputValue = target?.value?.trim();
@@ -210,19 +210,35 @@
<div class="field-row"> <div class="field-row">
<div class="field-group authors-field"> <div class="field-group authors-field">
<label for="authors">{{ t('authors') }} @if (isEmbeddable('authors', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label> <label for="authors">{{ t('authors') }} @if (isEmbeddable('authors', book)) { <i class="pi pi-file-export embeddable-indicator" [pTooltip]="t('writtenToFileTooltip')" tooltipPosition="top"></i> }</label>
<div class="field-with-lock"> <div class="field-with-lock authors-lock-wrapper">
<p-autoComplete <div class="author-chips-container" [class.disabled]="metadataForm.get('authors')?.disabled"
formControlName="authors" cdkDropList cdkDropListOrientation="mixed"
[multiple]="true" [cdkDropListDisabled]="metadataForm.get('authors')?.disabled"
[fluid]="true" (cdkDropListDropped)="dropAuthor($event)">
[dropdown]="false" @for (author of metadataForm.get('authors')!.value; track $index) {
[suggestions]="filteredAuthors" <span class="author-chip" [class.main-author]="$first" cdkDrag>
[forceSelection]="false" @if ($first) { <span class="main-author-badge">m</span> }
[showClear]="false" {{ author }}
(completeMethod)="filterAuthors($event)" @if (!metadataForm.get('authors')?.disabled) {
(onKeyUp)="onAutoCompleteKeyUp('authors', $event)" <i class="pi pi-times author-chip-remove" (click)="removeAuthor($index)"></i>
(onSelect)="onAutoCompleteSelect('authors', $event)"> }
</p-autoComplete> </span>
}
@if (!metadataForm.get('authors')?.disabled) {
<p-autoComplete
class="author-add-input"
[(ngModel)]="authorInputValue"
[ngModelOptions]="{ standalone: true }"
[suggestions]="filteredAuthors"
[forceSelection]="false"
[dropdown]="false"
(completeMethod)="filterAuthors($event)"
(onKeyUp)="onAuthorInputKeyUp($event)"
(onSelect)="onAuthorInputSelect($event)"
placeholder="Add author..."
/>
}
</div>
@if (!book.metadata!['authorsLocked']) { @if (!book.metadata!['authorsLocked']) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('authors')" severity="success"></p-button> <p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('authors')" severity="success"></p-button>
} }
@@ -250,6 +250,92 @@ label {
} }
} }
.author-chips-container {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.375rem;
padding: 0.375rem;
min-height: 2.25rem;
border: 1px solid var(--p-inputtext-border-color);
border-radius: 6px;
background: var(--p-inputtext-background);
flex: 1;
min-width: 0;
&.disabled {
opacity: 0.6;
background: var(--p-inputtext-disabled-background);
cursor: default;
.author-chip {
cursor: default;
}
}
}
.author-add-input {
flex: 1 1 6rem;
min-width: 6rem;
::ng-deep input {
border: none !important;
background: transparent !important;
padding: 0.25rem;
box-shadow: none !important;
outline: none !important;
}
}
.author-chip {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0.25rem 0.5rem;
border-radius: 1rem;
background: var(--p-chip-background);
color: var(--p-chip-color);
font-size: 0.875rem;
cursor: grab;
user-select: none;
}
.main-author-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1rem;
height: 1rem;
border-radius: 50%;
background: var(--p-primary-color);
color: var(--p-primary-contrast-color);
font-size: 0.6rem;
font-weight: 700;
flex-shrink: 0;
}
.author-chip-remove {
font-size: 0.65rem;
cursor: pointer;
opacity: 0.6;
padding: 0.15rem;
&:hover { opacity: 1; }
}
.cdk-drag-preview {
box-sizing: border-box;
border-radius: 1rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.cdk-drag-placeholder {
opacity: 0.4;
}
.cdk-drag-animating {
transition: transform 200ms ease;
}
.publisher-field { .publisher-field {
@media (min-width: 768px) { @media (min-width: 768px) {
flex-basis: 35%; flex-basis: 35%;
@@ -33,6 +33,7 @@ import {UserService} from '../../../../settings/user-management/user.service';
import {AppSettingsService} from '../../../../../shared/service/app-settings.service'; import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
import {MetadataProviderSpecificFields} from '../../../../../shared/model/app-settings.model'; import {MetadataProviderSpecificFields} from '../../../../../shared/model/app-settings.model';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/drag-drop';
@Component({ @Component({
selector: "app-metadata-editor", selector: "app-metadata-editor",
@@ -56,6 +57,8 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
LazyLoadImageModule, LazyLoadImageModule,
Select, Select,
TranslocoDirective, TranslocoDirective,
CdkDropList,
CdkDrag,
], ],
}) })
export class MetadataEditorComponent implements OnInit { export class MetadataEditorComponent implements OnInit {
@@ -105,6 +108,7 @@ export class MetadataEditorComponent implements OnInit {
allSeries!: string[]; allSeries!: string[];
filteredCategories: string[] = []; filteredCategories: string[] = [];
filteredAuthors: string[] = []; filteredAuthors: string[] = [];
authorInputValue = '';
filteredMoods: string[] = []; filteredMoods: string[] = [];
filteredTags: string[] = []; filteredTags: string[] = [];
filteredPublishers: string[] = []; filteredPublishers: string[] = [];
@@ -162,6 +166,44 @@ export class MetadataEditorComponent implements OnInit {
); );
} }
dropAuthor(event: CdkDragDrop<string[]>) {
const authors = [...(this.metadataForm.get('authors')?.value ?? [])];
moveItemInArray(authors, event.previousIndex, event.currentIndex);
this.metadataForm.get('authors')?.setValue(authors);
this.metadataForm.get('authors')?.markAsDirty();
}
removeAuthor(index: number) {
const authors = [...(this.metadataForm.get('authors')?.value ?? [])];
authors.splice(index, 1);
this.metadataForm.get('authors')?.setValue(authors);
this.metadataForm.get('authors')?.markAsDirty();
}
onAuthorInputKeyUp(event: KeyboardEvent) {
if (event.key === 'Enter') {
const value = this.authorInputValue?.trim();
if (value) {
const authors = this.metadataForm.get('authors')?.value || [];
if (!authors.includes(value)) {
this.metadataForm.get('authors')?.setValue([...authors, value]);
this.metadataForm.get('authors')?.markAsDirty();
}
this.authorInputValue = '';
}
}
}
onAuthorInputSelect(event: AutoCompleteSelectEvent) {
const authors = (this.metadataForm.get('authors')?.value as string[]) || [];
const value = event.value as string;
if (!authors.includes(value)) {
this.metadataForm.get('authors')?.setValue([...authors, value]);
this.metadataForm.get('authors')?.markAsDirty();
}
setTimeout(() => this.authorInputValue = '');
}
filterMoods(event: { query: string }) { filterMoods(event: { query: string }) {
const query = event.query.toLowerCase(); const query = event.query.toLowerCase();
this.filteredMoods = this.allMoods.filter((mood) => this.filteredMoods = this.allMoods.filter((mood) =>
@@ -392,7 +434,7 @@ export class MetadataEditorComponent implements OnInit {
this.metadataForm.patchValue({ this.metadataForm.patchValue({
title: metadata.title ?? null, title: metadata.title ?? null,
subtitle: metadata.subtitle ?? null, subtitle: metadata.subtitle ?? null,
authors: [...(metadata.authors ?? [])].sort(), authors: [...(metadata.authors ?? [])],
categories: [...(metadata.categories ?? [])].sort(), categories: [...(metadata.categories ?? [])].sort(),
moods: [...(metadata.moods ?? [])].sort(), moods: [...(metadata.moods ?? [])].sort(),
tags: [...(metadata.tags ?? [])].sort(), tags: [...(metadata.tags ?? [])].sort(),
@@ -258,18 +258,49 @@
> >
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i> <i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button> </button>
<p-autoComplete @if (field.controlName === 'authors') {
class="chips-input" <div class="author-chips-container" [class.disabled]="metadataForm.get('authors')?.disabled"
formControlName="{{field.controlName}}" cdkDropList cdkDropListOrientation="mixed"
[multiple]="true" [cdkDropListDisabled]="metadataForm.get('authors')?.disabled"
[dropdown]="false" (cdkDropListDropped)="dropAuthor($event)">
[forceSelection]="false" @for (author of metadataForm.get('authors')!.value; track $index) {
[showClear]="true" <span class="author-chip" [class.main-author]="$index === 0" cdkDrag>
[suggestions]="getFiltered(field.controlName)" @if ($index === 0) { <span class="main-author-badge">m</span> }
(completeMethod)="filterItems($event, field.controlName)" {{ author }}
(onKeyUp)="onAutoCompleteKeyUp(field.controlName, $event)" @if (!metadataForm.get('authors')?.disabled) {
(onSelect)="onAutoCompleteSelect(field.controlName, $event)" <i class="pi pi-times author-chip-remove" (click)="removeAuthor($index)"></i>
/> }
</span>
}
@if (!metadataForm.get('authors')?.disabled) {
<p-autoComplete
class="author-add-input"
[(ngModel)]="authorInputValue"
[ngModelOptions]="{ standalone: true }"
[suggestions]="getFiltered('authors')"
[forceSelection]="false"
[dropdown]="false"
(completeMethod)="filterItems($event, 'authors')"
(onKeyUp)="onAuthorInputKeyUp($event)"
(onSelect)="onAuthorInputSelect($event)"
placeholder="Add author..."
/>
}
</div>
} @else {
<p-autoComplete
class="chips-input"
formControlName="{{field.controlName}}"
[multiple]="true"
[dropdown]="false"
[forceSelection]="false"
[showClear]="true"
[suggestions]="getFiltered(field.controlName)"
(completeMethod)="filterItems($event, field.controlName)"
(onKeyUp)="onAutoCompleteKeyUp(field.controlName, $event)"
(onSelect)="onAutoCompleteSelect(field.controlName, $event)"
/>
}
</div> </div>
<button <button
@@ -630,3 +630,89 @@
font-weight: 600; font-weight: 600;
} }
} }
.author-chips-container {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.375rem;
padding: 0.375rem;
min-height: 2.25rem;
border: 1px solid var(--p-inputtext-border-color);
border-radius: 6px;
background: var(--p-inputtext-background);
flex: 1;
min-width: 0;
&.disabled {
opacity: 0.6;
background: var(--p-inputtext-disabled-background);
cursor: default;
.author-chip {
cursor: default;
}
}
}
.author-add-input {
flex: 1 1 6rem;
min-width: 6rem;
::ng-deep input {
border: none !important;
background: transparent !important;
padding: 0.25rem;
box-shadow: none !important;
outline: none !important;
}
}
.author-chip {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0.25rem 0.5rem;
border-radius: 1rem;
background: var(--p-chip-background);
color: var(--p-chip-color);
font-size: 0.875rem;
cursor: grab;
user-select: none;
}
.main-author-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1rem;
height: 1rem;
border-radius: 50%;
background: var(--p-primary-color);
color: var(--p-primary-contrast-color);
font-size: 0.6rem;
font-weight: 700;
flex-shrink: 0;
}
.author-chip-remove {
font-size: 0.65rem;
cursor: pointer;
opacity: 0.6;
padding: 0.15rem;
&:hover { opacity: 1; }
}
.cdk-drag-preview {
box-sizing: border-box;
border-radius: 1rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.cdk-drag-placeholder {
opacity: 0.4;
}
.cdk-drag-animating {
transition: transform 200ms ease;
}
@@ -1,6 +1,7 @@
import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output} from '@angular/core'; import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
import {Book, BookMetadata, ComicMetadata, MetadataClearFlags, MetadataUpdateWrapper} from '../../../../book/model/book.model'; import {Book, BookMetadata, ComicMetadata, MetadataClearFlags, MetadataUpdateWrapper} from '../../../../book/model/book.model';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/drag-drop';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {InputText} from 'primeng/inputtext'; import {InputText} from 'primeng/inputtext';
@@ -39,7 +40,9 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
Image, Image,
LazyLoadImageModule, LazyLoadImageModule,
Checkbox, Checkbox,
TranslocoDirective TranslocoDirective,
CdkDropList,
CdkDrag,
] ]
}) })
export class MetadataPickerComponent implements OnInit { export class MetadataPickerComponent implements OnInit {
@@ -68,6 +71,7 @@ export class MetadataPickerComponent implements OnInit {
private allItems: Record<string, string[]> = {}; private allItems: Record<string, string[]> = {};
filteredItems: Record<string, string[]> = {}; filteredItems: Record<string, string[]> = {};
authorInputValue = '';
metadataForm!: FormGroup; metadataForm!: FormGroup;
currentBookId!: number; currentBookId!: number;
@@ -284,6 +288,44 @@ export class MetadataPickerComponent implements OnInit {
} }
} }
dropAuthor(event: CdkDragDrop<string[]>) {
const authors = [...(this.metadataForm.get('authors')?.value ?? [])];
moveItemInArray(authors, event.previousIndex, event.currentIndex);
this.metadataForm.get('authors')?.setValue(authors);
this.metadataForm.get('authors')?.markAsDirty();
}
removeAuthor(index: number) {
const authors = [...(this.metadataForm.get('authors')?.value ?? [])];
authors.splice(index, 1);
this.metadataForm.get('authors')?.setValue(authors);
this.metadataForm.get('authors')?.markAsDirty();
}
onAuthorInputKeyUp(event: KeyboardEvent) {
if (event.key === 'Enter') {
const value = this.authorInputValue?.trim();
if (value) {
const authors = this.metadataForm.get('authors')?.value || [];
if (!authors.includes(value)) {
this.metadataForm.get('authors')?.setValue([...authors, value]);
this.metadataForm.get('authors')?.markAsDirty();
}
this.authorInputValue = '';
}
}
}
onAuthorInputSelect(event: AutoCompleteSelectEvent) {
const authors = (this.metadataForm.get('authors')?.value as string[]) || [];
const value = event.value as string;
if (!authors.includes(value)) {
this.metadataForm.get('authors')?.setValue([...authors, value]);
this.metadataForm.get('authors')?.markAsDirty();
}
setTimeout(() => this.authorInputValue = '');
}
onSave(): void { onSave(): void {
this.isSaving = true; this.isSaving = true;
const updatedBookMetadata = this.buildMetadataWrapper(undefined); const updatedBookMetadata = this.buildMetadataWrapper(undefined);
@@ -120,8 +120,13 @@
</div> </div>
<p class="authors"> <p class="authors">
@for (author of book?.metadata!.authors; track $index; let isLast = $last) { @for (author of book?.metadata!.authors; track $index; let isLast = $last; let isFirst = $first) {
<a class="author-link" (click)="goToAuthorBooks(author)">{{ author }}</a> @if (isFirst && book!.metadata!.authors!.length > 1) {
<a class="author-link" (click)="goToAuthorBooks(author)">{{ author }}</a>
<span class="first-author-badge">{{ t('firstAuthorBadge') }}</span>
} @else {
<a class="author-link" (click)="goToAuthorBooks(author)">{{ author }}</a>
}
@if (!isLast) { @if (!isLast) {
<span class="author-separator">, </span> <span class="author-separator">, </span>
} }
@@ -222,6 +222,22 @@
text-decoration: underline; text-decoration: underline;
} }
.first-author-badge {
display: inline-flex;
align-items: center;
font-size: 0.55rem;
font-weight: 700;
color: #DAA520;
text-transform: uppercase;
letter-spacing: 0.3px;
margin-left: 0.25rem;
padding: 0.1rem 0.3rem;
border: 1px solid #DAA520;
border-radius: 3px;
line-height: 1;
vertical-align: middle;
}
.formats-inline { .formats-inline {
display: flex; display: flex;
align-items: center; align-items: center;
+1
View File
@@ -245,6 +245,7 @@
"languageLabel": "Language:", "languageLabel": "Language:",
"formatsLabel": "Formats:", "formatsLabel": "Formats:",
"primaryBadge": "PRIMARY", "primaryBadge": "PRIMARY",
"firstAuthorBadge": "MAIN",
"physicalBadge": "PHYSICAL", "physicalBadge": "PHYSICAL",
"bookloreProgressLabel": "BookLore Progress:", "bookloreProgressLabel": "BookLore Progress:",
"metadataMatchLabel": "Metadata Match:", "metadataMatchLabel": "Metadata Match:",
+1
View File
@@ -245,6 +245,7 @@
"languageLabel": "Idioma:", "languageLabel": "Idioma:",
"formatsLabel": "Formatos:", "formatsLabel": "Formatos:",
"primaryBadge": "PRINCIPAL", "primaryBadge": "PRINCIPAL",
"firstAuthorBadge": "PRINCIPAL",
"physicalBadge": "FÍSICO", "physicalBadge": "FÍSICO",
"bookloreProgressLabel": "Progreso BookLore:", "bookloreProgressLabel": "Progreso BookLore:",
"metadataMatchLabel": "Coincidencia de metadatos:", "metadataMatchLabel": "Coincidencia de metadatos:",