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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user