refactor(browse): extract shared pagination, scoping, and facet responses (#2351)
Co-authored-by: James Ward <james@notjam.es>
This commit is contained in:
@@ -0,0 +1,63 @@
|
|||||||
|
package org.booklore.browse;
|
||||||
|
|
||||||
|
import org.booklore.exception.ApiError;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class BrowsePager {
|
||||||
|
|
||||||
|
public static final int MAX_PAGE_SIZE = 100;
|
||||||
|
private static final int MAX_RANDOM_SORT_SEED = 999;
|
||||||
|
|
||||||
|
private final CursorCodec codec;
|
||||||
|
private final LinksBuilder linksBuilder;
|
||||||
|
|
||||||
|
public BrowsePager(CursorCodec codec, LinksBuilder linksBuilder) {
|
||||||
|
this.codec = codec;
|
||||||
|
this.linksBuilder = linksBuilder;
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Window(long offset, int limit, String sort, String paramsHash, Integer randomSeed) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int newRandomSeed() {
|
||||||
|
return (int) (Math.random() * MAX_RANDOM_SORT_SEED);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Window resolve(String sort, String cursor, Pageable pageable, String paramsHash) {
|
||||||
|
long offset;
|
||||||
|
int limit;
|
||||||
|
String sortString;
|
||||||
|
Integer randomSeed;
|
||||||
|
if (cursor != null) {
|
||||||
|
CursorState state = codec.decode(cursor);
|
||||||
|
codec.verifyParamsMatch(state, paramsHash);
|
||||||
|
offset = state.offset();
|
||||||
|
limit = state.limit();
|
||||||
|
sortString = state.sort();
|
||||||
|
randomSeed = state.randomSeed();
|
||||||
|
} else {
|
||||||
|
offset = pageable.getOffset();
|
||||||
|
limit = pageable.getPageSize();
|
||||||
|
sortString = sort;
|
||||||
|
randomSeed = newRandomSeed();
|
||||||
|
}
|
||||||
|
if (limit <= 0) {
|
||||||
|
throw ApiError.INVALID_INPUT.createException("Page size must be positive.");
|
||||||
|
} else if (limit > MAX_PAGE_SIZE) {
|
||||||
|
throw ApiError.INVALID_INPUT.createException("Page size must be less than or equal to " + MAX_PAGE_SIZE + ".");
|
||||||
|
}
|
||||||
|
return new Window(offset, limit, sortString, paramsHash, randomSeed);
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> BrowsePage<T> assemble(String pagePath, String facetPath, String preserved,
|
||||||
|
Window window, long total, List<T> content) {
|
||||||
|
CursorState baseState = new CursorState(window.offset(), window.limit(), window.sort(), window.paramsHash(), window.randomSeed());
|
||||||
|
List<Link> links = linksBuilder.build(new LinksBuilder.Context(
|
||||||
|
pagePath, facetPath, preserved, window.offset(), window.limit(), total, baseState));
|
||||||
|
return BrowsePage.of(content, window.offset(), window.limit(), total, codec.encode(baseState), links);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -30,7 +30,6 @@ public class BookLoreUser {
|
|||||||
private List<Library> assignedLibraries;
|
private List<Library> assignedLibraries;
|
||||||
private UserPermissions permissions;
|
private UserPermissions permissions;
|
||||||
private UserSettings userSettings;
|
private UserSettings userSettings;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public static class UserPermissions {
|
public static class UserPermissions {
|
||||||
private boolean isAdmin;
|
private boolean isAdmin;
|
||||||
|
|||||||
@@ -1,23 +1,18 @@
|
|||||||
package org.booklore.service.browse;
|
package org.booklore.service.browse;
|
||||||
|
|
||||||
import jakarta.persistence.EntityManager;
|
import jakarta.persistence.EntityManager;
|
||||||
import jakarta.persistence.PersistenceContext;
|
|
||||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||||
import jakarta.persistence.criteria.CriteriaQuery;
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
import jakarta.persistence.criteria.Predicate;
|
import jakarta.persistence.criteria.Predicate;
|
||||||
import jakarta.persistence.criteria.Root;
|
import jakarta.persistence.criteria.Root;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.booklore.browse.BrowsePage;
|
import org.booklore.browse.BrowsePage;
|
||||||
import org.booklore.browse.CursorCodec;
|
import org.booklore.browse.BrowsePager;
|
||||||
import org.booklore.browse.CursorState;
|
|
||||||
import org.booklore.browse.FacetLogic;
|
import org.booklore.browse.FacetLogic;
|
||||||
import org.booklore.browse.Link;
|
|
||||||
import org.booklore.browse.LinksBuilder;
|
|
||||||
import org.booklore.browse.ParamsHash;
|
import org.booklore.browse.ParamsHash;
|
||||||
import org.booklore.browse.SortParser;
|
import org.booklore.browse.SortParser;
|
||||||
import org.booklore.browse.SortTerm;
|
import org.booklore.browse.SortTerm;
|
||||||
import org.booklore.config.security.service.AuthenticationService;
|
import org.booklore.config.security.service.AuthenticationService;
|
||||||
import org.booklore.exception.ApiError;
|
|
||||||
import org.booklore.model.dto.Book;
|
import org.booklore.model.dto.Book;
|
||||||
import org.booklore.model.dto.BookLoreUser;
|
import org.booklore.model.dto.BookLoreUser;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
@@ -44,76 +39,48 @@ public class BookBrowseService {
|
|||||||
|
|
||||||
private static final String PAGE_PATH = "/api/v1/books/page";
|
private static final String PAGE_PATH = "/api/v1/books/page";
|
||||||
private static final String FACET_PATH = "/api/v1/books/facets";
|
private static final String FACET_PATH = "/api/v1/books/facets";
|
||||||
private static final int MAX_PAGE_SIZE = 100;
|
|
||||||
private static final int MAX_RANDOM_SORT_SEED = 999;
|
|
||||||
|
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
private final BookQueryService bookQueryService;
|
private final BookQueryService bookQueryService;
|
||||||
private final ReadingProgressService readingProgressService;
|
private final ReadingProgressService readingProgressService;
|
||||||
private final BookFilterSpecifications filterSpecifications;
|
private final BookFilterSpecifications filterSpecifications;
|
||||||
private final BookSortRegistry sortRegistry;
|
private final BookSortRegistry sortRegistry;
|
||||||
private final CursorCodec cursorCodec;
|
private final BrowseScopeFactory scopeFactory;
|
||||||
private final LinksBuilder linksBuilder;
|
private final BrowsePager pager;
|
||||||
|
private final EntityManager entityManager;
|
||||||
@PersistenceContext
|
|
||||||
private EntityManager entityManager;
|
|
||||||
|
|
||||||
public BrowsePage<Book> browse(String sort, List<String> facet, String facetLogicParam, String query, String cursor, Pageable pageable) {
|
public BrowsePage<Book> browse(String sort, List<String> facet, String facetLogicParam, String query, String cursor, Pageable pageable) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = user.getId();
|
BrowseScope scope = scopeFactory.from(user);
|
||||||
boolean isAdmin = user.getPermissions().isAdmin();
|
Long userId = scope.userId();
|
||||||
|
|
||||||
Map<String, List<String>> facets = BookFilterSpecifications.parseFacets(facet);
|
Map<String, List<String>> facets = BrowseParams.parseFacets(facet);
|
||||||
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
||||||
String paramsHash = ParamsHash.compute(query, facets, facetLogic);
|
String paramsHash = ParamsHash.compute(query, facets, facetLogic);
|
||||||
|
|
||||||
long offset;
|
BrowsePager.Window window = pager.resolve(sort, cursor, pageable, paramsHash);
|
||||||
int limit;
|
|
||||||
String sortString;
|
|
||||||
Integer randomSeed;
|
|
||||||
if (cursor != null) {
|
|
||||||
CursorState state = cursorCodec.decode(cursor);
|
|
||||||
cursorCodec.verifyParamsMatch(state, paramsHash);
|
|
||||||
offset = state.offset();
|
|
||||||
limit = state.limit();
|
|
||||||
sortString = state.sort();
|
|
||||||
randomSeed = state.randomSeed();
|
|
||||||
} else {
|
|
||||||
offset = pageable.getOffset();
|
|
||||||
limit = pageable.getPageSize();
|
|
||||||
sortString = sort;
|
|
||||||
randomSeed = (int) (Math.random() * MAX_RANDOM_SORT_SEED);
|
|
||||||
}
|
|
||||||
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());
|
List<SortTerm> sortTerms = SortParser.parse(window.sort(), sortRegistry.registry().keys());
|
||||||
Specification<BookEntity> filter = filterSpecifications.base(query, facets, facetLogic, userId, isAdmin, BookFilterSpecifications.libraryIds(user), null);
|
Specification<BookEntity> filter = filterSpecifications.base(query, facets, facetLogic, scope, null);
|
||||||
Specification<BookEntity> spec = withSort(filter, sortTerms, userId, randomSeed);
|
Specification<BookEntity> spec = withSort(filter, sortTerms, userId, window.randomSeed());
|
||||||
|
|
||||||
Pageable pageRequest = PageRequest.of((int) (offset / limit), limit);
|
Pageable pageRequest = PageRequest.of((int) (window.offset() / window.limit()), window.limit());
|
||||||
Page<Book> page = bookQueryService.findBooksPaged(spec, pageRequest, userId);
|
Page<Book> page = bookQueryService.findBooksPaged(spec, pageRequest, userId);
|
||||||
enrich(page.getContent(), userId);
|
enrich(page.getContent(), userId);
|
||||||
|
|
||||||
CursorState baseState = new CursorState(offset, limit, sortString, paramsHash, randomSeed);
|
return pager.assemble(PAGE_PATH, FACET_PATH, BrowseParams.preserved(facet, facetLogicParam, query),
|
||||||
String currentCursor = cursorCodec.encode(baseState);
|
window, page.getTotalElements(), page.getContent());
|
||||||
List<Link> links = linksBuilder.build(new LinksBuilder.Context(
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Long> findAllIds(String sort, List<String> facet, String facetLogicParam, String query) {
|
public List<Long> findAllIds(String sort, List<String> facet, String facetLogicParam, String query) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = user.getId();
|
BrowseScope scope = scopeFactory.from(user);
|
||||||
boolean isAdmin = user.getPermissions().isAdmin();
|
Long userId = scope.userId();
|
||||||
|
|
||||||
Map<String, List<String>> facets = BookFilterSpecifications.parseFacets(facet);
|
Map<String, List<String>> facets = BrowseParams.parseFacets(facet);
|
||||||
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
||||||
List<SortTerm> sortTerms = SortParser.parse(sort, sortRegistry.registry().keys());
|
List<SortTerm> sortTerms = SortParser.parse(sort, sortRegistry.registry().keys());
|
||||||
Specification<BookEntity> filter = filterSpecifications.base(query, facets, facetLogic, userId, isAdmin, BookFilterSpecifications.libraryIds(user), null);
|
Specification<BookEntity> filter = filterSpecifications.base(query, facets, facetLogic, scope, null);
|
||||||
|
|
||||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||||
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
|
||||||
@@ -125,7 +92,7 @@ public class BookBrowseService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The `findAllIds` doesn't pass a cursor so it's a random seed every time.
|
// The `findAllIds` doesn't pass a cursor so it's a random seed every time.
|
||||||
int randomSeed = (int) (Math.random() * MAX_RANDOM_SORT_SEED);
|
int randomSeed = BrowsePager.newRandomSeed();
|
||||||
|
|
||||||
cq.orderBy(sortRegistry.registry().toOrders(sortTerms, root, cq, cb, userId, randomSeed));
|
cq.orderBy(sortRegistry.registry().toOrders(sortTerms, root, cq, cb, userId, randomSeed));
|
||||||
|
|
||||||
@@ -133,18 +100,12 @@ public class BookBrowseService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public BrowsePage<Book> wrapLegacy(Page<Book> page, Pageable pageable) {
|
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);
|
String paramsHash = ParamsHash.compute(null, Map.of(), FacetLogic.AND);
|
||||||
|
|
||||||
// Pass a null random seed for the legacy case - we don't actually store a seed value and
|
// Pass a null random seed for the legacy case - we don't actually store a seed value and
|
||||||
// this is good enough for most use cases.
|
// this is good enough for most use cases.
|
||||||
CursorState baseState = new CursorState(offset, limit, null, paramsHash, null);
|
BrowsePager.Window window = new BrowsePager.Window(pageable.getOffset(), pageable.getPageSize(), null, paramsHash, null);
|
||||||
|
return pager.assemble(PAGE_PATH, FACET_PATH, "", window, page.getTotalElements(), page.getContent());
|
||||||
List<Link> links = linksBuilder.build(new LinksBuilder.Context(
|
|
||||||
PAGE_PATH, FACET_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, Integer randomSeed) {
|
private Specification<BookEntity> withSort(Specification<BookEntity> filter, List<SortTerm> sortTerms, Long userId, Integer randomSeed) {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package org.booklore.service.browse;
|
|||||||
import com.github.benmanes.caffeine.cache.Cache;
|
import com.github.benmanes.caffeine.cache.Cache;
|
||||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||||
import jakarta.persistence.EntityManager;
|
import jakarta.persistence.EntityManager;
|
||||||
import jakarta.persistence.PersistenceContext;
|
|
||||||
import jakarta.persistence.Tuple;
|
import jakarta.persistence.Tuple;
|
||||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||||
import jakarta.persistence.criteria.CriteriaQuery;
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
@@ -14,15 +13,11 @@ import jakarta.persistence.criteria.Predicate;
|
|||||||
import jakarta.persistence.criteria.Root;
|
import jakarta.persistence.criteria.Root;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.booklore.browse.FacetLogic;
|
import org.booklore.browse.FacetLogic;
|
||||||
import org.booklore.browse.Link;
|
|
||||||
import org.booklore.browse.ParamsHash;
|
import org.booklore.browse.ParamsHash;
|
||||||
import org.booklore.config.security.service.AuthenticationService;
|
import org.booklore.config.security.service.AuthenticationService;
|
||||||
import org.booklore.model.dto.BookLoreUser;
|
import org.booklore.model.dto.BookLoreUser;
|
||||||
import org.booklore.model.dto.browse.FacetGroupsResponse;
|
import org.booklore.model.dto.browse.FacetGroupsResponse;
|
||||||
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup;
|
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.booklore.model.entity.BookEntity;
|
||||||
import org.booklore.model.entity.BookFileEntity;
|
import org.booklore.model.entity.BookFileEntity;
|
||||||
import org.booklore.model.entity.UserBookProgressEntity;
|
import org.booklore.model.entity.UserBookProgressEntity;
|
||||||
@@ -36,7 +31,6 @@ import java.util.ArrayList;
|
|||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@@ -54,65 +48,65 @@ public class BookFacetService {
|
|||||||
.otherwise(cb.nullLiteral(String.class)));
|
.otherwise(cb.nullLiteral(String.class)));
|
||||||
|
|
||||||
private static final List<FacetDef> FACETS = List.of(
|
private static final List<FacetDef> FACETS = List.of(
|
||||||
new FacetDef("author", "Authors", (cb, root, userId) -> metadata(root).join("authors", JoinType.LEFT).get("name")),
|
new FacetDef("author", "Authors", (cb, root, _) -> metadata(root).join("authors", JoinType.LEFT).get("name")),
|
||||||
new FacetDef("genre", "Genre", (cb, root, userId) -> metadata(root).join("categories", JoinType.LEFT).get("name")),
|
new FacetDef("genre", "Genre", (cb, root, _) -> metadata(root).join("categories", JoinType.LEFT).get("name")),
|
||||||
new FacetDef("tag", "Tags", (cb, root, userId) -> metadata(root).join("tags", JoinType.LEFT).get("name")),
|
new FacetDef("tag", "Tags", (cb, root, _) -> metadata(root).join("tags", JoinType.LEFT).get("name")),
|
||||||
new FacetDef("mood", "Moods", (cb, root, userId) -> metadata(root).join("moods", JoinType.LEFT).get("name")),
|
new FacetDef("mood", "Moods", (cb, root, _) -> metadata(root).join("moods", JoinType.LEFT).get("name")),
|
||||||
new FacetDef("series", "Series", (cb, root, userId) -> metadata(root).get("seriesName")),
|
new FacetDef("series", "Series", (cb, root, _) -> metadata(root).get("seriesName")),
|
||||||
new FacetDef("publisher", "Publisher", (cb, root, userId) -> metadata(root).get("publisher")),
|
new FacetDef("publisher", "Publisher", (cb, root, _) -> metadata(root).get("publisher")),
|
||||||
new FacetDef("language", "Language", (cb, root, userId) -> metadata(root).get("language")),
|
new FacetDef("language", "Language", (cb, root, _) -> metadata(root).get("language")),
|
||||||
new FacetDef("narrator", "Narrator", (cb, root, userId) -> metadata(root).get("narrator")),
|
new FacetDef("narrator", "Narrator", (cb, root, _) -> metadata(root).get("narrator")),
|
||||||
new FacetDef("file_type", "File Type", (cb, root, userId) -> {
|
new FacetDef("file_type", "File Type", (cb, root, _) -> {
|
||||||
Join<BookEntity, BookFileEntity> files = root.join("bookFiles", JoinType.LEFT);
|
Join<BookEntity, BookFileEntity> files = root.join("bookFiles", JoinType.LEFT);
|
||||||
files.on(cb.isTrue(files.get("isBookFormat")));
|
files.on(cb.isTrue(files.get("isBookFormat")));
|
||||||
return files.get("bookType");
|
return files.get("bookType");
|
||||||
}),
|
}),
|
||||||
new FacetDef("content_rating", "Content Rating", (cb, root, userId) -> metadata(root).get("contentRating")),
|
new FacetDef("content_rating", "Content Rating", (cb, root, _) -> metadata(root).get("contentRating")),
|
||||||
new FacetDef("amazon_rating", "Amazon Rating", (cb, root, userId) -> metadata(root).get("amazonRating")),
|
new FacetDef("amazon_rating", "Amazon Rating", (cb, root, _) -> metadata(root).get("amazonRating")),
|
||||||
new FacetDef("goodreads_rating", "Goodreads Rating", (cb, root, userId) -> metadata(root).get("goodreadsRating")),
|
new FacetDef("goodreads_rating", "Goodreads Rating", (cb, root, _) -> metadata(root).get("goodreadsRating")),
|
||||||
new FacetDef("hardcover_rating", "Hardcover Rating", (cb, root, userId) -> metadata(root).get("hardcoverRating")),
|
new FacetDef("hardcover_rating", "Hardcover Rating", (cb, root, _) -> metadata(root).get("hardcoverRating")),
|
||||||
new FacetDef("ranobedb_rating", "RanobeDB Rating", (cb, root, userId) -> metadata(root).get("ranobedbRating")),
|
new FacetDef("ranobedb_rating", "RanobeDB Rating", (cb, root, _) -> metadata(root).get("ranobedbRating")),
|
||||||
new FacetDef("lubimyczytac_rating", "Lubimyczytac Rating", (cb, root, userId) -> metadata(root).get("lubimyczytacRating")),
|
new FacetDef("lubimyczytac_rating", "Lubimyczytac Rating", (cb, root, _) -> metadata(root).get("lubimyczytacRating")),
|
||||||
new FacetDef("audible_rating", "Audible Rating", (cb, root, userId) -> metadata(root).get("audibleRating")),
|
new FacetDef("audible_rating", "Audible Rating", (cb, root, _) -> metadata(root).get("audibleRating")),
|
||||||
new FacetDef("applebooks_rating", "Apple Books Rating", (cb, root, userId) -> metadata(root).get("applebooksRating")),
|
new FacetDef("applebooks_rating", "Apple Books Rating", (cb, root, _) -> metadata(root).get("applebooksRating")),
|
||||||
new FacetDef("age_rating", "Age Rating", (cb, root, userId) -> metadata(root).get("ageRating")),
|
new FacetDef("age_rating", "Age Rating", (cb, root, _) -> metadata(root).get("ageRating")),
|
||||||
new FacetDef("page_count", "Page Count", (cb, root, userId) -> metadata(root).get("pageCount")),
|
new FacetDef("page_count", "Page Count", (cb, root, _) -> metadata(root).get("pageCount")),
|
||||||
new FacetDef("match_score", "Match Score", (cb, root, userId) -> root.get("metadataMatchScore")),
|
new FacetDef("match_score", "Match Score", (cb, root, _) -> root.get("metadataMatchScore")),
|
||||||
new FacetDef("published_year", "Published Year", (cb, root, userId) ->
|
new FacetDef("published_year", "Published Year", (cb, root, _) ->
|
||||||
cb.function("YEAR", Integer.class, metadata(root).get("publishedDate"))),
|
cb.function("YEAR", Integer.class, metadata(root).get("publishedDate"))),
|
||||||
new FacetDef("library", "Library", (cb, root, userId) -> root.join("library").get("id")),
|
new FacetDef("library", "Library", (cb, root, _) -> root.join("library").get("id")),
|
||||||
new FacetDef("shelf", "Shelf", (cb, root, userId) -> root.join("shelves", JoinType.LEFT).get("id")),
|
new FacetDef("shelf", "Shelf", (cb, root, _) -> root.join("shelves", JoinType.LEFT).get("id")),
|
||||||
new FacetDef("shelf_status", "Shelf Status", (cb, root, userId) -> cb.<String>selectCase()
|
new FacetDef("shelf_status", "Shelf Status", (cb, root, _) -> cb.<String>selectCase()
|
||||||
.when(cb.isNotEmpty(root.get("shelves")), "shelved")
|
.when(cb.isNotEmpty(root.get("shelves")), "shelved")
|
||||||
.otherwise("unshelved")),
|
.otherwise("unshelved")),
|
||||||
new FacetDef("read_status", "Read Status", (cb, root, userId) -> {
|
new FacetDef("read_status", "Read Status", (cb, root, scope) -> {
|
||||||
Join<BookEntity, UserBookProgressEntity> progress = root.join("userBookProgress", JoinType.LEFT);
|
Join<BookEntity, UserBookProgressEntity> progress = root.join("userBookProgress", JoinType.LEFT);
|
||||||
progress.on(cb.equal(progress.get("user").get("id"), userId));
|
progress.on(cb.equal(progress.get("user").get("id"), scope.userId()));
|
||||||
return cb.<ReadStatus>selectCase()
|
return cb.<ReadStatus>selectCase()
|
||||||
.when(progress.get("id").isNull(), ReadStatus.UNSET)
|
.when(progress.get("id").isNull(), ReadStatus.UNSET)
|
||||||
.otherwise(progress.get("readStatus"));
|
.otherwise(progress.get("readStatus"));
|
||||||
}),
|
}),
|
||||||
new FacetDef("personal_rating", "Personal Rating", (cb, root, userId) -> {
|
new FacetDef("personal_rating", "Personal Rating", (cb, root, scope) -> {
|
||||||
Join<BookEntity, UserBookProgressEntity> progress = root.join("userBookProgress");
|
Join<BookEntity, UserBookProgressEntity> progress = root.join("userBookProgress");
|
||||||
progress.on(cb.equal(progress.get("user").get("id"), userId));
|
progress.on(cb.equal(progress.get("user").get("id"), scope.userId()));
|
||||||
return progress.get("personalRating");
|
return progress.get("personalRating");
|
||||||
}),
|
}),
|
||||||
new FacetDef("file_size", "File Size", (cb, root, userId) -> {
|
new FacetDef("file_size", "File Size", (cb, root, _) -> {
|
||||||
Join<BookEntity, BookFileEntity> files = root.join("bookFiles", JoinType.LEFT);
|
Join<BookEntity, BookFileEntity> files = root.join("bookFiles", JoinType.LEFT);
|
||||||
files.on(cb.isTrue(files.get("isBookFormat")));
|
files.on(cb.isTrue(files.get("isBookFormat")));
|
||||||
return files.get("fileSizeKb");
|
return files.get("fileSizeKb");
|
||||||
}),
|
}),
|
||||||
new FacetDef("comic_character", "Comic Characters", (cb, root, userId) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("characters", JoinType.LEFT).get("name")),
|
new FacetDef("comic_character", "Comic Characters", (cb, root, _) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("characters", JoinType.LEFT).get("name")),
|
||||||
new FacetDef("comic_team", "Comic Teams", (cb, root, userId) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("teams", JoinType.LEFT).get("name")),
|
new FacetDef("comic_team", "Comic Teams", (cb, root, _) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("teams", JoinType.LEFT).get("name")),
|
||||||
new FacetDef("comic_location", "Comic Locations", (cb, root, userId) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("locations", JoinType.LEFT).get("name")),
|
new FacetDef("comic_location", "Comic Locations", (cb, root, _) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("locations", JoinType.LEFT).get("name")),
|
||||||
new FacetDef("comic_creator", "Comic Creators", (cb, root, userId) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("creatorMappings", JoinType.LEFT).join("creator", JoinType.LEFT).get("name")));
|
new FacetDef("comic_creator", "Comic Creators", (cb, root, _) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("creatorMappings", JoinType.LEFT).join("creator", JoinType.LEFT).get("name"))
|
||||||
|
);
|
||||||
|
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
private final BookFilterSpecifications filterSpecifications;
|
private final BookFilterSpecifications filterSpecifications;
|
||||||
private final BookSortRegistry sortRegistry;
|
private final BookSortRegistry sortRegistry;
|
||||||
|
private final BrowseScopeFactory scopeFactory;
|
||||||
@PersistenceContext
|
private final EntityManager entityManager;
|
||||||
private EntityManager entityManager;
|
|
||||||
|
|
||||||
private final Cache<String, FacetGroupsResponse> cache = Caffeine.newBuilder()
|
private final Cache<String, FacetGroupsResponse> cache = Caffeine.newBuilder()
|
||||||
.expireAfterWrite(Duration.ofSeconds(30))
|
.expireAfterWrite(Duration.ofSeconds(30))
|
||||||
@@ -122,29 +116,33 @@ public class BookFacetService {
|
|||||||
public FacetGroupsResponse getFacets(List<String> facet, String facetLogicParam, String query) {
|
public FacetGroupsResponse getFacets(List<String> facet, String facetLogicParam, String query) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = user.getId();
|
Long userId = user.getId();
|
||||||
boolean isAdmin = user.getPermissions().isAdmin();
|
BrowseScope scope = scopeFactory.from(user);
|
||||||
Set<Long> libraryIds = BookFilterSpecifications.libraryIds(user);
|
|
||||||
|
|
||||||
Map<String, List<String>> facets = BookFilterSpecifications.parseFacets(facet);
|
Map<String, List<String>> facets = BrowseParams.parseFacets(facet);
|
||||||
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
FacetLogic facetLogic = FacetLogic.from(facetLogicParam);
|
||||||
|
|
||||||
String cacheKey = userId + ":" + ParamsHash.compute(query, facets, facetLogic);
|
String cacheKey = scope.userId() + ":" + ParamsHash.compute(query, facets, facetLogic);
|
||||||
return cache.get(cacheKey, key -> {
|
return cache.get(cacheKey, key -> {
|
||||||
String preserved = BrowseParams.preserved(facet, facetLogicParam, query);
|
String preserved = BrowseParams.preserved(facet, facetLogicParam, query);
|
||||||
|
FacetResponseBuilder builder = new FacetResponseBuilder(PAGE_PATH, FACET_PATH, preserved, facet);
|
||||||
List<FacetGroup> groups = new ArrayList<>();
|
List<FacetGroup> groups = new ArrayList<>();
|
||||||
groups.add(sortGroup(preserved));
|
groups.add(builder.sortGroup(sortRegistry.registry().keys()));
|
||||||
for (FacetDef def : FACETS) {
|
for (FacetDef def : FACETS) {
|
||||||
Specification<BookEntity> base = filterSpecifications.base(query, facets, facetLogic, userId, isAdmin, libraryIds, def.key());
|
|
||||||
List<FacetCount> counts = count(def, base, userId);
|
Specification<BookEntity> base = filterSpecifications.base(query, facets, facetLogic, scope, def.key());
|
||||||
|
var counts = count(def, base, scope);
|
||||||
if ("file_type".equals(def.key())) {
|
if ("file_type".equals(def.key())) {
|
||||||
counts = Stream.concat(counts.stream(), count(PHYSICAL_FILE_TYPE, base, userId).stream())
|
counts = Stream.concat(counts.stream(), count(PHYSICAL_FILE_TYPE, base, scope).stream())
|
||||||
.sorted(Comparator.comparingLong(FacetCount::count).reversed().thenComparing(FacetCount::value))
|
.sorted(
|
||||||
|
Comparator.comparingLong(FacetResponseBuilder.FacetCount::count)
|
||||||
|
.reversed()
|
||||||
|
.thenComparing(FacetResponseBuilder.FacetCount::value)
|
||||||
|
)
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
groups.add(toGroup(def, counts, facet, preserved));
|
groups.add(builder.group(def.key(), def.title(), counts));
|
||||||
}
|
}
|
||||||
List<Link> links = List.of(Link.json(List.of("self"), href(FACET_PATH, preserved)));
|
return new FacetGroupsResponse(builder.selfLinks(), groups);
|
||||||
return new FacetGroupsResponse(links, groups);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,11 +151,11 @@ public class BookFacetService {
|
|||||||
cache.invalidateAll();
|
cache.invalidateAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<FacetCount> count(FacetDef def, Specification<BookEntity> base, Long userId) {
|
private List<FacetResponseBuilder.FacetCount> count(FacetDef def, Specification<BookEntity> base, BrowseScope scope) {
|
||||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||||
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
|
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
|
||||||
Root<BookEntity> root = cq.from(BookEntity.class);
|
Root<BookEntity> root = cq.from(BookEntity.class);
|
||||||
Expression<?> value = def.value().apply(cb, root, userId);
|
Expression<?> value = def.value().apply(cb, root, scope);
|
||||||
Expression<Long> count = cb.countDistinct(root.get("id"));
|
Expression<Long> count = cb.countDistinct(root.get("id"));
|
||||||
|
|
||||||
List<Predicate> predicates = new ArrayList<>();
|
List<Predicate> predicates = new ArrayList<>();
|
||||||
@@ -173,55 +171,18 @@ public class BookFacetService {
|
|||||||
cq.orderBy(cb.desc(count), cb.asc(value));
|
cq.orderBy(cb.desc(count), cb.asc(value));
|
||||||
|
|
||||||
return entityManager.createQuery(cq).setMaxResults(MAX_VALUES).getResultList().stream()
|
return entityManager.createQuery(cq).setMaxResults(MAX_VALUES).getResultList().stream()
|
||||||
.map(tuple -> new FacetCount(String.valueOf(tuple.get("value")), ((Number) tuple.get("count")).longValue()))
|
.map(tuple -> new FacetResponseBuilder.FacetCount(String.valueOf(tuple.get("value")), ((Number) tuple.get("count")).longValue()))
|
||||||
.toList();
|
.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) {
|
private static Join<?, ?> metadata(Root<BookEntity> root) {
|
||||||
return root.join("metadata", JoinType.LEFT);
|
return root.join("metadata", JoinType.LEFT);
|
||||||
}
|
}
|
||||||
|
|
||||||
private interface FacetValueSource {
|
private interface FacetValueSource {
|
||||||
Expression<?> apply(CriteriaBuilder cb, Root<BookEntity> root, Long userId);
|
Expression<?> apply(CriteriaBuilder cb, Root<BookEntity> root, BrowseScope scope);
|
||||||
}
|
}
|
||||||
|
|
||||||
private record FacetDef(String key, String title, FacetValueSource value) {
|
private record FacetDef(String key, String title, FacetValueSource value) {
|
||||||
}
|
}
|
||||||
|
|
||||||
private record FacetCount(String value, long count) {
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,37 +4,30 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import org.booklore.app.specification.AppBookSpecification;
|
import org.booklore.app.specification.AppBookSpecification;
|
||||||
import org.booklore.browse.FacetLogic;
|
import org.booklore.browse.FacetLogic;
|
||||||
import org.booklore.exception.ApiError;
|
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.model.entity.BookEntity;
|
||||||
import org.booklore.repository.UserContentRestrictionRepository;
|
|
||||||
import org.booklore.security.policy.ContentRestrictionSpecification;
|
|
||||||
import org.springframework.data.jpa.domain.Specification;
|
import org.springframework.data.jpa.domain.Specification;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class BookFilterSpecifications {
|
public class BookFilterSpecifications {
|
||||||
|
|
||||||
private final BookFacetRegistry facetRegistry;
|
private final BookFacetRegistry facetRegistry;
|
||||||
private final UserContentRestrictionRepository restrictionRepository;
|
|
||||||
|
|
||||||
public Specification<BookEntity> base(String query, Map<String, List<String>> facets, FacetLogic facetLogic,
|
public Specification<BookEntity> base(
|
||||||
Long userId, boolean isAdmin, Set<Long> libraryIds, String omitFacet) {
|
String query,
|
||||||
|
Map<String, List<String>> facets,
|
||||||
|
FacetLogic facetLogic,
|
||||||
|
BrowseScope scope,
|
||||||
|
String omitFacet
|
||||||
|
) {
|
||||||
List<Specification<BookEntity>> specs = new ArrayList<>();
|
List<Specification<BookEntity>> specs = new ArrayList<>();
|
||||||
specs.add(AppBookSpecification.notDeleted());
|
specs.add(scope.visibleBooks());
|
||||||
if (!isAdmin) {
|
|
||||||
specs.add(inLibraries(libraryIds));
|
|
||||||
specs.add(ContentRestrictionSpecification.from(restrictionRepository.findByUserId(userId)));
|
|
||||||
}
|
|
||||||
if (query != null && !query.isBlank()) {
|
if (query != null && !query.isBlank()) {
|
||||||
specs.add(BookSearchSpecification.matching(query));
|
specs.add(BookSearchSpecification.matching(query));
|
||||||
}
|
}
|
||||||
@@ -45,39 +38,8 @@ public class BookFilterSpecifications {
|
|||||||
if (!facetRegistry.has(entry.getKey())) {
|
if (!facetRegistry.has(entry.getKey())) {
|
||||||
throw ApiError.INVALID_FACET.createException("Unknown facet: " + entry.getKey());
|
throw ApiError.INVALID_FACET.createException("Unknown facet: " + entry.getKey());
|
||||||
}
|
}
|
||||||
specs.add(facetRegistry.toSpecification(entry.getKey(), entry.getValue(), facetLogic, userId));
|
specs.add(facetRegistry.toSpecification(entry.getKey(), entry.getValue(), facetLogic, scope.userId()));
|
||||||
}
|
}
|
||||||
return AppBookSpecification.combine(specs.toArray(Specification[]::new));
|
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,37 @@
|
|||||||
package org.booklore.service.browse;
|
package org.booklore.service.browse;
|
||||||
|
|
||||||
|
import org.booklore.exception.ApiError;
|
||||||
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
final class BrowseParams {
|
final class BrowseParams {
|
||||||
|
|
||||||
private BrowseParams() {
|
private BrowseParams() {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
static String preserved(List<String> facet, String facetLogic, String query) {
|
static String preserved(List<String> facet, String facetLogic, String query) {
|
||||||
List<String> parts = new ArrayList<>();
|
List<String> parts = new ArrayList<>();
|
||||||
if (facet != null) {
|
if (facet != null) {
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package org.booklore.service.browse;
|
||||||
|
|
||||||
|
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||||
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
|
import jakarta.persistence.criteria.Predicate;
|
||||||
|
import jakarta.persistence.criteria.Root;
|
||||||
|
import org.booklore.model.entity.BookEntity;
|
||||||
|
import org.springframework.data.jpa.domain.Specification;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public record BrowseScope(
|
||||||
|
Long userId,
|
||||||
|
boolean isAdmin,
|
||||||
|
Set<Long> libraryIds,
|
||||||
|
Specification<BookEntity> contentRestriction
|
||||||
|
) {
|
||||||
|
|
||||||
|
public Predicate visibleBook(Root<BookEntity> book, CriteriaQuery<?> query, CriteriaBuilder cb) {
|
||||||
|
List<Predicate> predicates = new ArrayList<>();
|
||||||
|
predicates.add(cb.or(cb.isNull(book.get("deleted")), cb.equal(book.get("deleted"), false)));
|
||||||
|
if (!isAdmin) {
|
||||||
|
predicates.add(libraryIds.isEmpty()
|
||||||
|
? cb.disjunction()
|
||||||
|
: book.get("library").get("id").in(libraryIds));
|
||||||
|
if (contentRestriction != null) {
|
||||||
|
Predicate restriction = contentRestriction.toPredicate(book, query, cb);
|
||||||
|
if (restriction != null) {
|
||||||
|
predicates.add(restriction);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cb.and(predicates.toArray(Predicate[]::new));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Specification<BookEntity> visibleBooks() {
|
||||||
|
return this::visibleBook;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package org.booklore.service.browse;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.booklore.model.dto.BookLoreUser;
|
||||||
|
import org.booklore.model.dto.Library;
|
||||||
|
import org.booklore.repository.UserContentRestrictionRepository;
|
||||||
|
import org.booklore.security.policy.ContentRestrictionSpecification;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class BrowseScopeFactory {
|
||||||
|
|
||||||
|
private final UserContentRestrictionRepository restrictionRepository;
|
||||||
|
|
||||||
|
private Set<Long> assignedLibraryIds(BookLoreUser user) {
|
||||||
|
if (user.getAssignedLibraries() == null) {
|
||||||
|
return Set.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
return user.getAssignedLibraries()
|
||||||
|
.stream()
|
||||||
|
.map(Library::getId)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
}
|
||||||
|
|
||||||
|
public BrowseScope from(BookLoreUser user) {
|
||||||
|
boolean isAdmin = user.getPermissions().isAdmin();
|
||||||
|
return new BrowseScope(
|
||||||
|
user.getId(),
|
||||||
|
isAdmin,
|
||||||
|
assignedLibraryIds(user),
|
||||||
|
isAdmin ? null : ContentRestrictionSpecification.from(restrictionRepository.findByUserId(user.getId())));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package org.booklore.service.browse;
|
||||||
|
|
||||||
|
import org.booklore.browse.Link;
|
||||||
|
import org.booklore.browse.SortParser;
|
||||||
|
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 java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
final class FacetResponseBuilder {
|
||||||
|
|
||||||
|
record FacetCount(String value, long count) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private final String pagePath;
|
||||||
|
private final String facetPath;
|
||||||
|
private final String preserved;
|
||||||
|
private final List<String> selectedFacets;
|
||||||
|
|
||||||
|
FacetResponseBuilder(String pagePath, String facetPath, String preserved, List<String> selectedFacets) {
|
||||||
|
this.pagePath = pagePath;
|
||||||
|
this.facetPath = facetPath;
|
||||||
|
this.preserved = preserved;
|
||||||
|
this.selectedFacets = selectedFacets;
|
||||||
|
}
|
||||||
|
|
||||||
|
FacetGroup sortGroup(Set<String> sortKeys) {
|
||||||
|
List<FacetLink> links = new ArrayList<>();
|
||||||
|
for (String key : sortKeys) {
|
||||||
|
if (key.equals(SortParser.TIEBREAKER_KEY)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
links.add(new FacetLink(List.of("sort"), pageLink("sort=" + BrowseParams.encode(key)), Link.JSON_TYPE, key + " ascending", key, null));
|
||||||
|
links.add(new FacetLink(List.of("sort"), pageLink("sort=-" + BrowseParams.encode(key)), Link.JSON_TYPE, key + " descending", "-" + key, null));
|
||||||
|
}
|
||||||
|
return new FacetGroup(new Metadata("sort", "sort", "Sort"), links);
|
||||||
|
}
|
||||||
|
|
||||||
|
FacetGroup group(String key, String title, List<FacetCount> counts) {
|
||||||
|
List<FacetLink> links = counts.stream()
|
||||||
|
.map(c -> {
|
||||||
|
boolean active = BrowseParams.hasFacet(selectedFacets, key, c.value());
|
||||||
|
List<String> rel = active ? List.of("self", "facet") : List.of("facet");
|
||||||
|
String href = active
|
||||||
|
? href(pagePath)
|
||||||
|
: pageLink("facet=" + BrowseParams.encode(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", key, title), links);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Link> selfLinks() {
|
||||||
|
return List.of(Link.json(List.of("self"), href(facetPath)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String pageLink(String param) {
|
||||||
|
return preserved.isBlank() ? pagePath + "?" + param : pagePath + "?" + preserved + "&" + param;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String href(String path) {
|
||||||
|
return preserved.isBlank() ? path : path + "?" + preserved;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,7 +17,10 @@ import org.booklore.model.entity.BookMetadataEntity;
|
|||||||
import org.booklore.model.entity.CategoryEntity;
|
import org.booklore.model.entity.CategoryEntity;
|
||||||
import org.booklore.model.entity.LibraryEntity;
|
import org.booklore.model.entity.LibraryEntity;
|
||||||
import org.booklore.model.entity.LibraryPathEntity;
|
import org.booklore.model.entity.LibraryPathEntity;
|
||||||
|
import org.booklore.model.entity.UserContentRestrictionEntity;
|
||||||
import org.booklore.model.enums.BookFileType;
|
import org.booklore.model.enums.BookFileType;
|
||||||
|
import org.booklore.model.enums.ContentRestrictionMode;
|
||||||
|
import org.booklore.model.enums.ContentRestrictionType;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.service.task.TaskCronService;
|
import org.booklore.service.task.TaskCronService;
|
||||||
import org.flywaydb.core.Flyway;
|
import org.flywaydb.core.Flyway;
|
||||||
@@ -325,4 +328,43 @@ class BookBrowseServiceTest {
|
|||||||
assertThat(result.content()).hasSize(1);
|
assertThat(result.content()).hasSize(1);
|
||||||
assertThat(result.content().get(0).getId()).isNotEqualTo(outside.getId());
|
assertThat(result.content().get(0).getId()).isNotEqualTo(outside.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nonAdminWithNoLibrariesSeesNothing() {
|
||||||
|
book("Alpha", List.of());
|
||||||
|
em.flush();
|
||||||
|
when(authenticationService.getAuthenticatedUser()).thenReturn(noLibrariesUser());
|
||||||
|
|
||||||
|
BrowsePage<Book> result = browse(null, null, null, null, 0, 20);
|
||||||
|
assertThat(result.content()).isEmpty();
|
||||||
|
assertThat(result.page().totalElements()).isZero();
|
||||||
|
assertThat(browseService.findAllIds(null, null, null, null)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void contentRestrictionsExcludeBooks() {
|
||||||
|
em.persist(UserContentRestrictionEntity.builder()
|
||||||
|
.user(userEntity)
|
||||||
|
.restrictionType(ContentRestrictionType.CATEGORY)
|
||||||
|
.mode(ContentRestrictionMode.EXCLUDE)
|
||||||
|
.value("Horror")
|
||||||
|
.build());
|
||||||
|
Long romance = book("R", List.of("Romance")).getId();
|
||||||
|
book("H", List.of("Horror"));
|
||||||
|
em.flush();
|
||||||
|
|
||||||
|
assertThat(browse(null, null, null, null, 0, 20).content().stream().map(Book::getId))
|
||||||
|
.containsExactly(romance);
|
||||||
|
assertThat(browseService.findAllIds(null, null, null, null)).containsExactly(romance);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BookLoreUser noLibrariesUser() {
|
||||||
|
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
|
||||||
|
permissions.setAdmin(false);
|
||||||
|
return BookLoreUser.builder()
|
||||||
|
.id(userEntity.getId())
|
||||||
|
.assignedLibraries(List.of())
|
||||||
|
.permissions(permissions)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,10 @@ import org.booklore.model.entity.BookMetadataEntity;
|
|||||||
import org.booklore.model.entity.CategoryEntity;
|
import org.booklore.model.entity.CategoryEntity;
|
||||||
import org.booklore.model.entity.LibraryEntity;
|
import org.booklore.model.entity.LibraryEntity;
|
||||||
import org.booklore.model.entity.LibraryPathEntity;
|
import org.booklore.model.entity.LibraryPathEntity;
|
||||||
|
import org.booklore.model.entity.UserContentRestrictionEntity;
|
||||||
import org.booklore.model.enums.BookFileType;
|
import org.booklore.model.enums.BookFileType;
|
||||||
|
import org.booklore.model.enums.ContentRestrictionMode;
|
||||||
|
import org.booklore.model.enums.ContentRestrictionType;
|
||||||
import org.booklore.service.task.TaskCronService;
|
import org.booklore.service.task.TaskCronService;
|
||||||
import org.flywaydb.core.Flyway;
|
import org.flywaydb.core.Flyway;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
@@ -366,4 +369,41 @@ class BookFacetServiceTest {
|
|||||||
assertThat(json).doesNotContain("\"rel\":[\"self\"]");
|
assertThat(json).doesNotContain("\"rel\":[\"self\"]");
|
||||||
assertThat(json).doesNotContain("\"rel\":[\"facet\"]");
|
assertThat(json).doesNotContain("\"rel\":[\"facet\"]");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nonAdminWithNoLibrariesGetsNoFacetValues() {
|
||||||
|
book("A", "Horror", "Alice");
|
||||||
|
em.flush();
|
||||||
|
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
|
||||||
|
permissions.setAdmin(false);
|
||||||
|
when(authenticationService.getAuthenticatedUser()).thenReturn(BookLoreUser.builder()
|
||||||
|
.id(userEntity.getId())
|
||||||
|
.assignedLibraries(List.of())
|
||||||
|
.permissions(permissions)
|
||||||
|
.build());
|
||||||
|
|
||||||
|
FacetGroupsResponse response = facetService.getFacets(null, null, null);
|
||||||
|
|
||||||
|
assertThat(group(response, "genre").links()).isEmpty();
|
||||||
|
assertThat(group(response, "author").links()).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void contentRestrictionsExcludeBooksFromCounts() {
|
||||||
|
em.persist(UserContentRestrictionEntity.builder()
|
||||||
|
.user(userEntity)
|
||||||
|
.restrictionType(ContentRestrictionType.CATEGORY)
|
||||||
|
.mode(ContentRestrictionMode.EXCLUDE)
|
||||||
|
.value("Horror")
|
||||||
|
.build());
|
||||||
|
book("H", "Horror", "Alice");
|
||||||
|
book("R", "Romance", "Bob");
|
||||||
|
em.flush();
|
||||||
|
|
||||||
|
FacetGroupsResponse response = facetService.getFacets(null, null, null);
|
||||||
|
|
||||||
|
assertThat(count(group(response, "genre"), "Romance")).isEqualTo(1);
|
||||||
|
assertThat(count(group(response, "genre"), "Horror")).isNull();
|
||||||
|
assertThat(count(group(response, "author"), "Alice")).isNull();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user