refactor(books): paginate /api/v1/books/page with cursor, sort, facet, search (#1853)

Co-authored-by: James Ward <james@notjam.es>
This commit is contained in:
Zach
2026-07-09 15:58:30 -04:00
committed by GitHub
co-authored by James Ward
parent a1a6031359
commit ef51479d22
31 changed files with 1983 additions and 6 deletions
@@ -0,0 +1,19 @@
package org.booklore.browse;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public record BrowsePage<T>(List<T> content, PageMetadata page, List<Link> links) {
@JsonInclude(JsonInclude.Include.NON_NULL)
public record PageMetadata(int number, int size, long totalElements, int totalPages, String cursor) {
}
public static <T> BrowsePage<T> of(List<T> content, long offset, int limit, long totalElements, String cursor, List<Link> links) {
int number = limit > 0 ? (int) (offset / limit) : 0;
int totalPages = limit > 0 ? (int) Math.ceil((double) totalElements / limit) : 0;
return new BrowsePage<>(content, new PageMetadata(number, limit, totalElements, totalPages, cursor), links);
}
}
@@ -0,0 +1,49 @@
package org.booklore.browse;
import org.booklore.exception.ApiError;
import org.springframework.stereotype.Component;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
import java.util.Base64;
import java.util.Objects;
// Pagination cursor- unsigned, unpadded base64url of the JSON CursorState
// Parameter validation is enforced via the embedded params hash
@Component
public class CursorCodec {
private final ObjectMapper mapper = JsonMapper.shared();
public String encode(CursorState state) {
byte[] json = mapper.writeValueAsBytes(state);
return Base64.getUrlEncoder().withoutPadding().encodeToString(json);
}
public CursorState decode(String cursor) {
if (cursor == null || cursor.isBlank()) {
throw ApiError.INVALID_CURSOR.createException("Cursor is missing.");
}
CursorState state;
try {
byte[] json = Base64.getUrlDecoder().decode(cursor);
state = mapper.readValue(json, CursorState.class);
} catch (Exception e) {
throw ApiError.INVALID_CURSOR.createException("Cursor is malformed.");
}
if (state == null) {
throw ApiError.INVALID_CURSOR.createException("Cursor is malformed.");
}
if (state.offset() < 0 || state.offset() > Integer.MAX_VALUE || state.limit() <= 0) {
throw ApiError.INVALID_CURSOR.createException("Cursor offset/limit out of range.");
}
return state;
}
public void verifyParamsMatch(CursorState state, String currentParamsHash) {
if (!Objects.equals(state.paramsHash(), currentParamsHash)) {
throw ApiError.INVALID_CURSOR.createException(
"Cursor does not match the supplied facet/query parameters. Drop the cursor or re-send the original parameters.");
}
}
}
@@ -0,0 +1,20 @@
package org.booklore.browse;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
// Decoded contents of a pagination cursor (compact base64url JSON via CursorCodec)
// Offset-with-state: absolute offset/limit, sort string, and a fingerprint of the
// facet/query params, so a cursor with conflicting params is rejected
@JsonInclude(JsonInclude.Include.NON_NULL)
public record CursorState(
@JsonProperty("o") long offset,
@JsonProperty("l") int limit,
@JsonProperty("s") String sort,
@JsonProperty("f") String paramsHash
) {
public CursorState withOffset(long newOffset) {
return new CursorState(newOffset, limit, sort, paramsHash);
}
}
@@ -0,0 +1,18 @@
package org.booklore.browse;
public enum FacetLogic {
AND,
OR,
NOT;
public static FacetLogic from(String value) {
if (value == null || value.isBlank()) {
return AND;
}
return switch (value.trim().toLowerCase()) {
case "or" -> OR;
case "not" -> NOT;
default -> AND;
};
}
}
@@ -0,0 +1,15 @@
package org.booklore.browse;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Link(List<String> rel, String href, String type) {
public static final String JSON_TYPE = "application/json";
public static Link json(List<String> rel, String href) {
return new Link(rel, href, JSON_TYPE);
}
}
@@ -0,0 +1,53 @@
package org.booklore.browse;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
// Builds the paging links for a browse page (self/first/previous/next)
// Each carries the request's facet/query params + a cursor offset
@Component
public class LinksBuilder {
private final CursorCodec codec;
public LinksBuilder(CursorCodec codec) {
this.codec = codec;
}
public record Context(
String pagePath,
String preservedQuery,
long offset,
int limit,
long totalElements,
CursorState baseState
) {
}
public List<Link> build(Context ctx) {
List<Link> links = new ArrayList<>();
links.add(pageLink(List.of("self"), ctx, ctx.offset()));
links.add(pageLink(List.of("first"), ctx, 0));
if (ctx.offset() > 0) {
long previousOffset = Math.max(0, ctx.offset() - ctx.limit());
links.add(pageLink(List.of("previous"), ctx, previousOffset));
}
if (ctx.offset() + ctx.limit() < ctx.totalElements()) {
links.add(pageLink(List.of("next"), ctx, ctx.offset() + ctx.limit()));
}
return links;
}
private Link pageLink(List<String> rel, Context ctx, long offset) {
String cursor = codec.encode(ctx.baseState().withOffset(offset));
StringBuilder href = new StringBuilder(ctx.pagePath()).append('?');
if (ctx.preservedQuery() != null && !ctx.preservedQuery().isBlank()) {
href.append(ctx.preservedQuery()).append('&');
}
href.append("cursor=").append(cursor);
return Link.json(rel, href.toString());
}
}
@@ -0,0 +1,54 @@
package org.booklore.browse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
// Fingerprint of the request params (query, facet logic, facet selections)
// Used within the cursor + compared on follow-up so cursors w/ conflicting facets are rejected
public final class ParamsHash {
private static final int LENGTH = 12;
private ParamsHash() {
}
public static String compute(String query, Map<String, List<String>> facets, FacetLogic logic) {
StringBuilder canonical = new StringBuilder();
appendField(canonical, query == null ? "" : query.trim());
appendField(canonical, (logic == null ? FacetLogic.AND : logic).name());
if (facets != null) {
List<String> keys = new ArrayList<>(facets.keySet());
keys.sort(String::compareTo);
for (String key : keys) {
appendField(canonical, key);
List<String> values = new ArrayList<>(facets.get(key));
values.sort(String::compareTo);
appendField(canonical, Integer.toString(values.size()));
for (String value : values) {
appendField(canonical, value);
}
}
}
return hash(canonical.toString());
}
private static void appendField(StringBuilder sb, String value) {
String v = value == null ? "" : value;
sb.append(v.length()).append(':').append(v).append('|');
}
private static String hash(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] bytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(bytes).substring(0, LENGTH);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 unavailable", e);
}
}
}
@@ -0,0 +1,17 @@
package org.booklore.browse;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
// Criteria context handed to a SortOrderBuilder for one sort term
// Query is available for sorts that need a subquery
// userId is null for admin/system queries
public record SortContext<E>(
Root<E> root,
CriteriaQuery<?> query,
CriteriaBuilder cb,
boolean descending,
Long userId
) {
}
@@ -0,0 +1,12 @@
package org.booklore.browse;
import jakarta.persistence.criteria.Order;
import java.util.List;
// Builds the JPA orders for one sort key (a list so one key can expand to support multiple orders)
@FunctionalInterface
public interface SortOrderBuilder<E> {
List<Order> toOrders(SortContext<E> context);
}
@@ -0,0 +1,43 @@
package org.booklore.browse;
import org.booklore.exception.ApiError;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
// Parses the sort param- comma-separated keys, each optionally '-' prefixed for descending
// Always appends an ascending primary key so pagination is stable
public final class SortParser {
public static final String TIEBREAKER_KEY = "id";
private SortParser() {
}
public static List<SortTerm> parse(String sortString, Set<String> knownKeys) {
List<SortTerm> terms = new ArrayList<>();
if (sortString != null && !sortString.isBlank()) {
for (String raw : sortString.split(",", -1)) {
String token = raw.trim();
boolean descending = false;
if (token.startsWith("-")) {
descending = true;
token = token.substring(1).trim();
}
if (token.isEmpty()) {
throw ApiError.INVALID_SORT.createException("Empty sort key in: " + sortString);
}
// id is reserved for the implicit tiebreaker, so to callers it is not a sortable key.
if (token.equals(TIEBREAKER_KEY) || !knownKeys.contains(token)) {
throw ApiError.INVALID_SORT.createException("Unknown sort key: " + token);
}
terms.add(new SortTerm(token, descending));
}
}
terms.add(new SortTerm(TIEBREAKER_KEY, false));
return terms;
}
}
@@ -0,0 +1,47 @@
package org.booklore.browse;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Root;
import org.booklore.exception.ApiError;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
// Maps sort keys to JPA order builders for one browsable entity
// Registered keys are the allow-list SortParser validates against
// Every registry must register the "id" tiebreaker.
public class SortRegistry<E> {
private final Map<String, SortOrderBuilder<E>> builders = new LinkedHashMap<>();
public SortRegistry<E> register(String key, SortOrderBuilder<E> builder) {
builders.put(key, builder);
return this;
}
public boolean has(String key) {
return builders.containsKey(key);
}
public Set<String> keys() {
return Collections.unmodifiableSet(builders.keySet());
}
public List<Order> toOrders(List<SortTerm> terms, Root<E> root, CriteriaQuery<?> query, CriteriaBuilder cb, Long userId) {
List<Order> orders = new ArrayList<>();
for (SortTerm term : terms) {
SortOrderBuilder<E> builder = builders.get(term.key());
if (builder == null) {
throw ApiError.INVALID_SORT.createException("Unknown sort key: " + term.key());
}
orders.addAll(builder.toOrders(new SortContext<>(root, query, cb, term.descending(), userId)));
}
return orders;
}
}
@@ -0,0 +1,4 @@
package org.booklore.browse;
public record SortTerm(String key, boolean descending) {
}
@@ -1,5 +1,6 @@
package org.booklore.controller;
import org.booklore.browse.BrowsePage;
import org.booklore.config.security.annotation.CheckBookAccess;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.Book;
@@ -23,6 +24,7 @@ import org.booklore.service.book.BookService;
import org.booklore.service.book.BookUpdateService;
import org.booklore.service.book.DuplicateDetectionService;
import org.booklore.service.book.PhysicalBookService;
import org.booklore.service.browse.BookBrowseService;
import org.booklore.service.metadata.BookMetadataService;
import org.booklore.service.progress.ReadingProgressService;
import org.booklore.service.recommender.BookRecommendationService;
@@ -58,6 +60,7 @@ import java.io.IOException;
public class BookController {
private final BookService bookService;
private final BookBrowseService bookBrowseService;
private final BookUpdateService bookUpdateService;
private final BookRecommendationService bookRecommendationService;
private final BookFileAttachmentService bookFileAttachmentService;
@@ -77,12 +80,26 @@ public class BookController {
return ResponseEntity.ok(bookService.getBookDTOs(withDescription, stripForListView));
}
@Operation(summary = "Get books (paginated)", description = "Retrieve a paginated list of books. Supports sorting via 'sort' parameter (e.g. sort=metadata.title,asc).")
@Operation(summary = "Get books (paginated)", description = "Retrieve a page of books. Supports cursor pagination plus sort, facet, facet_logic, and query parameters; with none of these the legacy page/size behavior is preserved.")
@ApiResponse(responseCode = "200", description = "Page of books returned successfully")
@GetMapping("/page")
public ResponseEntity<Page<Book>> getBooksPaged(
@Parameter(hidden = true) Pageable pageable) {
return ResponseEntity.ok(bookService.getBookDTOsPaged(pageable));
public ResponseEntity<BrowsePage<Book>> getBooksPaged(
@Parameter(hidden = true) Pageable pageable,
@Parameter(description = "Comma-separated sort keys; prefix a key with '-' for descending (e.g. seriesName,-seriesNumber)")
@RequestParam(required = false) String sort,
@Parameter(description = "Facet selection in key:value form; repeatable (e.g. facet=genre:Horror&facet=read_status:READ)")
@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 across title, series, author, genre, tag, ISBN, and ASIN")
@RequestParam(required = false) String query,
@Parameter(description = "Opaque pagination cursor from a prior response's links")
@RequestParam(required = false) String cursor) {
boolean browseMode = sort != null || facet != null || facetLogic != null || query != null || cursor != null;
if (browseMode) {
return ResponseEntity.ok(bookBrowseService.browse(sort, facet, facetLogic, query, cursor, pageable));
}
return ResponseEntity.ok(bookBrowseService.wrapLegacy(bookService.getBookDTOsPaged(pageable), pageable));
}
@Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.")
@@ -74,7 +74,11 @@ public enum ApiError {
OIDC_LOGOUT_REPLAY(HttpStatus.BAD_REQUEST, "Logout token has already been processed"),
OIDC_LOGOUT_MISSING_JTI(HttpStatus.BAD_REQUEST, "Logout token missing required jti claim"),
OIDC_INVALID_STATE(HttpStatus.BAD_REQUEST, "Invalid or expired OIDC state parameter"),
JWT_INVALID(HttpStatus.UNAUTHORIZED, "Invalid JWT token: %s");
JWT_INVALID(HttpStatus.UNAUTHORIZED, "Invalid JWT token: %s"),
INVALID_SORT(HttpStatus.BAD_REQUEST, "%s"),
INVALID_CURSOR(HttpStatus.BAD_REQUEST, "%s"),
INVALID_FACET(HttpStatus.BAD_REQUEST, "%s");
private final HttpStatus status;
private final String message;
@@ -52,7 +52,11 @@ public class BookQueryService {
}
public Page<Book> getAllBooksByLibraryIdsPaged(Collection<Long> libraryIds, Long userId, Pageable pageable) {
Page<BookEntity> page = bookRepository.findAll(visibleBooks(libraryIds, userId), pageable);
return findBooksPaged(visibleBooks(libraryIds, userId), pageable, userId);
}
public Page<Book> findBooksPaged(Specification<BookEntity> spec, Pageable pageable, Long userId) {
Page<BookEntity> page = bookRepository.findAll(spec, pageable);
Map<Long, BookEntity> booksById = bookRepository
.findAllWithMetadataByIds(page.getContent().stream().map(BookEntity::getId).collect(Collectors.toSet()))
.stream()
@@ -0,0 +1,121 @@
package org.booklore.service.browse;
import lombok.RequiredArgsConstructor;
import org.booklore.browse.BrowsePage;
import org.booklore.browse.CursorCodec;
import org.booklore.browse.CursorState;
import org.booklore.browse.FacetLogic;
import org.booklore.browse.Link;
import org.booklore.browse.LinksBuilder;
import org.booklore.browse.ParamsHash;
import org.booklore.browse.SortParser;
import org.booklore.browse.SortTerm;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.Book;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.UserBookFileProgressEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.service.book.BookQueryService;
import org.booklore.service.progress.ReadingProgressService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
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.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class BookBrowseService {
private static final String PAGE_PATH = "/api/v1/books/page";
private static final int MAX_PAGE_SIZE = 100;
private final AuthenticationService authenticationService;
private final BookQueryService bookQueryService;
private final ReadingProgressService readingProgressService;
private final BookFilterSpecifications filterSpecifications;
private final BookSortRegistry sortRegistry;
private final CursorCodec cursorCodec;
private final LinksBuilder linksBuilder;
public BrowsePage<Book> browse(String sort, List<String> facet, String facetLogicParam, String query, String cursor, Pageable pageable) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
boolean isAdmin = user.getPermissions().isAdmin();
Map<String, List<String>> facets = BookFilterSpecifications.parseFacets(facet);
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
String paramsHash = ParamsHash.compute(query, facets, facetLogic);
long offset;
int limit;
String sortString;
if (cursor != null) {
CursorState state = cursorCodec.decode(cursor);
cursorCodec.verifyParamsMatch(state, paramsHash);
offset = state.offset();
limit = state.limit();
sortString = state.sort();
} else {
offset = pageable.getOffset();
limit = pageable.getPageSize();
sortString = sort;
}
if (limit <= 0) {
throw ApiError.INVALID_INPUT.createException("Page size must be positive.");
}
limit = Math.min(limit, MAX_PAGE_SIZE);
List<SortTerm> sortTerms = SortParser.parse(sortString, sortRegistry.registry().keys());
Specification<BookEntity> filter = filterSpecifications.base(query, facets, facetLogic, userId, isAdmin, BookFilterSpecifications.libraryIds(user), null);
Specification<BookEntity> spec = withSort(filter, sortTerms, userId);
Pageable pageRequest = PageRequest.of((int) (offset / limit), limit);
Page<Book> page = bookQueryService.findBooksPaged(spec, pageRequest, userId);
enrich(page.getContent(), userId);
CursorState baseState = new CursorState(offset, limit, sortString, paramsHash);
String currentCursor = cursorCodec.encode(baseState);
List<Link> links = linksBuilder.build(new LinksBuilder.Context(
PAGE_PATH, BrowseParams.preserved(facet, facetLogicParam, query), offset, limit, page.getTotalElements(), baseState));
return BrowsePage.of(page.getContent(), offset, limit, page.getTotalElements(), currentCursor, links);
}
public BrowsePage<Book> wrapLegacy(Page<Book> page, Pageable pageable) {
long offset = pageable.getOffset();
int limit = pageable.getPageSize();
String paramsHash = ParamsHash.compute(null, Map.of(), FacetLogic.AND);
CursorState baseState = new CursorState(offset, limit, null, paramsHash);
List<Link> links = linksBuilder.build(new LinksBuilder.Context(
PAGE_PATH, "", offset, limit, page.getTotalElements(), baseState));
return BrowsePage.of(page.getContent(), offset, limit, page.getTotalElements(), cursorCodec.encode(baseState), links);
}
private Specification<BookEntity> withSort(Specification<BookEntity> filter, List<SortTerm> sortTerms, Long userId) {
return (root, query, cb) -> {
if (query.getResultType() != Long.class && query.getResultType() != long.class) {
query.orderBy(sortRegistry.registry().toOrders(sortTerms, root, query, cb, userId));
}
return filter.toPredicate(root, query, cb);
};
}
private void enrich(List<Book> books, Long userId) {
Set<Long> bookIds = books.stream().map(Book::getId).collect(Collectors.toSet());
Map<Long, UserBookProgressEntity> progress = readingProgressService.fetchUserProgress(userId, bookIds);
Map<Long, UserBookFileProgressEntity> fileProgress = readingProgressService.fetchUserFileProgress(userId, bookIds);
for (Book book : books) {
readingProgressService.enrichBookWithProgress(book, progress.get(book.getId()), fileProgress.get(book.getId()));
}
}
}
@@ -0,0 +1,117 @@
package org.booklore.service.browse;
import org.booklore.app.specification.AppBookSpecification;
import org.booklore.browse.FacetLogic;
import org.booklore.exception.ApiError;
import org.booklore.model.entity.BookEntity;
import org.booklore.service.opds.MagicShelfBookService;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Component
public class BookFacetRegistry {
private static final String MAGIC_SHELF_PREFIX = "magic:";
private static final Set<String> NAMES = Set.of(
"author", "series", "genre", "tag", "mood", "language", "publisher", "library", "shelf",
"file_type", "read_status", "personal_rating", "amazon_rating", "goodreads_rating",
"hardcover_rating", "ranobedb_rating", "age_rating", "content_rating", "match_score",
"published_year", "file_size", "page_count", "shelf_status",
"comic_character", "comic_team", "comic_location", "comic_creator");
private final MagicShelfBookService magicShelfBookService;
public BookFacetRegistry(MagicShelfBookService magicShelfBookService) {
this.magicShelfBookService = magicShelfBookService;
}
public boolean has(String facetName) {
return NAMES.contains(facetName);
}
public Set<String> facetNames() {
return NAMES;
}
public Specification<BookEntity> toSpecification(String facetName, List<String> values, FacetLogic logic, Long userId) {
String mode = mode(logic);
return switch (facetName) {
case "author" -> AppBookSpecification.withAuthors(values, mode);
case "series" -> AppBookSpecification.inSeriesMulti(values, mode);
case "genre" -> AppBookSpecification.withCategories(values, mode);
case "tag" -> AppBookSpecification.withTags(values, mode);
case "mood" -> AppBookSpecification.withMoods(values, mode);
case "language" -> AppBookSpecification.withLanguages(values, mode);
case "publisher" -> AppBookSpecification.withPublishers(values, mode);
case "library" -> AppBookSpecification.inLibraries(values, mode);
case "shelf" -> shelves(values, logic, userId);
case "file_type" -> AppBookSpecification.withFileTypes(values, mode);
case "read_status" -> AppBookSpecification.withReadStatuses(values, userId, mode);
case "personal_rating" -> AppBookSpecification.withPersonalRatings(values, userId, mode);
case "amazon_rating" -> AppBookSpecification.withAmazonRatings(values, mode);
case "goodreads_rating" -> AppBookSpecification.withGoodreadsRatings(values, mode);
case "hardcover_rating" -> AppBookSpecification.withHardcoverRatings(values, mode);
case "ranobedb_rating" -> AppBookSpecification.withRanobedbRatings(values, mode);
case "age_rating" -> AppBookSpecification.withAgeRatings(values, mode);
case "content_rating" -> AppBookSpecification.withContentRatings(values, mode);
case "match_score" -> AppBookSpecification.withMatchScores(values, mode);
case "published_year" -> AppBookSpecification.withPublishedYears(values, mode);
case "file_size" -> AppBookSpecification.withFileSizes(values, mode);
case "page_count" -> AppBookSpecification.withPageCounts(values, mode);
case "shelf_status" -> AppBookSpecification.withShelfStatus(values, mode);
case "comic_character" -> AppBookSpecification.withComicCharacters(values, mode);
case "comic_team" -> AppBookSpecification.withComicTeams(values, mode);
case "comic_location" -> AppBookSpecification.withComicLocations(values, mode);
case "comic_creator" -> AppBookSpecification.withComicCreators(values, mode);
default -> throw ApiError.INVALID_FACET.createException("Unknown facet: " + facetName);
};
}
private Specification<BookEntity> shelves(List<String> values, FacetLogic logic, Long userId) {
List<String> regularIds = new ArrayList<>();
List<Specification<BookEntity>> specs = new ArrayList<>();
for (String value : values) {
if (value == null || value.isBlank()) {
continue;
}
if (value.startsWith(MAGIC_SHELF_PREFIX)) {
specs.add(magicShelfBookService.toSpecification(userId, parseMagicShelfId(value)));
} else {
regularIds.add(value);
}
}
if (!regularIds.isEmpty()) {
String inMode = logic == FacetLogic.AND ? "and" : "or";
specs.add(AppBookSpecification.inShelves(regularIds, inMode));
}
if (specs.isEmpty()) {
return (root, query, cb) -> cb.conjunction();
}
return switch (logic) {
case OR -> Specification.anyOf(specs);
case NOT -> Specification.not(Specification.anyOf(specs));
case AND -> Specification.allOf(specs);
};
}
private static long parseMagicShelfId(String value) {
try {
return Long.parseLong(value.substring(MAGIC_SHELF_PREFIX.length()));
} catch (NumberFormatException e) {
throw ApiError.INVALID_FACET.createException("Invalid magic shelf id: " + value);
}
}
private static String mode(FacetLogic logic) {
return switch (logic) {
case OR -> "or";
case NOT -> "not";
case AND -> "and";
};
}
}
@@ -0,0 +1,83 @@
package org.booklore.service.browse;
import lombok.RequiredArgsConstructor;
import org.booklore.app.specification.AppBookSpecification;
import org.booklore.browse.FacetLogic;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.BookEntity;
import org.booklore.repository.UserContentRestrictionRepository;
import org.booklore.security.policy.ContentRestrictionSpecification;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@Component
@RequiredArgsConstructor
public class BookFilterSpecifications {
private final BookFacetRegistry facetRegistry;
private final UserContentRestrictionRepository restrictionRepository;
public Specification<BookEntity> base(String query, Map<String, List<String>> facets, FacetLogic facetLogic,
Long userId, boolean isAdmin, Set<Long> libraryIds, String omitFacet) {
List<Specification<BookEntity>> specs = new ArrayList<>();
specs.add(AppBookSpecification.notDeleted());
if (!isAdmin) {
specs.add(inLibraries(libraryIds));
specs.add(ContentRestrictionSpecification.from(restrictionRepository.findByUserId(userId)));
}
if (query != null && !query.isBlank()) {
specs.add(BookSearchSpecification.matching(query));
}
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, userId));
}
return AppBookSpecification.combine(specs.toArray(Specification[]::new));
}
private static Specification<BookEntity> inLibraries(Set<Long> libraryIds) {
return (root, query, cb) -> libraryIds.isEmpty()
? cb.disjunction()
: root.get("library").get("id").in(libraryIds);
}
public static Set<Long> libraryIds(BookLoreUser user) {
if (user.getAssignedLibraries() == null) {
return Set.of();
}
return user.getAssignedLibraries().stream().map(Library::getId).collect(Collectors.toSet());
}
public static Map<String, List<String>> parseFacets(List<String> facet) {
Map<String, List<String>> facets = new LinkedHashMap<>();
if (facet == null) {
return facets;
}
for (String entry : facet) {
if (entry == null || entry.isBlank()) {
continue;
}
int colon = entry.indexOf(':');
if (colon <= 0 || colon == entry.length() - 1) {
throw ApiError.INVALID_FACET.createException("Facet must be in key:value form: " + entry);
}
facets.computeIfAbsent(entry.substring(0, colon), k -> new ArrayList<>()).add(entry.substring(colon + 1));
}
return facets;
}
}
@@ -0,0 +1,49 @@
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 org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookMetadataEntity;
import org.springframework.data.jpa.domain.Specification;
public final class BookSearchSpecification {
private BookSearchSpecification() {
}
public static Specification<BookEntity> matching(String query) {
return (root, criteriaQuery, cb) -> {
if (query == null || query.isBlank()) {
return cb.conjunction();
}
String pattern = "%" + query.toLowerCase().trim() + "%";
Join<BookEntity, BookMetadataEntity> metadata = root.join("metadata", JoinType.LEFT);
return cb.or(
cb.like(cb.lower(metadata.get("title")), pattern),
cb.like(cb.lower(metadata.get("seriesName")), pattern),
cb.like(cb.lower(metadata.get("isbn13")), pattern),
cb.like(cb.lower(metadata.get("isbn10")), pattern),
cb.like(cb.lower(metadata.get("asin")), pattern),
collectionMatches(root, criteriaQuery, cb, "authors", pattern),
collectionMatches(root, criteriaQuery, cb, "categories", pattern),
collectionMatches(root, criteriaQuery, cb, "tags", pattern)
);
};
}
private static Predicate collectionMatches(Root<BookEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
String collectionAttribute, String pattern) {
Subquery<Long> sub = query.subquery(Long.class);
Root<BookMetadataEntity> m = sub.from(BookMetadataEntity.class);
Join<Object, Object> joined = m.join(collectionAttribute, JoinType.INNER);
sub.select(cb.literal(1L)).where(
cb.equal(m.get("bookId"), root.get("id")),
cb.like(cb.lower(joined.get("name")), pattern));
return cb.exists(sub);
}
}
@@ -0,0 +1,112 @@
package org.booklore.service.browse;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Root;
import org.booklore.browse.SortContext;
import org.booklore.browse.SortOrderBuilder;
import org.booklore.browse.SortRegistry;
import org.booklore.model.entity.BookEntity;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class BookSortRegistry {
private static final List<String> PROGRESS_PERCENT_FIELDS = List.of(
"pdfProgressPercent", "epubProgressPercent", "cbxProgressPercent",
"koreaderProgressPercent", "koboProgressPercent");
private final SortRegistry<BookEntity> registry = build();
public SortRegistry<BookEntity> registry() {
return registry;
}
private static SortRegistry<BookEntity> build() {
SortRegistry<BookEntity> registry = new SortRegistry<>();
registry.register("id", rootField("id"));
registry.register("addedOn", rootField("addedOn"));
for (String field : List.of(
"title", "seriesName", "seriesNumber", "publisher", "publishedDate",
"amazonRating", "amazonReviewCount", "goodreadsRating", "goodreadsReviewCount",
"hardcoverRating", "hardcoverReviewCount", "ranobedbRating",
"narrator", "pageCount", "language")) {
registry.register(field, metadataField(field));
}
for (String field : List.of("personalRating", "lastReadTime", "readStatus", "dateFinished")) {
registry.register(field, progressField(field));
}
registry.register("readingProgress", readingProgress());
return registry;
}
private static SortOrderBuilder<BookEntity> rootField(String field) {
return ctx -> List.of(order(ctx, ctx.root().get(field)));
}
private static SortOrderBuilder<BookEntity> metadataField(String field) {
return ctx -> List.of(order(ctx, metadataJoin(ctx.root()).get(field)));
}
private static SortOrderBuilder<BookEntity> progressField(String field) {
return ctx -> List.of(order(ctx, progressJoin(ctx).get(field)));
}
private static SortOrderBuilder<BookEntity> readingProgress() {
return ctx -> {
CriteriaBuilder cb = ctx.cb();
Join<BookEntity, ?> progress = progressJoin(ctx);
Expression<Float> greatest = null;
for (String field : PROGRESS_PERCENT_FIELDS) {
Expression<Float> value = cb.coalesce(progress.get(field), cb.literal(0f));
greatest = greatest == null ? value : greatestOf(cb, greatest, value);
}
return List.of(order(ctx, greatest));
};
}
private static Expression<Float> greatestOf(CriteriaBuilder cb, Expression<Float> a, Expression<Float> b) {
return cb.<Float>selectCase()
.when(cb.greaterThanOrEqualTo(a, b), a)
.otherwise(b);
}
private static Order order(SortContext<BookEntity> ctx, Expression<?> expression) {
return ctx.descending() ? ctx.cb().desc(expression) : ctx.cb().asc(expression);
}
@SuppressWarnings("unchecked")
private static <Y> Join<BookEntity, Y> metadataJoin(Root<BookEntity> root) {
for (Join<BookEntity, ?> join : root.getJoins()) {
if (join.getAttribute().getName().equals("metadata") && join.getJoinType() == JoinType.LEFT) {
return (Join<BookEntity, Y>) join;
}
}
return root.join("metadata", JoinType.LEFT);
}
@SuppressWarnings("unchecked")
private static Join<BookEntity, ?> progressJoin(SortContext<BookEntity> ctx) {
Root<BookEntity> root = ctx.root();
for (Join<BookEntity, ?> join : root.getJoins()) {
if (join.getAttribute().getName().equals("userBookProgress")) {
return join;
}
}
Join<BookEntity, ?> join = root.join("userBookProgress", JoinType.LEFT);
CriteriaBuilder cb = ctx.cb();
Path<Object> joinUserId = ((Join<BookEntity, Object>) join).get("user").get("id");
join.on(ctx.userId() != null ? cb.equal(joinUserId, ctx.userId()) : cb.disjunction());
return join;
}
}
@@ -0,0 +1,34 @@
package org.booklore.service.browse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
final class BrowseParams {
private BrowseParams() {
}
static String preserved(List<String> facet, String facetLogic, String query) {
List<String> parts = new ArrayList<>();
if (facet != null) {
for (String entry : facet) {
if (entry != null && !entry.isBlank()) {
parts.add("facet=" + encode(entry));
}
}
}
if (facetLogic != null && !facetLogic.isBlank()) {
parts.add("facet_logic=" + encode(facetLogic));
}
if (query != null && !query.isBlank()) {
parts.add("query=" + encode(query));
}
return String.join("&", parts);
}
static String encode(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
}