refactor(books): add /api/v1/books/facets endpoint (#1898)

This commit is contained in:
Zach
2026-07-16 00:45:26 -04:00
committed by GitHub
parent 9e3c503d00
commit d2c0836f5d
11 changed files with 699 additions and 8 deletions
@@ -1,11 +1,12 @@
package org.booklore.browse;
import com.fasterxml.jackson.annotation.JsonInclude;
import tools.jackson.databind.annotation.JsonSerialize;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Link(List<String> rel, String href, String type) {
public record Link(@JsonSerialize(using = RelSerializer.class) List<String> rel, String href, String type) {
public static final String JSON_TYPE = "application/json";
@@ -5,8 +5,8 @@ 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
// Builds the links for a browse page (self/first/previous/next/facet)
// Paging links carry the request's facet/query params + a cursor offset
@Component
public class LinksBuilder {
@@ -18,6 +18,7 @@ public class LinksBuilder {
public record Context(
String pagePath,
String facetPath,
String preservedQuery,
long offset,
int limit,
@@ -28,6 +29,11 @@ public class LinksBuilder {
public List<Link> build(Context ctx) {
List<Link> links = new ArrayList<>();
String facetHref = ctx.facetPath();
if (ctx.preservedQuery() != null && !ctx.preservedQuery().isBlank()) {
facetHref = facetHref + "?" + ctx.preservedQuery();
}
links.add(Link.json(List.of("facet"), facetHref));
links.add(pageLink(List.of("self"), ctx, ctx.offset()));
links.add(pageLink(List.of("first"), ctx, 0));
@@ -0,0 +1,25 @@
package org.booklore.browse;
import tools.jackson.core.JsonGenerator;
import tools.jackson.databind.SerializationContext;
import tools.jackson.databind.ValueSerializer;
import java.util.List;
// Serializes rel following the RWPM Link Object convention used by the OPDS 2.0
// examples: a bare string for a single relation, an array for several.
public class RelSerializer extends ValueSerializer<List<String>> {
@Override
public void serialize(List<String> rels, JsonGenerator gen, SerializationContext context) {
if (rels.size() == 1) {
gen.writeString(rels.getFirst());
return;
}
gen.writeStartArray();
for (String rel : rels) {
gen.writeString(rel);
}
gen.writeEndArray();
}
}
@@ -25,6 +25,8 @@ 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.browse.BookFacetService;
import org.booklore.model.dto.browse.FacetGroupsResponse;
import org.booklore.service.metadata.BookMetadataService;
import org.booklore.service.progress.ReadingProgressService;
import org.booklore.service.recommender.BookRecommendationService;
@@ -61,6 +63,7 @@ public class BookController {
private final BookService bookService;
private final BookBrowseService bookBrowseService;
private final BookFacetService bookFacetService;
private final BookUpdateService bookUpdateService;
private final BookRecommendationService bookRecommendationService;
private final BookFileAttachmentService bookFileAttachmentService;
@@ -102,6 +105,19 @@ public class BookController {
return ResponseEntity.ok(bookBrowseService.wrapLegacy(bookService.getBookDTOsPaged(pageable), pageable));
}
@Operation(summary = "Get book facets", description = "Available facet values and 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.")
@ApiResponse(responseCode = "200", description = "Facet groups returned successfully")
@GetMapping("/facets")
public ResponseEntity<FacetGroupsResponse> getBookFacets(
@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(bookFacetService.getFacets(facet, facetLogic, query));
}
@Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Book details returned successfully"),
@@ -0,0 +1,28 @@
package org.booklore.model.dto.browse;
import com.fasterxml.jackson.annotation.JsonInclude;
import tools.jackson.databind.annotation.JsonSerialize;
import org.booklore.browse.Link;
import org.booklore.browse.RelSerializer;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public record FacetGroupsResponse(List<Link> links, List<FacetGroup> facets) {
@JsonInclude(JsonInclude.Include.NON_NULL)
public record FacetGroup(Metadata metadata, List<FacetLink> links) {
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Metadata(String rel, String key, String title) {
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public record FacetLink(@JsonSerialize(using = RelSerializer.class) List<String> rel, String href, String type, String title, String value, Properties properties) {
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Properties(Long numberOfItems) {
}
}
@@ -37,6 +37,7 @@ import java.util.stream.Collectors;
public class BookBrowseService {
private static final String PAGE_PATH = "/api/v1/books/page";
private static final String FACET_PATH = "/api/v1/books/facets";
private static final int MAX_PAGE_SIZE = 100;
private final AuthenticationService authenticationService;
@@ -86,7 +87,7 @@ public class BookBrowseService {
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));
PAGE_PATH, FACET_PATH, BrowseParams.preserved(facet, facetLogicParam, query), offset, limit, page.getTotalElements(), baseState));
return BrowsePage.of(page.getContent(), offset, limit, page.getTotalElements(), currentCursor, links);
}
@@ -97,7 +98,7 @@ public class BookBrowseService {
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));
PAGE_PATH, FACET_PATH, "", offset, limit, page.getTotalElements(), baseState));
return BrowsePage.of(page.getContent(), offset, limit, page.getTotalElements(), cursorCodec.encode(baseState), links);
}
@@ -0,0 +1,165 @@
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.PersistenceContext;
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.Link;
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.dto.browse.FacetGroupsResponse.FacetLink;
import org.booklore.model.dto.browse.FacetGroupsResponse.Metadata;
import org.booklore.model.dto.browse.FacetGroupsResponse.Properties;
import org.booklore.model.entity.BookEntity;
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.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class BookFacetService {
private static final String PAGE_PATH = "/api/v1/books/page";
private static final String FACET_PATH = "/api/v1/books/facets";
private static final int MAX_VALUES = 100;
private static final List<FacetDef> FACETS = List.of(
new FacetDef("author", "Authors", root -> metadata(root).join("authors", JoinType.LEFT).get("name")),
new FacetDef("genre", "Genre", root -> metadata(root).join("categories", JoinType.LEFT).get("name")),
new FacetDef("tag", "Tags", root -> metadata(root).join("tags", JoinType.LEFT).get("name")),
new FacetDef("mood", "Moods", root -> metadata(root).join("moods", JoinType.LEFT).get("name")),
new FacetDef("series", "Series", root -> metadata(root).get("seriesName")),
new FacetDef("publisher", "Publisher", root -> metadata(root).get("publisher")),
new FacetDef("language", "Language", root -> metadata(root).get("language")),
new FacetDef("narrator", "Narrator", root -> metadata(root).get("narrator")),
new FacetDef("file_type", "File Type", root -> root.join("bookFiles", JoinType.LEFT).get("bookType")));
private final AuthenticationService authenticationService;
private final BookFilterSpecifications filterSpecifications;
private final BookSortRegistry sortRegistry;
@PersistenceContext
private 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();
Long userId = user.getId();
boolean isAdmin = user.getPermissions().isAdmin();
Set<Long> libraryIds = BookFilterSpecifications.libraryIds(user);
Map<String, List<String>> facets = BookFilterSpecifications.parseFacets(facet);
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
String cacheKey = userId + ":" + ParamsHash.compute(query, facets, facetLogic);
return cache.get(cacheKey, key -> {
String preserved = BrowseParams.preserved(facet, facetLogicParam, query);
List<FacetGroup> groups = new ArrayList<>();
groups.add(sortGroup(preserved));
for (FacetDef def : FACETS) {
Specification<BookEntity> base = filterSpecifications.base(query, facets, facetLogic, userId, isAdmin, libraryIds, def.key());
groups.add(toGroup(def, count(def, base), facet, preserved));
}
List<Link> links = List.of(Link.json(List.of("self"), href(FACET_PATH, preserved)));
return new FacetGroupsResponse(links, groups);
});
}
// Package-private: lets tests reset the shared singleton cache between runs.
void clearCache() {
cache.invalidateAll();
}
private List<FacetCount> count(FacetDef def, Specification<BookEntity> base) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<BookEntity> root = cq.from(BookEntity.class);
Expression<?> value = def.value().apply(root);
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));
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 FacetCount(String.valueOf(tuple.get("value")), ((Number) tuple.get("count")).longValue()))
.toList();
}
private FacetGroup toGroup(FacetDef def, List<FacetCount> counts, List<String> facet, String preserved) {
List<FacetLink> links = counts.stream()
.map(c -> {
boolean active = BrowseParams.hasFacet(facet, def.key(), c.value());
List<String> rel = active ? List.of("self", "facet") : List.of("facet");
String href = active
? href(PAGE_PATH, preserved)
: pageLink(preserved, "facet=" + BrowseParams.encode(def.key() + ":" + c.value()));
return new FacetLink(rel, href, Link.JSON_TYPE, c.value(), c.value(), new Properties(c.count()));
})
.toList();
return new FacetGroup(new Metadata("facet", def.key(), def.title()), links);
}
private FacetGroup sortGroup(String preserved) {
List<FacetLink> links = new ArrayList<>();
for (String key : sortRegistry.registry().keys()) {
if (key.equals("id")) {
continue;
}
links.add(new FacetLink(List.of("sort"), pageLink(preserved, "sort=" + BrowseParams.encode(key)), Link.JSON_TYPE, key + " ascending", key, null));
links.add(new FacetLink(List.of("sort"), pageLink(preserved, "sort=-" + BrowseParams.encode(key)), Link.JSON_TYPE, key + " descending", "-" + key, null));
}
return new FacetGroup(new Metadata("sort", "sort", "Sort"), links);
}
private static String pageLink(String preserved, String param) {
return preserved.isBlank() ? PAGE_PATH + "?" + param : PAGE_PATH + "?" + preserved + "&" + param;
}
private static String href(String path, String preserved) {
return preserved.isBlank() ? path : path + "?" + preserved;
}
private static Join<?, ?> metadata(Root<BookEntity> root) {
return root.join("metadata", JoinType.LEFT);
}
private record FacetDef(String key, String title, Function<Root<BookEntity>, Expression<?>> value) {
}
private record FacetCount(String value, long count) {
}
}
@@ -28,6 +28,24 @@ final class BrowseParams {
return String.join("&", parts);
}
static boolean hasFacet(List<String> facet, String key, String value) {
if (facet == null) {
return false;
}
return facet.stream().anyMatch(entry -> matchesFacet(entry, key, value));
}
private static boolean matchesFacet(String entry, String key, String value) {
if (entry == null) {
return false;
}
int colon = entry.indexOf(':');
if (colon <= 0 || colon == entry.length() - 1) {
return false;
}
return entry.substring(0, colon).equals(key) && entry.substring(colon + 1).equalsIgnoreCase(value);
}
static String encode(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}