feat(api): add paginated author browse, facets, and ids endpoints (#2354)
Co-authored-by: James Ward <james@notjam.es>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
package org.booklore.controller;
|
||||
|
||||
import org.booklore.browse.BrowsePage;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.AuthorDetails;
|
||||
import org.booklore.model.dto.AuthorSearchResult;
|
||||
@@ -7,14 +8,18 @@ import org.booklore.model.dto.AuthorSummary;
|
||||
import org.booklore.model.dto.CoverImage;
|
||||
import org.booklore.model.dto.request.AuthorMatchRequest;
|
||||
import org.booklore.model.dto.request.AuthorUpdateRequest;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse;
|
||||
import org.booklore.service.AuthorMetadataService;
|
||||
import org.booklore.service.AuthorService;
|
||||
import org.booklore.service.browse.AuthorBrowseService;
|
||||
import org.booklore.service.browse.AuthorFacetService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
@@ -33,6 +38,8 @@ public class AuthorController {
|
||||
|
||||
private final AuthorService authorService;
|
||||
private final AuthorMetadataService authorMetadataService;
|
||||
private final AuthorBrowseService authorBrowseService;
|
||||
private final AuthorFacetService authorFacetService;
|
||||
|
||||
@Operation(summary = "Get all authors", description = "Retrieve all authors with book counts.")
|
||||
@ApiResponse(responseCode = "200", description = "Authors returned successfully")
|
||||
@@ -41,6 +48,52 @@ public class AuthorController {
|
||||
return ResponseEntity.ok(authorMetadataService.getAllAuthors());
|
||||
}
|
||||
|
||||
@Operation(summary = "Get authors (paginated)", description = "Retrieve a page of authors with book counts. Supports cursor pagination plus sort, facet, facet_logic, and query parameters.")
|
||||
@ApiResponse(responseCode = "200", description = "Page of authors returned successfully")
|
||||
@GetMapping("/page")
|
||||
public ResponseEntity<BrowsePage<AuthorSummary>> getAuthorsPaged(
|
||||
@Parameter(hidden = true) Pageable pageable,
|
||||
@Parameter(description = "Comma-separated sort keys; prefix a key with '-' for descending (e.g. sortName or -bookCount)")
|
||||
@RequestParam(required = false) String sort,
|
||||
@Parameter(description = "Facet selection in key:value form; repeatable (e.g. facet=has_asin:false&facet=genre:Horror)")
|
||||
@RequestParam(required = false) List<String> facet,
|
||||
@Parameter(description = "How facet values combine within a group: and, or, or not")
|
||||
@RequestParam(name = "facet_logic", required = false) String facetLogic,
|
||||
@Parameter(description = "Free-text search on author name and ASIN")
|
||||
@RequestParam(required = false) String query,
|
||||
@Parameter(description = "Opaque pagination cursor from a prior response's links")
|
||||
@RequestParam(required = false) String cursor) {
|
||||
return ResponseEntity.ok(authorBrowseService.browse(sort, facet, facetLogic, query, cursor, pageable));
|
||||
}
|
||||
|
||||
@Operation(summary = "Get author facets", description = "Available facet values and author counts for the current user, scoped by the same facet, facet_logic, and query parameters as the page endpoint. Each facet omits its own selections from its counts. book_count, library, and read_status are filter-only and not enumerated here.")
|
||||
@ApiResponse(responseCode = "200", description = "Facet groups returned successfully")
|
||||
@GetMapping("/facets")
|
||||
public ResponseEntity<FacetGroupsResponse> getAuthorFacets(
|
||||
@Parameter(description = "Facet selection in key:value form; repeatable")
|
||||
@RequestParam(required = false) List<String> facet,
|
||||
@Parameter(description = "How facet values combine within a group: and, or, or not")
|
||||
@RequestParam(name = "facet_logic", required = false) String facetLogic,
|
||||
@Parameter(description = "Free-text search applied to the counts")
|
||||
@RequestParam(required = false) String query) {
|
||||
return ResponseEntity.ok(authorFacetService.getFacets(facet, facetLogic, query));
|
||||
}
|
||||
|
||||
@Operation(summary = "Get matching author ids", description = "Returns every author id matching the given sort, facet, facet_logic, and query parameters, in sort order. For select-all over the current filters.")
|
||||
@ApiResponse(responseCode = "200", description = "Matching author ids returned successfully")
|
||||
@GetMapping("/ids")
|
||||
public ResponseEntity<List<Long>> getAuthorIds(
|
||||
@Parameter(description = "Comma-separated sort keys; prefix a key with '-' for descending")
|
||||
@RequestParam(required = false) String sort,
|
||||
@Parameter(description = "Facet selection in key:value form; repeatable")
|
||||
@RequestParam(required = false) List<String> facet,
|
||||
@Parameter(description = "How facet values combine within a group: and, or, or not")
|
||||
@RequestParam(name = "facet_logic", required = false) String facetLogic,
|
||||
@Parameter(description = "Free-text search")
|
||||
@RequestParam(required = false) String query) {
|
||||
return ResponseEntity.ok(authorBrowseService.findAllIds(sort, facet, facetLogic, query));
|
||||
}
|
||||
|
||||
@Operation(summary = "Find author by name", description = "Find an author by exact name (case-insensitive).")
|
||||
@ApiResponse(responseCode = "200", description = "Author found successfully")
|
||||
@GetMapping("/by-name")
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.Tuple;
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import jakarta.persistence.criteria.Root;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.browse.BrowsePage;
|
||||
import org.booklore.browse.BrowsePager;
|
||||
import org.booklore.browse.FacetLogic;
|
||||
import org.booklore.browse.ParamsHash;
|
||||
import org.booklore.browse.SortParser;
|
||||
import org.booklore.browse.SortRegistry;
|
||||
import org.booklore.browse.SortTerm;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.model.dto.AuthorSummary;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(readOnly = true)
|
||||
public class AuthorBrowseService {
|
||||
|
||||
private static final String PAGE_PATH = "/api/v1/authors/page";
|
||||
private static final String FACET_PATH = "/api/v1/authors/facets";
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final AuthorFilterSpecifications filterSpecifications;
|
||||
private final AuthorSortRegistry sortRegistry;
|
||||
private final AuthorVisibleBooks visibleBooks;
|
||||
private final BrowseScopeFactory scopeFactory;
|
||||
private final BrowsePager pager;
|
||||
private final AuthorPhotoIndex photoIndex;
|
||||
private final EntityManager entityManager;
|
||||
|
||||
public BrowsePage<AuthorSummary> browse(String sort, List<String> facet, String facetLogicParam, String query, String cursor, Pageable pageable) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BrowseScope scope = scopeFactory.from(user);
|
||||
|
||||
Map<String, List<String>> facets = BrowseParams.parseFacets(facet);
|
||||
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
||||
String paramsHash = ParamsHash.compute(query, facets, facetLogic);
|
||||
|
||||
BrowsePager.Window window = pager.resolve(sort, cursor, pageable, paramsHash);
|
||||
|
||||
SortRegistry<AuthorEntity> registry = sortRegistry.registry(scope);
|
||||
List<SortTerm> sortTerms = SortParser.parse(window.sort(), registry.keys());
|
||||
Specification<AuthorEntity> spec = filterSpecifications.base(query, facets, facetLogic, scope, null);
|
||||
|
||||
long total = count(spec);
|
||||
List<AuthorEntity> authors = page(spec, registry, sortTerms, scope, window.offset(), window.limit());
|
||||
List<AuthorSummary> summaries = toSummaries(authors, scope);
|
||||
|
||||
return pager.assemble(PAGE_PATH, FACET_PATH, BrowseParams.preserved(facet, facetLogicParam, query),
|
||||
window, total, summaries);
|
||||
}
|
||||
|
||||
public List<Long> findAllIds(String sort, List<String> facet, String facetLogicParam, String query) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BrowseScope scope = scopeFactory.from(user);
|
||||
|
||||
Map<String, List<String>> facets = BrowseParams.parseFacets(facet);
|
||||
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
||||
SortRegistry<AuthorEntity> registry = sortRegistry.registry(scope);
|
||||
List<SortTerm> sortTerms = SortParser.parse(sort, registry.keys());
|
||||
Specification<AuthorEntity> spec = filterSpecifications.base(query, facets, facetLogic, scope, null);
|
||||
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<AuthorEntity> root = cq.from(AuthorEntity.class);
|
||||
cq.select(root.get("id"));
|
||||
Predicate predicate = spec.toPredicate(root, cq, cb);
|
||||
if (predicate != null) {
|
||||
cq.where(predicate);
|
||||
}
|
||||
cq.orderBy(registry.toOrders(sortTerms, root, cq, cb, scope.userId(), null));
|
||||
|
||||
return entityManager.createQuery(cq).getResultList();
|
||||
}
|
||||
|
||||
private long count(Specification<AuthorEntity> spec) {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<AuthorEntity> root = cq.from(AuthorEntity.class);
|
||||
cq.select(cb.count(root));
|
||||
Predicate predicate = spec.toPredicate(root, cq, cb);
|
||||
if (predicate != null) {
|
||||
cq.where(predicate);
|
||||
}
|
||||
return entityManager.createQuery(cq).getSingleResult();
|
||||
}
|
||||
|
||||
private List<AuthorEntity> page(Specification<AuthorEntity> spec, SortRegistry<AuthorEntity> registry,
|
||||
List<SortTerm> sortTerms, BrowseScope scope, long offset, int limit) {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<AuthorEntity> cq = cb.createQuery(AuthorEntity.class);
|
||||
Root<AuthorEntity> root = cq.from(AuthorEntity.class);
|
||||
Predicate predicate = spec.toPredicate(root, cq, cb);
|
||||
if (predicate != null) {
|
||||
cq.where(predicate);
|
||||
}
|
||||
cq.orderBy(registry.toOrders(sortTerms, root, cq, cb, scope.userId(), null));
|
||||
return entityManager.createQuery(cq)
|
||||
.setFirstResult((int) offset)
|
||||
.setMaxResults(limit)
|
||||
.getResultList();
|
||||
}
|
||||
|
||||
private List<AuthorSummary> toSummaries(List<AuthorEntity> authors, BrowseScope scope) {
|
||||
Map<Long, Long> counts = bookCounts(authors, scope);
|
||||
Set<Long> withPhoto = photoIndex.authorIdsWithPhoto();
|
||||
return authors.stream()
|
||||
.map(author -> AuthorSummary.builder()
|
||||
.id(author.getId())
|
||||
.name(author.getName())
|
||||
.asin(author.getAsin())
|
||||
.bookCount(counts.getOrDefault(author.getId(), 0L).intValue())
|
||||
.hasPhoto(withPhoto.contains(author.getId()))
|
||||
.build())
|
||||
.toList();
|
||||
}
|
||||
|
||||
private Map<Long, Long> bookCounts(List<AuthorEntity> authors, BrowseScope scope) {
|
||||
if (authors.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
List<Long> ids = authors.stream().map(AuthorEntity::getId).toList();
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
|
||||
Root<AuthorEntity> root = cq.from(AuthorEntity.class);
|
||||
cq.multiselect(root.get("id").alias("id"),
|
||||
visibleBooks.bookCount(root.get("id"), cq, cb, scope).alias("count"));
|
||||
cq.where(root.get("id").in(ids));
|
||||
|
||||
Map<Long, Long> counts = new HashMap<>();
|
||||
for (Tuple tuple : entityManager.createQuery(cq).getResultList()) {
|
||||
Number count = (Number) tuple.get("count");
|
||||
counts.put((Long) tuple.get("id"), count == null ? 0L : count.longValue());
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
import jakarta.persistence.criteria.Join;
|
||||
import jakarta.persistence.criteria.JoinType;
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import jakarta.persistence.criteria.Root;
|
||||
import jakarta.persistence.criteria.Subquery;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.browse.FacetLogic;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuthorFacetRegistry {
|
||||
|
||||
private static final Set<String> NAMES = Set.of(
|
||||
"has_asin", "has_photo", "has_description", "read_status", "book_count", "library", "genre", "language");
|
||||
|
||||
private final AuthorVisibleBooks visibleBooks;
|
||||
private final AuthorPhotoIndex photoIndex;
|
||||
|
||||
public boolean has(String facetName) {
|
||||
return NAMES.contains(facetName);
|
||||
}
|
||||
|
||||
public Set<String> facetNames() {
|
||||
return NAMES;
|
||||
}
|
||||
|
||||
public Specification<AuthorEntity> toSpecification(String facetName, List<String> values, FacetLogic logic, BrowseScope scope) {
|
||||
return (root, query, cb) -> {
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (String value : values) {
|
||||
predicates.add(valuePredicate(facetName, value, root, query, cb, scope));
|
||||
}
|
||||
if (predicates.isEmpty()) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
return switch (logic == null ? FacetLogic.AND : logic) {
|
||||
case AND -> cb.and(predicates.toArray(Predicate[]::new));
|
||||
case OR -> cb.or(predicates.toArray(Predicate[]::new));
|
||||
case NOT -> cb.not(cb.or(predicates.toArray(Predicate[]::new)));
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
public Predicate valuePredicate(String facetName, String value, Root<AuthorEntity> root,
|
||||
CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
return switch (facetName) {
|
||||
case "has_asin" -> booleanPredicate(cb, hasAsin(root, cb), value, facetName);
|
||||
case "has_photo" -> booleanPredicate(cb, hasPhoto(root, cb), value, facetName);
|
||||
case "has_description" -> booleanPredicate(cb, hasDescription(root, cb), value, facetName);
|
||||
case "read_status" -> readStatus(root, query, cb, scope, value);
|
||||
case "book_count" -> bookCountRange(root, query, cb, scope, value);
|
||||
case "library" -> library(root, query, cb, scope, value);
|
||||
case "genre" -> genre(root, query, cb, scope, value);
|
||||
case "language" -> language(root, query, cb, scope, value);
|
||||
default -> throw ApiError.INVALID_FACET.createException("Unknown facet: " + facetName);
|
||||
};
|
||||
}
|
||||
|
||||
private Predicate hasAsin(Root<AuthorEntity> root, CriteriaBuilder cb) {
|
||||
return cb.and(cb.isNotNull(root.get("asin")), cb.notEqual(root.get("asin"), ""));
|
||||
}
|
||||
|
||||
private Predicate hasDescription(Root<AuthorEntity> root, CriteriaBuilder cb) {
|
||||
return cb.and(cb.isNotNull(root.get("description")), cb.notEqual(root.get("description"), ""));
|
||||
}
|
||||
|
||||
private Predicate hasPhoto(Root<AuthorEntity> root, CriteriaBuilder cb) {
|
||||
Set<Long> ids = photoIndex.authorIdsWithPhoto();
|
||||
return ids.isEmpty() ? cb.disjunction() : root.get("id").in(ids);
|
||||
}
|
||||
|
||||
private Predicate booleanPredicate(CriteriaBuilder cb, Predicate truePredicate, String value, String facetName) {
|
||||
return switch (value.trim().toLowerCase(Locale.ROOT)) {
|
||||
case "true" -> truePredicate;
|
||||
case "false" -> truePredicate.not();
|
||||
default -> throw ApiError.INVALID_FACET.createException(
|
||||
"Facet " + facetName + " accepts true or false, got: " + value);
|
||||
};
|
||||
}
|
||||
|
||||
private Predicate readStatus(Root<AuthorEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
|
||||
BrowseScope scope, String value) {
|
||||
ReadStatus status;
|
||||
try {
|
||||
status = ReadStatus.valueOf(value.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw ApiError.INVALID_FACET.createException(
|
||||
"Invalid read_status value: " + value + ". Valid values: " + List.of(ReadStatus.values()));
|
||||
}
|
||||
return visibleBooks.hasBookWithReadStatus(root.get("id"), query, cb, scope, status);
|
||||
}
|
||||
|
||||
private Predicate bookCountRange(Root<AuthorEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
|
||||
BrowseScope scope, String value) {
|
||||
long[] bounds = parseRange(value);
|
||||
Subquery<Long> count = visibleBooks.bookCount(root.get("id"), query, cb, scope);
|
||||
if (bounds[0] >= 0 && bounds[1] >= 0) {
|
||||
return cb.and(cb.greaterThanOrEqualTo(count, bounds[0]), cb.lessThanOrEqualTo(count, bounds[1]));
|
||||
}
|
||||
if (bounds[0] >= 0) {
|
||||
return cb.greaterThanOrEqualTo(count, bounds[0]);
|
||||
}
|
||||
return cb.lessThanOrEqualTo(count, bounds[1]);
|
||||
}
|
||||
|
||||
private static long[] parseRange(String value) {
|
||||
String range = value.trim();
|
||||
try {
|
||||
if (!range.contains("-")) {
|
||||
long exact = Long.parseLong(range);
|
||||
requireNonNegative(exact, value);
|
||||
return new long[]{exact, exact};
|
||||
}
|
||||
int dash = range.indexOf('-');
|
||||
String left = range.substring(0, dash).trim();
|
||||
String right = range.substring(dash + 1).trim();
|
||||
long min = left.isEmpty() ? -1 : Long.parseLong(left);
|
||||
long max = right.isEmpty() ? -1 : Long.parseLong(right);
|
||||
if (min < 0 && max < 0) {
|
||||
throw ApiError.INVALID_FACET.createException("Facet book_count range needs at least one bound: " + value);
|
||||
}
|
||||
if (!left.isEmpty()) {
|
||||
requireNonNegative(min, value);
|
||||
}
|
||||
if (!right.isEmpty()) {
|
||||
requireNonNegative(max, value);
|
||||
}
|
||||
if (min >= 0 && max >= 0 && min > max) {
|
||||
throw ApiError.INVALID_FACET.createException("Facet book_count range is inverted: " + value);
|
||||
}
|
||||
return new long[]{min, max};
|
||||
} catch (NumberFormatException e) {
|
||||
throw ApiError.INVALID_FACET.createException(
|
||||
"Facet book_count must be a count or range (e.g. 4, 2-10, 5-, -3), got: " + value);
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireNonNegative(long bound, String value) {
|
||||
if (bound < 0) {
|
||||
throw ApiError.INVALID_FACET.createException("Facet book_count bounds must be non-negative: " + value);
|
||||
}
|
||||
}
|
||||
|
||||
private Predicate library(Root<AuthorEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
|
||||
BrowseScope scope, String value) {
|
||||
long libraryId;
|
||||
try {
|
||||
libraryId = Long.parseLong(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
throw ApiError.INVALID_FACET.createException("Facet library expects a library id, got: " + value);
|
||||
}
|
||||
return visibleBooks.exists(root.get("id"), query, cb, scope,
|
||||
(book, metadata, q, criteria) -> criteria.equal(book.get("library").get("id"), libraryId));
|
||||
}
|
||||
|
||||
private Predicate genre(Root<AuthorEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
|
||||
BrowseScope scope, String value) {
|
||||
String lowered = value.trim().toLowerCase(Locale.ROOT);
|
||||
return visibleBooks.exists(root.get("id"), query, cb, scope,
|
||||
(book, metadata, q, criteria) -> {
|
||||
Join<?, ?> category = metadata.join("categories", JoinType.INNER);
|
||||
return criteria.equal(criteria.lower(category.get("name")), lowered);
|
||||
});
|
||||
}
|
||||
|
||||
private Predicate language(Root<AuthorEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
|
||||
BrowseScope scope, String value) {
|
||||
String lowered = value.trim().toLowerCase(Locale.ROOT);
|
||||
return visibleBooks.exists(root.get("id"), query, cb, scope,
|
||||
(book, metadata, q, criteria) -> criteria.equal(criteria.lower(metadata.get("language")), lowered));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.Tuple;
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
import jakarta.persistence.criteria.Expression;
|
||||
import jakarta.persistence.criteria.Join;
|
||||
import jakarta.persistence.criteria.JoinType;
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import jakarta.persistence.criteria.Root;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.browse.FacetLogic;
|
||||
import org.booklore.browse.ParamsHash;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(readOnly = true)
|
||||
public class AuthorFacetService {
|
||||
|
||||
private static final String PAGE_PATH = "/api/v1/authors/page";
|
||||
private static final String FACET_PATH = "/api/v1/authors/facets";
|
||||
private static final int MAX_VALUES = 100;
|
||||
|
||||
private static final List<ValueFacetDef> VALUE_FACETS = List.of(
|
||||
new ValueFacetDef("has_asin", "ASIN", List.of("true", "false")),
|
||||
new ValueFacetDef("has_photo", "Photo", List.of("true", "false")),
|
||||
new ValueFacetDef("has_description", "Description", List.of("true", "false")));
|
||||
|
||||
private static final List<GroupByFacetDef> GROUP_BY_FACETS = List.of(
|
||||
new GroupByFacetDef("genre", "Genre", metadata -> metadata.join("categories", JoinType.LEFT).get("name")),
|
||||
new GroupByFacetDef("language", "Language", metadata -> metadata.get("language")));
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final AuthorFilterSpecifications filterSpecifications;
|
||||
private final AuthorFacetRegistry facetRegistry;
|
||||
private final AuthorSortRegistry sortRegistry;
|
||||
private final BrowseScopeFactory scopeFactory;
|
||||
private final AuthorVisibleBooks visibleBooks;
|
||||
private final EntityManager entityManager;
|
||||
|
||||
private final Cache<String, FacetGroupsResponse> cache = Caffeine.newBuilder()
|
||||
.expireAfterWrite(Duration.ofSeconds(30))
|
||||
.maximumSize(200)
|
||||
.build();
|
||||
|
||||
public FacetGroupsResponse getFacets(List<String> facet, String facetLogicParam, String query) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BrowseScope scope = scopeFactory.from(user);
|
||||
|
||||
Map<String, List<String>> facets = BrowseParams.parseFacets(facet);
|
||||
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
||||
|
||||
String cacheKey = scope.userId() + ":" + ParamsHash.compute(query, facets, facetLogic);
|
||||
return cache.get(cacheKey, key -> {
|
||||
String preserved = BrowseParams.preserved(facet, facetLogicParam, query);
|
||||
FacetResponseBuilder builder = new FacetResponseBuilder(PAGE_PATH, FACET_PATH, preserved, facet);
|
||||
List<FacetGroup> groups = new ArrayList<>();
|
||||
groups.add(builder.sortGroup(sortRegistry.registry(scope).keys()));
|
||||
for (ValueFacetDef def : VALUE_FACETS) {
|
||||
Specification<AuthorEntity> base = filterSpecifications.base(query, facets, facetLogic, scope, def.key());
|
||||
groups.add(builder.group(def.key(), def.title(), valueCounts(def, base, scope)));
|
||||
}
|
||||
for (GroupByFacetDef def : GROUP_BY_FACETS) {
|
||||
Specification<AuthorEntity> base = filterSpecifications.base(query, facets, facetLogic, scope, def.key());
|
||||
groups.add(builder.group(def.key(), def.title(), groupByCounts(def, base, scope)));
|
||||
}
|
||||
return new FacetGroupsResponse(builder.selfLinks(), groups);
|
||||
});
|
||||
}
|
||||
|
||||
void clearCache() {
|
||||
cache.invalidateAll();
|
||||
}
|
||||
|
||||
private List<FacetResponseBuilder.FacetCount> valueCounts(ValueFacetDef def, Specification<AuthorEntity> base, BrowseScope scope) {
|
||||
List<FacetResponseBuilder.FacetCount> counts = new ArrayList<>();
|
||||
for (String value : def.values()) {
|
||||
long count = countAuthors(base, def.key(), value, scope);
|
||||
if (count > 0) {
|
||||
counts.add(new FacetResponseBuilder.FacetCount(value, count));
|
||||
}
|
||||
}
|
||||
counts.sort(Comparator.comparingLong(FacetResponseBuilder.FacetCount::count).reversed()
|
||||
.thenComparing(FacetResponseBuilder.FacetCount::value));
|
||||
return counts;
|
||||
}
|
||||
|
||||
private long countAuthors(Specification<AuthorEntity> base, String facetKey, String value, BrowseScope scope) {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||
Root<AuthorEntity> root = cq.from(AuthorEntity.class);
|
||||
cq.select(cb.count(root));
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
Predicate basePredicate = base.toPredicate(root, cq, cb);
|
||||
if (basePredicate != null) {
|
||||
predicates.add(basePredicate);
|
||||
}
|
||||
predicates.add(facetRegistry.valuePredicate(facetKey, value, root, cq, cb, scope));
|
||||
cq.where(predicates.toArray(Predicate[]::new));
|
||||
return entityManager.createQuery(cq).getSingleResult();
|
||||
}
|
||||
|
||||
private List<FacetResponseBuilder.FacetCount> groupByCounts(GroupByFacetDef def, Specification<AuthorEntity> base, BrowseScope scope) {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
|
||||
Root<AuthorEntity> root = cq.from(AuthorEntity.class);
|
||||
Join<?, ?> metadata = root.join("bookMetadataEntityList", JoinType.INNER);
|
||||
Expression<?> value = def.value().apply(metadata);
|
||||
Expression<Long> count = cb.countDistinct(root.get("id"));
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
Predicate basePredicate = base.toPredicate(root, cq, cb);
|
||||
if (basePredicate != null) {
|
||||
predicates.add(basePredicate);
|
||||
}
|
||||
predicates.add(cb.isNotNull(value));
|
||||
predicates.add(visibleBooks.bookIdVisible(metadata.get("bookId"), cq, cb, scope));
|
||||
|
||||
cq.multiselect(value.alias("value"), count.alias("count"));
|
||||
cq.where(predicates.toArray(Predicate[]::new));
|
||||
cq.groupBy(value);
|
||||
cq.orderBy(cb.desc(count), cb.asc(value));
|
||||
|
||||
return entityManager.createQuery(cq).setMaxResults(MAX_VALUES).getResultList().stream()
|
||||
.map(tuple -> new FacetResponseBuilder.FacetCount(String.valueOf(tuple.get("value")), ((Number) tuple.get("count")).longValue()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private record ValueFacetDef(String key, String title, List<String> values) {
|
||||
}
|
||||
|
||||
private record GroupByFacetDef(String key, String title, Function<Join<?, ?>, Expression<?>> value) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.browse.FacetLogic;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuthorFilterSpecifications {
|
||||
|
||||
private final AuthorFacetRegistry facetRegistry;
|
||||
private final AuthorVisibleBooks visibleBooks;
|
||||
|
||||
public Specification<AuthorEntity> base(String query, Map<String, List<String>> facets, FacetLogic facetLogic,
|
||||
BrowseScope scope, String omitFacet) {
|
||||
List<Specification<AuthorEntity>> specs = new ArrayList<>();
|
||||
if (!scope.isAdmin()) {
|
||||
specs.add((root, cq, cb) -> visibleBooks.exists(root.get("id"), cq, cb, scope));
|
||||
}
|
||||
if (query != null && !query.isBlank()) {
|
||||
String pattern = "%" + query.trim().toLowerCase(Locale.ROOT) + "%";
|
||||
specs.add((root, cq, cb) -> cb.or(
|
||||
cb.like(cb.lower(root.get("name")), pattern),
|
||||
cb.like(cb.lower(root.get("asin")), pattern)));
|
||||
}
|
||||
for (Map.Entry<String, List<String>> entry : facets.entrySet()) {
|
||||
if (Objects.equals(entry.getKey(), omitFacet)) {
|
||||
continue;
|
||||
}
|
||||
if (!facetRegistry.has(entry.getKey())) {
|
||||
throw ApiError.INVALID_FACET.createException("Unknown facet: " + entry.getKey());
|
||||
}
|
||||
specs.add(facetRegistry.toSpecification(entry.getKey(), entry.getValue(), facetLogic, scope));
|
||||
}
|
||||
return Specification.allOf(specs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.util.FileService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Duration;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuthorPhotoIndex {
|
||||
|
||||
private static final String KEY = "ids";
|
||||
|
||||
private final FileService fileService;
|
||||
|
||||
private final Cache<String, Set<Long>> cache = Caffeine.newBuilder()
|
||||
.expireAfterWrite(Duration.ofSeconds(30))
|
||||
.build();
|
||||
|
||||
public Set<Long> authorIdsWithPhoto() {
|
||||
return cache.get(KEY, key -> scan());
|
||||
}
|
||||
|
||||
void clearCache() {
|
||||
cache.invalidateAll();
|
||||
}
|
||||
|
||||
private Set<Long> scan() {
|
||||
Path root = Paths.get(fileService.getAuthorImagesRoot());
|
||||
if (!Files.isDirectory(root)) {
|
||||
return Set.of();
|
||||
}
|
||||
Set<Long> ids = new HashSet<>();
|
||||
try (Stream<Path> dirs = Files.list(root)) {
|
||||
dirs.forEach(dir -> {
|
||||
long id;
|
||||
try {
|
||||
id = Long.parseLong(dir.getFileName().toString());
|
||||
} catch (NumberFormatException e) {
|
||||
return;
|
||||
}
|
||||
if (Files.exists(Paths.get(fileService.getAuthorThumbnailFile(id)))) {
|
||||
ids.add(id);
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to scan author images root {}", root, e);
|
||||
return Set.of();
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import jakarta.persistence.criteria.Expression;
|
||||
import jakarta.persistence.criteria.Order;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.browse.SortContext;
|
||||
import org.booklore.browse.SortOrderBuilder;
|
||||
import org.booklore.browse.SortRegistry;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuthorSortRegistry {
|
||||
|
||||
private final AuthorVisibleBooks visibleBooks;
|
||||
|
||||
public SortRegistry<AuthorEntity> registry(BrowseScope scope) {
|
||||
SortRegistry<AuthorEntity> registry = new SortRegistry<>();
|
||||
|
||||
registry.register("id", rootField("id"));
|
||||
registry.register("name", rootField("name"));
|
||||
registry.register("sortName", rootField("sortName"));
|
||||
|
||||
registry.register("bookCount", ctx ->
|
||||
List.of(order(ctx, visibleBooks.bookCount(ctx.root().get("id"), ctx.query(), ctx.cb(), scope))));
|
||||
registry.register("seriesCount", ctx ->
|
||||
List.of(order(ctx, visibleBooks.seriesCount(ctx.root().get("id"), ctx.query(), ctx.cb(), scope))));
|
||||
registry.register("addedOn", ctx ->
|
||||
List.of(order(ctx, visibleBooks.latestAddedOn(ctx.root().get("id"), ctx.query(), ctx.cb(), scope))));
|
||||
registry.register("lastReadTime", ctx ->
|
||||
List.of(order(ctx, visibleBooks.lastReadTime(ctx.root().get("id"), ctx.query(), ctx.cb(), scope))));
|
||||
registry.register("personalRating", ctx ->
|
||||
List.of(order(ctx, visibleBooks.avgPersonalRating(ctx.root().get("id"), ctx.query(), ctx.cb(), scope))));
|
||||
|
||||
for (String field : List.of("amazonRating", "goodreadsRating", "hardcoverRating", "ranobedbRating")) {
|
||||
registry.register(field, ctx ->
|
||||
List.of(order(ctx, visibleBooks.avgMetadataRating(field, ctx.root().get("id"), ctx.query(), ctx.cb(), scope))));
|
||||
}
|
||||
|
||||
return registry;
|
||||
}
|
||||
|
||||
private static SortOrderBuilder<AuthorEntity> rootField(String field) {
|
||||
return ctx -> List.of(order(ctx, ctx.root().get(field)));
|
||||
}
|
||||
|
||||
private static Order order(SortContext<AuthorEntity> ctx, Expression<?> expression) {
|
||||
return ctx.descending() ? ctx.cb().desc(expression) : ctx.cb().asc(expression);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
import jakarta.persistence.criteria.Expression;
|
||||
import jakarta.persistence.criteria.Join;
|
||||
import jakarta.persistence.criteria.Path;
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import jakarta.persistence.criteria.Root;
|
||||
import jakarta.persistence.criteria.Subquery;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class AuthorVisibleBooks {
|
||||
|
||||
public interface BookCondition {
|
||||
Predicate apply(Root<BookEntity> book, Join<?, ?> metadata, CriteriaQuery<?> query, CriteriaBuilder cb);
|
||||
}
|
||||
|
||||
public Predicate exists(Path<?> authorId, CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
return exists(authorId, query, cb, scope, null);
|
||||
}
|
||||
|
||||
public Predicate exists(Path<?> authorId, CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope, BookCondition extra) {
|
||||
Subquery<Long> sq = query.subquery(Long.class);
|
||||
Root<BookEntity> book = sq.from(BookEntity.class);
|
||||
Join<?, ?> metadata = book.join("metadata");
|
||||
sq.select(cb.literal(1L));
|
||||
List<Predicate> predicates = predicates(authorId, book, metadata, query, cb, scope);
|
||||
if (extra != null) {
|
||||
predicates.add(extra.apply(book, metadata, query, cb));
|
||||
}
|
||||
sq.where(predicates.toArray(Predicate[]::new));
|
||||
return cb.exists(sq);
|
||||
}
|
||||
|
||||
public Subquery<Long> bookCount(Path<?> authorId, CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
Subquery<Long> sq = query.subquery(Long.class);
|
||||
Root<BookEntity> book = sq.from(BookEntity.class);
|
||||
Join<?, ?> metadata = book.join("metadata");
|
||||
sq.select(cb.count(book));
|
||||
sq.where(predicates(authorId, book, metadata, query, cb, scope).toArray(Predicate[]::new));
|
||||
return sq;
|
||||
}
|
||||
|
||||
public Subquery<Long> seriesCount(Path<?> authorId, CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
Subquery<Long> sq = query.subquery(Long.class);
|
||||
Root<BookEntity> book = sq.from(BookEntity.class);
|
||||
Join<?, ?> metadata = book.join("metadata");
|
||||
sq.select(cb.countDistinct(metadata.get("seriesName")));
|
||||
List<Predicate> predicates = predicates(authorId, book, metadata, query, cb, scope);
|
||||
predicates.add(cb.isNotNull(metadata.get("seriesName")));
|
||||
sq.where(predicates.toArray(Predicate[]::new));
|
||||
return sq;
|
||||
}
|
||||
|
||||
public Subquery<Instant> latestAddedOn(Path<?> authorId, CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
Subquery<Instant> sq = query.subquery(Instant.class);
|
||||
Root<BookEntity> book = sq.from(BookEntity.class);
|
||||
Join<?, ?> metadata = book.join("metadata");
|
||||
sq.select(cb.greatest(book.<Instant>get("addedOn")));
|
||||
sq.where(predicates(authorId, book, metadata, query, cb, scope).toArray(Predicate[]::new));
|
||||
return sq;
|
||||
}
|
||||
|
||||
public Subquery<Instant> lastReadTime(Path<?> authorId, CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
Subquery<Instant> sq = query.subquery(Instant.class);
|
||||
Root<BookEntity> book = sq.from(BookEntity.class);
|
||||
Join<?, ?> metadata = book.join("metadata");
|
||||
Join<?, ?> progress = book.join("userBookProgress");
|
||||
sq.select(cb.greatest(progress.<Instant>get("lastReadTime")));
|
||||
List<Predicate> predicates = predicates(authorId, book, metadata, query, cb, scope);
|
||||
predicates.add(userMatches(progress, cb, scope));
|
||||
sq.where(predicates.toArray(Predicate[]::new));
|
||||
return sq;
|
||||
}
|
||||
|
||||
public Subquery<Double> avgMetadataRating(String field, Path<?> authorId, CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
Subquery<Double> sq = query.subquery(Double.class);
|
||||
Root<BookEntity> book = sq.from(BookEntity.class);
|
||||
Join<?, ?> metadata = book.join("metadata");
|
||||
sq.select(cb.avg(metadata.get(field)));
|
||||
sq.where(predicates(authorId, book, metadata, query, cb, scope).toArray(Predicate[]::new));
|
||||
return sq;
|
||||
}
|
||||
|
||||
public Subquery<Double> avgPersonalRating(Path<?> authorId, CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
Subquery<Double> sq = query.subquery(Double.class);
|
||||
Root<BookEntity> book = sq.from(BookEntity.class);
|
||||
Join<?, ?> metadata = book.join("metadata");
|
||||
Join<?, ?> progress = book.join("userBookProgress");
|
||||
sq.select(cb.avg(progress.get("personalRating")));
|
||||
List<Predicate> predicates = predicates(authorId, book, metadata, query, cb, scope);
|
||||
predicates.add(userMatches(progress, cb, scope));
|
||||
sq.where(predicates.toArray(Predicate[]::new));
|
||||
return sq;
|
||||
}
|
||||
|
||||
public Predicate bookIdVisible(Expression<Long> bookId, CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
Subquery<Long> sq = query.subquery(Long.class);
|
||||
Root<BookEntity> book = sq.from(BookEntity.class);
|
||||
sq.select(cb.literal(1L));
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
predicates.add(cb.equal(book.get("id"), bookId));
|
||||
predicates.add(scope.visibleBook(book, query, cb));
|
||||
sq.where(predicates.toArray(Predicate[]::new));
|
||||
return cb.exists(sq);
|
||||
}
|
||||
|
||||
private Predicate hasProgressStatus(Root<BookEntity> book, CriteriaQuery<?> query, CriteriaBuilder cb,
|
||||
BrowseScope scope, Collection<ReadStatus> statuses) {
|
||||
Subquery<Long> sq = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> progress = sq.from(UserBookProgressEntity.class);
|
||||
sq.select(cb.literal(1L));
|
||||
sq.where(
|
||||
cb.equal(progress.get("book").get("id"), book.get("id")),
|
||||
userMatches(progress, cb, scope),
|
||||
progress.get("readStatus").in(statuses));
|
||||
return cb.exists(sq);
|
||||
}
|
||||
|
||||
public Predicate hasBookWithReadStatus(Path<?> authorId, CriteriaQuery<?> query, CriteriaBuilder cb,
|
||||
BrowseScope scope, ReadStatus status) {
|
||||
BookCondition condition = status == ReadStatus.UNSET
|
||||
? (book, metadata, q, criteria) -> criteria.or(
|
||||
criteria.not(hasAnyProgress(book, q, criteria, scope)),
|
||||
hasProgressStatus(book, q, criteria, scope, List.of(ReadStatus.UNSET)))
|
||||
: (book, metadata, q, criteria) -> hasProgressStatus(book, q, criteria, scope, List.of(status));
|
||||
return exists(authorId, query, cb, scope, condition);
|
||||
}
|
||||
|
||||
private Predicate hasAnyProgress(Root<BookEntity> book, CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
Subquery<Long> sq = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> progress = sq.from(UserBookProgressEntity.class);
|
||||
sq.select(cb.literal(1L));
|
||||
sq.where(
|
||||
cb.equal(progress.get("book").get("id"), book.get("id")),
|
||||
userMatches(progress, cb, scope));
|
||||
return cb.exists(sq);
|
||||
}
|
||||
|
||||
private List<Predicate> predicates(Path<?> authorId, Root<BookEntity> book, Join<?, ?> metadata,
|
||||
CriteriaQuery<?> query, CriteriaBuilder cb, BrowseScope scope) {
|
||||
Join<?, ?> author = metadata.join("authors");
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
predicates.add(cb.equal(author.get("id"), authorId));
|
||||
predicates.add(scope.visibleBook(book, query, cb));
|
||||
return predicates;
|
||||
}
|
||||
|
||||
private Predicate userMatches(Path<?> progress, CriteriaBuilder cb, BrowseScope scope) {
|
||||
return scope.userId() != null
|
||||
? cb.equal(progress.get("user").get("id"), scope.userId())
|
||||
: cb.disjunction();
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,10 @@ public class FileService {
|
||||
return Paths.get(appProperties.getPathConfig(), IMAGES_DIR, String.valueOf(bookId), AUDIOBOOK_COVER_FILENAME).toString();
|
||||
}
|
||||
|
||||
public String getAuthorImagesRoot() {
|
||||
return Paths.get(appProperties.getPathConfig(), AUTHOR_IMAGES_DIR).toString();
|
||||
}
|
||||
|
||||
public String getAuthorImagesFolder(long authorId) {
|
||||
return Paths.get(appProperties.getPathConfig(), AUTHOR_IMAGES_DIR, String.valueOf(authorId)).toString();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import org.booklore.BookloreApplication;
|
||||
import org.booklore.browse.BrowsePage;
|
||||
import org.booklore.browse.Link;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.APIException;
|
||||
import org.booklore.model.dto.AuthorSummary;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.BookMetadataEntity;
|
||||
import org.booklore.model.entity.CategoryEntity;
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.booklore.model.entity.UserContentRestrictionEntity;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.model.enums.ContentRestrictionMode;
|
||||
import org.booklore.model.enums.ContentRestrictionType;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.model.entity.TagEntity;
|
||||
import org.booklore.service.task.TaskCronService;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SpringBootTest(classes = BookloreApplication.class)
|
||||
@Transactional
|
||||
@TestPropertySource(properties = {
|
||||
"spring.flyway.enabled=false",
|
||||
"spring.jpa.hibernate.ddl-auto=create-drop",
|
||||
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
|
||||
"spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect",
|
||||
"spring.datasource.url=jdbc:h2:mem:authorbrowseservicetest;DB_CLOSE_DELAY=-1;NON_KEYWORDS=VALUE",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver",
|
||||
"spring.datasource.username=sa",
|
||||
"spring.datasource.password=",
|
||||
"app.path-config=build/tmp/test-config",
|
||||
"app.bookdrop-folder=build/tmp/test-bookdrop",
|
||||
"spring.main.allow-bean-definition-overriding=true",
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false"
|
||||
})
|
||||
@Import(AuthorBrowseServiceTest.TestConfig.class)
|
||||
class AuthorBrowseServiceTest {
|
||||
|
||||
@Autowired
|
||||
private AuthorBrowseService browseService;
|
||||
@MockitoBean
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager em;
|
||||
|
||||
private BookLoreUserEntity userEntity;
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
private final Map<String, CategoryEntity> categories = new HashMap<>();
|
||||
private final Map<String, TagEntity> tags = new HashMap<>();
|
||||
|
||||
@TestConfiguration
|
||||
public static class TestConfig {
|
||||
@Bean("flyway")
|
||||
@Primary
|
||||
public Flyway flyway() {
|
||||
return mock(Flyway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public TaskCronService taskCronService() {
|
||||
return mock(TaskCronService.class);
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void seed() {
|
||||
userEntity = BookLoreUserEntity.builder().username("reader").passwordHash("x").name("Reader").build();
|
||||
em.persist(userEntity);
|
||||
library = LibraryEntity.builder().name("Lib").icon("book").watch(false)
|
||||
.formatPriority(List.of(BookFileType.EPUB)).build();
|
||||
em.persist(library);
|
||||
libraryPath = LibraryPathEntity.builder().library(library).path("/p").build();
|
||||
em.persist(libraryPath);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(nonAdminUser());
|
||||
}
|
||||
|
||||
private BookLoreUser nonAdminUser() {
|
||||
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(false);
|
||||
return BookLoreUser.builder()
|
||||
.id(userEntity.getId())
|
||||
.assignedLibraries(List.of(Library.builder().id(library.getId()).build()))
|
||||
.permissions(permissions)
|
||||
.build();
|
||||
}
|
||||
|
||||
private BookLoreUser adminUser() {
|
||||
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(true);
|
||||
return BookLoreUser.builder()
|
||||
.id(userEntity.getId())
|
||||
.assignedLibraries(List.of())
|
||||
.permissions(permissions)
|
||||
.build();
|
||||
}
|
||||
|
||||
private AuthorEntity author(String name) {
|
||||
AuthorEntity author = AuthorEntity.builder().name(name).build();
|
||||
em.persist(author);
|
||||
return author;
|
||||
}
|
||||
|
||||
private BookEntity book(String title, LibraryEntity lib, LibraryPathEntity path, List<AuthorEntity> authors) {
|
||||
return book(title, lib, path, authors, null, null, null);
|
||||
}
|
||||
|
||||
private BookEntity book(String title, LibraryEntity lib, LibraryPathEntity path, List<AuthorEntity> authors,
|
||||
String seriesName, List<String> categoryNames, String language) {
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.library(lib).libraryPath(path).addedOn(Instant.now()).deleted(false).build();
|
||||
em.persist(bookEntity);
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(bookEntity).title(title).seriesName(seriesName).language(language).build();
|
||||
metadata.setAuthors(new java.util.ArrayList<>(authors));
|
||||
if (categoryNames != null) {
|
||||
metadata.setCategories(categoryNames.stream().map(this::category).collect(Collectors.toSet()));
|
||||
}
|
||||
em.persist(metadata);
|
||||
bookEntity.setMetadata(metadata);
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
private CategoryEntity category(String name) {
|
||||
return categories.computeIfAbsent(name, n -> {
|
||||
CategoryEntity e = CategoryEntity.builder().name(n).build();
|
||||
em.persist(e);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
|
||||
private TagEntity tag(String name) {
|
||||
return tags.computeIfAbsent(name, n -> {
|
||||
TagEntity e = TagEntity.builder().name(n).build();
|
||||
em.persist(e);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
|
||||
private void progress(BookEntity book, ReadStatus status) {
|
||||
progress(book, status, null);
|
||||
}
|
||||
|
||||
private void progress(BookEntity book, ReadStatus status, Integer personalRating) {
|
||||
em.persist(UserBookProgressEntity.builder()
|
||||
.user(userEntity).book(book).readStatus(status).lastReadTime(Instant.now())
|
||||
.personalRating(personalRating).build());
|
||||
}
|
||||
|
||||
private BrowsePage<AuthorSummary> browse(String sort, List<String> facet, String query, String cursor, int page, int size) {
|
||||
return browse(sort, facet, null, query, cursor, page, size);
|
||||
}
|
||||
|
||||
private BrowsePage<AuthorSummary> browse(String sort, List<String> facet, String facetLogic, String query, String cursor, int page, int size) {
|
||||
return browseService.browse(sort, facet, facetLogic, query, cursor, PageRequest.of(page, size));
|
||||
}
|
||||
|
||||
private List<Long> ids(BrowsePage<AuthorSummary> page) {
|
||||
return page.content().stream().map(AuthorSummary::getId).toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsPageWithTotalsAndCursorAndLinks() {
|
||||
AuthorEntity alice = author("Alice");
|
||||
AuthorEntity bob = author("Bob");
|
||||
book("A", library, libraryPath, List.of(alice));
|
||||
book("B", library, libraryPath, List.of(bob));
|
||||
em.flush();
|
||||
|
||||
BrowsePage<AuthorSummary> result = browse(null, null, null, null, 0, 20);
|
||||
|
||||
assertThat(result.content()).hasSize(2);
|
||||
assertThat(result.page().totalElements()).isEqualTo(2);
|
||||
assertThat(result.page().cursor()).isNotBlank();
|
||||
assertThat(result.links().stream().anyMatch(l -> l.rel().contains("self"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sortByNameAndSortName() {
|
||||
AuthorEntity zeta = author("Zeta Abbott");
|
||||
AuthorEntity anna = author("Anna Zimmer");
|
||||
book("A", library, libraryPath, List.of(zeta));
|
||||
book("B", library, libraryPath, List.of(anna));
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse("name", null, null, null, 0, 20))).containsExactly(anna.getId(), zeta.getId());
|
||||
assertThat(ids(browse("-name", null, null, null, 0, 20))).containsExactly(zeta.getId(), anna.getId());
|
||||
assertThat(ids(browse("sortName", null, null, null, 0, 20))).containsExactly(zeta.getId(), anna.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sortByBookCount() {
|
||||
AuthorEntity prolific = author("Prolific");
|
||||
AuthorEntity oneHit = author("One Hit");
|
||||
book("A", library, libraryPath, List.of(prolific));
|
||||
book("B", library, libraryPath, List.of(prolific));
|
||||
book("C", library, libraryPath, List.of(oneHit));
|
||||
em.flush();
|
||||
|
||||
BrowsePage<AuthorSummary> result = browse("-bookCount", null, null, null, 0, 20);
|
||||
assertThat(ids(result)).containsExactly(prolific.getId(), oneHit.getId());
|
||||
assertThat(result.content().get(0).getBookCount()).isEqualTo(2);
|
||||
assertThat(result.content().get(1).getBookCount()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sortBySeriesCountAndAddedOn() {
|
||||
AuthorEntity serial = author("Serial");
|
||||
AuthorEntity standalone = author("Standalone");
|
||||
book("S1", library, libraryPath, List.of(serial), "Saga", null, null)
|
||||
.setAddedOn(Instant.parse("2024-01-01T00:00:00Z"));
|
||||
book("S2", library, libraryPath, List.of(serial), "Other Saga", null, null)
|
||||
.setAddedOn(Instant.parse("2024-02-01T00:00:00Z"));
|
||||
book("Solo", library, libraryPath, List.of(standalone))
|
||||
.setAddedOn(Instant.parse("2024-03-01T00:00:00Z"));
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse("-seriesCount", null, null, null, 0, 20)))
|
||||
.containsExactly(serial.getId(), standalone.getId());
|
||||
assertThat(ids(browse("-addedOn", null, null, null, 0, 20)))
|
||||
.containsExactly(standalone.getId(), serial.getId());
|
||||
assertThat(ids(browse("addedOn", null, null, null, 0, 20)))
|
||||
.containsExactly(serial.getId(), standalone.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sortByLastReadTimeAndAvgRating() {
|
||||
AuthorEntity read = author("Read Author");
|
||||
AuthorEntity unread = author("Unread Author");
|
||||
BookEntity readBook = book("R", library, libraryPath, List.of(read));
|
||||
BookEntity unreadBook = book("U", library, libraryPath, List.of(unread));
|
||||
readBook.getMetadata().setGoodreadsRating(2.0);
|
||||
unreadBook.getMetadata().setGoodreadsRating(4.5);
|
||||
progress(readBook, ReadStatus.READ, 5);
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse("-lastReadTime", null, null, null, 0, 20)))
|
||||
.containsExactly(read.getId(), unread.getId());
|
||||
assertThat(ids(browse("-goodreadsRating", null, null, null, 0, 20)))
|
||||
.containsExactly(unread.getId(), read.getId());
|
||||
assertThat(ids(browse("goodreadsRating", null, null, null, 0, 20)))
|
||||
.containsExactly(read.getId(), unread.getId());
|
||||
assertThat(ids(browse("-personalRating", null, null, null, 0, 20)))
|
||||
.containsExactly(read.getId(), unread.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void facetLogicCombinesSelectedValues() {
|
||||
AuthorEntity horrorOnly = author("Horror Only");
|
||||
AuthorEntity romanceOnly = author("Romance Only");
|
||||
AuthorEntity both = author("Both");
|
||||
AuthorEntity neither = author("Neither");
|
||||
book("H", library, libraryPath, List.of(horrorOnly), null, List.of("Horror"), null);
|
||||
book("R", library, libraryPath, List.of(romanceOnly), null, List.of("Romance"), null);
|
||||
book("B", library, libraryPath, List.of(both), null, List.of("Horror", "Romance"), null);
|
||||
book("N", library, libraryPath, List.of(neither), null, List.of("Fantasy"), null);
|
||||
em.flush();
|
||||
|
||||
List<String> facets = List.of("genre:Horror", "genre:Romance");
|
||||
assertThat(ids(browse("name", facets, "or", null, null, 0, 20)))
|
||||
.containsExactly(both.getId(), horrorOnly.getId(), romanceOnly.getId());
|
||||
assertThat(ids(browse("name", facets, "and", null, null, 0, 20)))
|
||||
.containsExactly(both.getId());
|
||||
assertThat(ids(browse("name", facets, "not", null, null, 0, 20)))
|
||||
.containsExactly(neither.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryFiltersOnNameAndAsin() {
|
||||
AuthorEntity tolkien = author("J.R.R. Tolkien");
|
||||
tolkien.setAsin("B000AP9A6K");
|
||||
AuthorEntity herbert = author("Frank Herbert");
|
||||
book("A", library, libraryPath, List.of(tolkien));
|
||||
book("B", library, libraryPath, List.of(herbert));
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse(null, null, "tolkien", null, 0, 20))).containsExactly(tolkien.getId());
|
||||
assertThat(ids(browse(null, null, "b000ap9a6k", null, 0, 20))).containsExactly(tolkien.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void hasAsinFacetIsApplied() {
|
||||
AuthorEntity matched = author("Matched");
|
||||
matched.setAsin("B0FAKE");
|
||||
AuthorEntity unmatched = author("Unmatched");
|
||||
book("A", library, libraryPath, List.of(matched));
|
||||
book("B", library, libraryPath, List.of(unmatched));
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse(null, List.of("has_asin:true"), null, null, 0, 20))).containsExactly(matched.getId());
|
||||
assertThat(ids(browse(null, List.of("has_asin:false"), null, null, 0, 20))).containsExactly(unmatched.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void hasDescriptionFacetIsApplied() {
|
||||
AuthorEntity documented = author("Documented");
|
||||
documented.setDescription("Has a bio.");
|
||||
AuthorEntity bare = author("Bare");
|
||||
book("A", library, libraryPath, List.of(documented));
|
||||
book("B", library, libraryPath, List.of(bare));
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse(null, List.of("has_description:true"), null, null, 0, 20)))
|
||||
.containsExactly(documented.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void bookCountRangeFacetIsApplied() {
|
||||
AuthorEntity one = author("One");
|
||||
AuthorEntity three = author("Three");
|
||||
book("A", library, libraryPath, List.of(one));
|
||||
for (int i = 0; i < 3; i++) {
|
||||
book("B" + i, library, libraryPath, List.of(three));
|
||||
}
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse(null, List.of("book_count:1"), null, null, 0, 20))).containsExactly(one.getId());
|
||||
assertThat(ids(browse(null, List.of("book_count:2-"), null, null, 0, 20))).containsExactly(three.getId());
|
||||
assertThat(ids(browse(null, List.of("book_count:-2"), null, null, 0, 20))).containsExactly(one.getId());
|
||||
assertThat(ids(browse(null, List.of("book_count:1-3"), null, null, 0, 20)))
|
||||
.containsExactlyInAnyOrder(one.getId(), three.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidBookCountRangeIsRejected() {
|
||||
assertThatThrownBy(() -> browse(null, List.of("book_count:abc"), null, null, 0, 20))
|
||||
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
assertThatThrownBy(() -> browse(null, List.of("book_count:5-2"), null, null, 0, 20))
|
||||
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
}
|
||||
|
||||
@Test
|
||||
void genreAndLanguageFacetsAreApplied() {
|
||||
AuthorEntity horror = author("Horror Writer");
|
||||
AuthorEntity romance = author("Romance Writer");
|
||||
book("H", library, libraryPath, List.of(horror), null, List.of("Horror"), "en");
|
||||
book("R", library, libraryPath, List.of(romance), null, List.of("Romance"), "fr");
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse(null, List.of("genre:Horror"), null, null, 0, 20))).containsExactly(horror.getId());
|
||||
assertThat(ids(browse(null, List.of("language:fr"), null, null, 0, 20))).containsExactly(romance.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void libraryFacetIsApplied() {
|
||||
LibraryEntity otherLibrary = LibraryEntity.builder().name("Other").icon("book").watch(false)
|
||||
.formatPriority(List.of(BookFileType.EPUB)).build();
|
||||
em.persist(otherLibrary);
|
||||
LibraryPathEntity otherPath = LibraryPathEntity.builder().library(otherLibrary).path("/o").build();
|
||||
em.persist(otherPath);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(adminUser());
|
||||
|
||||
AuthorEntity here = author("Here");
|
||||
AuthorEntity there = author("There");
|
||||
book("A", library, libraryPath, List.of(here));
|
||||
book("B", otherLibrary, otherPath, List.of(there));
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse(null, List.of("library:" + library.getId()), null, null, 0, 20)))
|
||||
.containsExactly(here.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readStatusFacetUsesBookVocabulary() {
|
||||
AuthorEntity finished = author("Finished");
|
||||
AuthorEntity reading = author("Reading");
|
||||
AuthorEntity unsetRow = author("Unset Row");
|
||||
AuthorEntity untouched = author("Untouched");
|
||||
|
||||
BookEntity f = book("F", library, libraryPath, List.of(finished));
|
||||
progress(f, ReadStatus.READ);
|
||||
|
||||
BookEntity r = book("R", library, libraryPath, List.of(reading));
|
||||
progress(r, ReadStatus.READING);
|
||||
|
||||
BookEntity u = book("U", library, libraryPath, List.of(unsetRow));
|
||||
progress(u, ReadStatus.UNSET);
|
||||
|
||||
book("N", library, libraryPath, List.of(untouched));
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse(null, List.of("read_status:READ"), null, null, 0, 20)))
|
||||
.containsExactly(finished.getId());
|
||||
assertThat(ids(browse(null, List.of("read_status:reading"), null, null, 0, 20)))
|
||||
.containsExactly(reading.getId());
|
||||
assertThat(ids(browse(null, List.of("read_status:UNSET"), null, null, 0, 20)))
|
||||
.containsExactlyInAnyOrder(unsetRow.getId(), untouched.getId());
|
||||
|
||||
assertThatThrownBy(() -> browse(null, List.of("read_status:some_read"), null, null, 0, 20))
|
||||
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
|
||||
.hasMessageContaining("Invalid read_status value");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonAdminSeesOnlyAuthorsWithVisibleBooks() {
|
||||
LibraryEntity otherLibrary = LibraryEntity.builder().name("Other").icon("book").watch(false)
|
||||
.formatPriority(List.of(BookFileType.EPUB)).build();
|
||||
em.persist(otherLibrary);
|
||||
LibraryPathEntity otherPath = LibraryPathEntity.builder().library(otherLibrary).path("/o").build();
|
||||
em.persist(otherPath);
|
||||
|
||||
AuthorEntity visible = author("Visible");
|
||||
AuthorEntity hidden = author("Hidden");
|
||||
AuthorEntity bookless = author("Bookless");
|
||||
book("In", library, libraryPath, List.of(visible));
|
||||
book("Out", otherLibrary, otherPath, List.of(hidden));
|
||||
em.flush();
|
||||
|
||||
assertThat(ids(browse(null, null, null, null, 0, 20))).containsExactly(visible.getId());
|
||||
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(adminUser());
|
||||
assertThat(ids(browse("name", null, null, null, 0, 20)))
|
||||
.containsExactly(bookless.getId(), hidden.getId(), visible.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonAdminWithNoLibrariesSeesNothing() {
|
||||
AuthorEntity a = author("Alice");
|
||||
book("A", library, libraryPath, List.of(a));
|
||||
em.flush();
|
||||
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(false);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(BookLoreUser.builder()
|
||||
.id(userEntity.getId())
|
||||
.assignedLibraries(List.of())
|
||||
.permissions(permissions)
|
||||
.build());
|
||||
|
||||
BrowsePage<AuthorSummary> result = browse(null, null, null, null, 0, 20);
|
||||
assertThat(result.content()).isEmpty();
|
||||
assertThat(result.page().totalElements()).isZero();
|
||||
assertThat(browseService.findAllIds(null, null, null, null)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void contentRestrictionsHideAuthorsAndTheirCounts() {
|
||||
em.persist(UserContentRestrictionEntity.builder()
|
||||
.user(userEntity)
|
||||
.restrictionType(ContentRestrictionType.TAG)
|
||||
.mode(ContentRestrictionMode.EXCLUDE)
|
||||
.value("adult")
|
||||
.build());
|
||||
|
||||
AuthorEntity clean = author("Clean");
|
||||
AuthorEntity mixed = author("Mixed");
|
||||
AuthorEntity restricted = author("Restricted");
|
||||
|
||||
book("C", library, libraryPath, List.of(clean));
|
||||
book("M1", library, libraryPath, List.of(mixed));
|
||||
BookEntity m2 = book("M2", library, libraryPath, List.of(mixed));
|
||||
m2.getMetadata().setTags(java.util.Set.of(tag("adult")));
|
||||
BookEntity r = book("R", library, libraryPath, List.of(restricted));
|
||||
r.getMetadata().setTags(java.util.Set.of(tag("adult")));
|
||||
em.flush();
|
||||
|
||||
BrowsePage<AuthorSummary> result = browse("name", null, null, null, 0, 20);
|
||||
assertThat(ids(result)).containsExactly(clean.getId(), mixed.getId());
|
||||
AuthorSummary mixedSummary = result.content().get(1);
|
||||
assertThat(mixedSummary.getBookCount()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cursorWalkIsConsistent() {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
AuthorEntity a = author(String.format("Author%02d", i));
|
||||
book("B" + i, library, libraryPath, List.of(a));
|
||||
}
|
||||
em.flush();
|
||||
|
||||
BrowsePage<AuthorSummary> page0 = browse("name", null, null, null, 0, 2);
|
||||
assertThat(page0.content()).hasSize(2);
|
||||
assertThat(page0.page().totalElements()).isEqualTo(5);
|
||||
|
||||
Link next = page0.links().stream().filter(l -> l.rel().contains("next")).findFirst().orElseThrow();
|
||||
String cursor = next.href().substring(next.href().indexOf("cursor=") + "cursor=".length());
|
||||
BrowsePage<AuthorSummary> page1 = browse("name", null, null, cursor, 0, 2);
|
||||
assertThat(page1.content()).hasSize(2);
|
||||
assertThat(ids(page1)).doesNotContainAnyElementsOf(ids(page0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cursorWithConflictingFacetsIsRejected() {
|
||||
AuthorEntity a = author("Alice");
|
||||
book("A", library, libraryPath, List.of(a));
|
||||
em.flush();
|
||||
String cursor = browse(null, null, null, null, 0, 20).page().cursor();
|
||||
assertThatThrownBy(() -> browse(null, List.of("has_asin:true"), null, cursor, 0, 20))
|
||||
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
|
||||
.hasMessageContaining("does not match");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownSortAndFacetAreRejected() {
|
||||
assertThatThrownBy(() -> browse("title", null, null, null, 0, 20))
|
||||
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
|
||||
.hasMessageContaining("Unknown sort key");
|
||||
assertThatThrownBy(() -> browse(null, List.of("shoe_size:12"), null, null, 0, 20))
|
||||
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
|
||||
.hasMessageContaining("Unknown facet");
|
||||
}
|
||||
|
||||
@Test
|
||||
void findAllIdsMatchesPageOrderingForSameFilters() {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
AuthorEntity a = author(String.format("Author%02d", i));
|
||||
book("B" + i, library, libraryPath, List.of(a));
|
||||
}
|
||||
em.flush();
|
||||
|
||||
List<Long> pageIds = ids(browse("name", null, null, null, 0, 20));
|
||||
assertThat(browseService.findAllIds("name", null, null, null)).isEqualTo(pageIds);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findAllIdsAppliesFacets() {
|
||||
AuthorEntity matched = author("Matched");
|
||||
matched.setAsin("B0FAKE");
|
||||
AuthorEntity unmatched = author("Unmatched");
|
||||
book("A", library, libraryPath, List.of(matched));
|
||||
book("B", library, libraryPath, List.of(unmatched));
|
||||
em.flush();
|
||||
|
||||
assertThat(browseService.findAllIds(null, List.of("has_asin:true"), null, null))
|
||||
.containsExactly(matched.getId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package org.booklore.service.browse;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import org.booklore.BookloreApplication;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup;
|
||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetLink;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.BookMetadataEntity;
|
||||
import org.booklore.model.entity.CategoryEntity;
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.service.task.TaskCronService;
|
||||
import org.booklore.util.FileService;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SpringBootTest(classes = BookloreApplication.class)
|
||||
@Transactional
|
||||
@TestPropertySource(properties = {
|
||||
"spring.flyway.enabled=false",
|
||||
"spring.jpa.hibernate.ddl-auto=create-drop",
|
||||
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
|
||||
"spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect",
|
||||
"spring.datasource.url=jdbc:h2:mem:authorfacetservicetest;DB_CLOSE_DELAY=-1;NON_KEYWORDS=VALUE",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver",
|
||||
"spring.datasource.username=sa",
|
||||
"spring.datasource.password=",
|
||||
"app.path-config=build/tmp/test-config",
|
||||
"app.bookdrop-folder=build/tmp/test-bookdrop",
|
||||
"spring.main.allow-bean-definition-overriding=true",
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false"
|
||||
})
|
||||
@Import(AuthorFacetServiceTest.TestConfig.class)
|
||||
class AuthorFacetServiceTest {
|
||||
|
||||
@Autowired
|
||||
private AuthorFacetService facetService;
|
||||
@Autowired
|
||||
private AuthorPhotoIndex photoIndex;
|
||||
@Autowired
|
||||
private FileService fileService;
|
||||
@MockitoBean
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager em;
|
||||
|
||||
private BookLoreUserEntity userEntity;
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
private final Map<String, CategoryEntity> categories = new HashMap<>();
|
||||
|
||||
@TestConfiguration
|
||||
public static class TestConfig {
|
||||
@Bean("flyway")
|
||||
@Primary
|
||||
public Flyway flyway() {
|
||||
return mock(Flyway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public TaskCronService taskCronService() {
|
||||
return mock(TaskCronService.class);
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void seed() throws IOException {
|
||||
facetService.clearCache();
|
||||
photoIndex.clearCache();
|
||||
deleteAuthorImages();
|
||||
|
||||
userEntity = BookLoreUserEntity.builder().username("reader").passwordHash("x").name("Reader").build();
|
||||
em.persist(userEntity);
|
||||
library = LibraryEntity.builder().name("Lib").icon("book").watch(false)
|
||||
.formatPriority(List.of(BookFileType.EPUB)).build();
|
||||
em.persist(library);
|
||||
libraryPath = LibraryPathEntity.builder().library(library).path("/p").build();
|
||||
em.persist(libraryPath);
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(nonAdminUser());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUpAuthorImages() throws IOException {
|
||||
deleteAuthorImages();
|
||||
}
|
||||
|
||||
private void deleteAuthorImages() throws IOException {
|
||||
Path imagesRoot = Paths.get(fileService.getAuthorImagesRoot());
|
||||
if (Files.isDirectory(imagesRoot)) {
|
||||
try (Stream<Path> paths = Files.walk(imagesRoot)) {
|
||||
paths.sorted(Comparator.reverseOrder()).forEach(p -> {
|
||||
try {
|
||||
Files.delete(p);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private BookLoreUser nonAdminUser() {
|
||||
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(false);
|
||||
return BookLoreUser.builder()
|
||||
.id(userEntity.getId())
|
||||
.assignedLibraries(List.of(Library.builder().id(library.getId()).build()))
|
||||
.permissions(permissions)
|
||||
.build();
|
||||
}
|
||||
|
||||
private AuthorEntity author(String name) {
|
||||
AuthorEntity author = AuthorEntity.builder().name(name).build();
|
||||
em.persist(author);
|
||||
return author;
|
||||
}
|
||||
|
||||
private void book(String title, List<AuthorEntity> authors, List<String> categoryNames, String language) {
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.library(library).libraryPath(libraryPath).addedOn(Instant.now()).deleted(false).build();
|
||||
em.persist(bookEntity);
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(bookEntity).title(title).language(language).build();
|
||||
metadata.setAuthors(new ArrayList<>(authors));
|
||||
if (categoryNames != null) {
|
||||
metadata.setCategories(categoryNames.stream().map(this::category).collect(Collectors.toSet()));
|
||||
}
|
||||
em.persist(metadata);
|
||||
bookEntity.setMetadata(metadata);
|
||||
}
|
||||
|
||||
private CategoryEntity category(String name) {
|
||||
return categories.computeIfAbsent(name, n -> {
|
||||
CategoryEntity e = CategoryEntity.builder().name(n).build();
|
||||
em.persist(e);
|
||||
return e;
|
||||
});
|
||||
}
|
||||
|
||||
private FacetGroup group(FacetGroupsResponse response, String key) {
|
||||
return response.facets().stream()
|
||||
.filter(g -> g.metadata().key().equals(key))
|
||||
.findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
private Long count(FacetGroup group, String value) {
|
||||
return group.links().stream()
|
||||
.filter(l -> l.value().equals(value))
|
||||
.findFirst()
|
||||
.map(l -> l.properties().numberOfItems())
|
||||
.orElse(0L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsSortGroupAndFacetGroupsWithCounts() {
|
||||
AuthorEntity matched = author("Matched");
|
||||
matched.setAsin("B0FAKE");
|
||||
matched.setDescription("Bio");
|
||||
AuthorEntity unmatched = author("Unmatched");
|
||||
book("A", List.of(matched), List.of("Horror"), "en");
|
||||
book("B", List.of(unmatched), List.of("Romance", "Horror"), "fr");
|
||||
em.flush();
|
||||
|
||||
FacetGroupsResponse response = facetService.getFacets(null, null, null);
|
||||
|
||||
FacetGroup sort = group(response, "sort");
|
||||
assertThat(sort.metadata().rel()).isEqualTo("sort");
|
||||
assertThat(sort.links().stream().map(FacetLink::value))
|
||||
.contains("name", "-name", "bookCount", "-bookCount", "amazonRating", "-personalRating");
|
||||
assertThat(sort.links().stream().map(FacetLink::value)).doesNotContain("id", "-id");
|
||||
|
||||
assertThat(count(group(response, "has_asin"), "true")).isEqualTo(1);
|
||||
assertThat(count(group(response, "has_asin"), "false")).isEqualTo(1);
|
||||
assertThat(count(group(response, "has_description"), "true")).isEqualTo(1);
|
||||
|
||||
FacetGroup genre = group(response, "genre");
|
||||
assertThat(count(genre, "Horror")).isEqualTo(2);
|
||||
assertThat(count(genre, "Romance")).isEqualTo(1);
|
||||
|
||||
FacetGroup language = group(response, "language");
|
||||
assertThat(count(language, "en")).isEqualTo(1);
|
||||
assertThat(count(language, "fr")).isEqualTo(1);
|
||||
|
||||
assertThat(response.facets().stream().map(g -> g.metadata().key()))
|
||||
.doesNotContain("book_count", "library", "read_status");
|
||||
}
|
||||
|
||||
@Test
|
||||
void hasPhotoFacetCountsFromDisk() throws IOException {
|
||||
AuthorEntity photographed = author("Photographed");
|
||||
AuthorEntity faceless = author("Faceless");
|
||||
book("A", List.of(photographed), null, null);
|
||||
book("B", List.of(faceless), null, null);
|
||||
em.flush();
|
||||
|
||||
Path thumbnail = Paths.get(fileService.getAuthorThumbnailFile(photographed.getId()));
|
||||
Files.createDirectories(thumbnail.getParent());
|
||||
Files.write(thumbnail, new byte[]{1});
|
||||
|
||||
FacetGroupsResponse response = facetService.getFacets(null, null, null);
|
||||
assertThat(count(group(response, "has_photo"), "true")).isEqualTo(1);
|
||||
assertThat(count(group(response, "has_photo"), "false")).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ownFacetSelectionsAreOmittedFromItsCounts() {
|
||||
AuthorEntity matched = author("Matched");
|
||||
matched.setAsin("B0FAKE");
|
||||
AuthorEntity unmatched = author("Unmatched");
|
||||
book("A", List.of(matched), List.of("Horror"), null);
|
||||
book("B", List.of(unmatched), List.of("Romance"), null);
|
||||
em.flush();
|
||||
|
||||
FacetGroupsResponse response = facetService.getFacets(List.of("has_asin:true"), null, null);
|
||||
|
||||
assertThat(count(group(response, "has_asin"), "false")).isEqualTo(1);
|
||||
assertThat(count(group(response, "genre"), "Horror")).isEqualTo(1);
|
||||
assertThat(group(response, "genre").links().stream().map(FacetLink::value))
|
||||
.doesNotContain("Romance");
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroCountValuesAreOmitted() {
|
||||
AuthorEntity unmatched = author("Unmatched");
|
||||
book("A", List.of(unmatched), null, null);
|
||||
em.flush();
|
||||
|
||||
FacetGroupsResponse response = facetService.getFacets(null, null, null);
|
||||
assertThat(group(response, "has_asin").links().stream().map(FacetLink::value))
|
||||
.containsExactly("false");
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeFacetLinksCarrySelfRel() {
|
||||
AuthorEntity matched = author("Matched");
|
||||
matched.setAsin("B0FAKE");
|
||||
AuthorEntity unmatched = author("Unmatched");
|
||||
book("A", List.of(matched), null, null);
|
||||
book("B", List.of(unmatched), null, null);
|
||||
em.flush();
|
||||
|
||||
FacetGroupsResponse response = facetService.getFacets(List.of("has_asin:true"), null, null);
|
||||
FacetLink active = group(response, "has_asin").links().stream()
|
||||
.filter(l -> l.value().equals("true"))
|
||||
.findFirst().orElseThrow();
|
||||
assertThat(active.rel()).contains("self", "facet");
|
||||
|
||||
Set<String> hrefs = group(response, "has_asin").links().stream()
|
||||
.map(FacetLink::href).collect(Collectors.toSet());
|
||||
assertThat(hrefs).allSatisfy(href -> assertThat(href).startsWith("/api/v1/authors/page"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user