feat(shelf): add shelf filtering options and integrate into book processing (#2268)

* feat(shelf): add shelf filtering options and integrate into book processing

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(book-rule-evaluator): normalize array values to lowercase for rule comparisons

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* feat(filter): enhance library and shelf filtering logic for 'or' and 'and' modes

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* feat(shelf): implement support for multiple shelf IDs in book retrieval and filtering

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

---------

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
Balázs Szücs
2026-01-15 19:58:30 -07:00
committed by GitHub
parent 869bea9ca5
commit 775887b55f
13 changed files with 545 additions and 28 deletions
@@ -5,6 +5,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
public enum RuleField {
@JsonProperty("library")
LIBRARY,
@JsonProperty("shelf")
SHELF,
@JsonProperty("title")
TITLE,
@JsonProperty("subtitle")
@@ -105,6 +105,38 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
@Query("SELECT DISTINCT b FROM BookEntity b WHERE b.id IN :ids AND b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithFullMetadataByIdsAndLibraryIds(@Param("ids") Collection<Long> ids, @Param("libraryIds") Collection<Long> libraryIds);
// ============================================
// SEARCH BY METADATA IN SHELVES - Two Query Pattern
// ============================================
@Query("""
SELECT DISTINCT b.id FROM BookEntity b
LEFT JOIN b.metadata m
JOIN b.shelves s
WHERE (b.deleted IS NULL OR b.deleted = false)
AND s.id IN :shelfIds
AND (
m.searchText LIKE CONCAT('%', :text, '%')
)
ORDER BY b.addedOn DESC
""")
Page<Long> findBookIdsByMetadataSearchAndShelfIds(@Param("text") String text, @Param("shelfIds") Collection<Long> shelfIds, Pageable pageable);
@EntityGraph(attributePaths = {"metadata", "metadata.authors", "metadata.categories", "additionalFiles", "shelves"})
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.shelves s WHERE b.id IN :ids AND s.id IN :shelfIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithFullMetadataByIdsAndShelfIds(@Param("ids") Collection<Long> ids, @Param("shelfIds") Collection<Long> shelfIds);
// ============================================
// BOOKS BY SHELF IDs - Two Query Pattern
// ============================================
@Query("SELECT DISTINCT b.id FROM BookEntity b JOIN b.shelves s WHERE s.id IN :shelfIds AND (b.deleted IS NULL OR b.deleted = false) ORDER BY b.addedOn DESC")
Page<Long> findBookIdsByShelfIds(@Param("shelfIds") Collection<Long> shelfIds, Pageable pageable);
@EntityGraph(attributePaths = {"metadata", "additionalFiles", "shelves"})
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.shelves s WHERE b.id IN :ids AND s.id IN :shelfIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByIdsAndShelfIds(@Param("ids") Collection<Long> ids, @Param("shelfIds") Collection<Long> shelfIds);
// ============================================
// RANDOM BOOKS - "Surprise Me" Feed
// ============================================
@@ -232,8 +232,12 @@ public class BookRuleEvaluatorService {
Subquery<Long> subquery = cb.createQuery().subquery(Long.class);
Root<BookEntity> subRoot = subquery.from(BookEntity.class);
Join<Object, Object> metadataJoin = subRoot.join("metadata", JoinType.INNER);
joinArrayField(rule.getField(), metadataJoin);
if (rule.getField() == RuleField.SHELF) {
subRoot.join("shelves", JoinType.INNER);
} else {
Join<Object, Object> metadataJoin = subRoot.join("metadata", JoinType.INNER);
joinArrayField(rule.getField(), metadataJoin);
}
subquery.select(cb.literal(1L)).where(cb.equal(subRoot.get("id"), root.get("id")));
@@ -309,6 +313,7 @@ public class BookRuleEvaluatorService {
private Expression<?> getFieldExpression(RuleField field, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
return switch (field) {
case LIBRARY -> root.get("library").get("id");
case SHELF -> null; // Shelf is handled specially as a join field
case READ_STATUS -> progressJoin.get("readStatus");
case DATE_FINISHED -> progressJoin.get("dateFinished");
case LAST_READ_TIME -> progressJoin.get("lastReadTime");
@@ -342,15 +347,21 @@ public class BookRuleEvaluatorService {
private boolean isArrayField(RuleField field) {
return field == RuleField.AUTHORS || field == RuleField.CATEGORIES ||
field == RuleField.MOODS || field == RuleField.TAGS ||
field == RuleField.GENRE;
field == RuleField.GENRE || field == RuleField.SHELF;
}
private Join<?, ?> createArrayFieldJoin(RuleField field, Root<BookEntity> root) {
if (field == RuleField.SHELF) {
return root.join("shelves", JoinType.INNER);
}
Join<Object, Object> metadataJoin = root.join("metadata", JoinType.INNER);
return joinArrayField(field, metadataJoin);
}
private Expression<String> getArrayFieldNameExpression(RuleField field, Join<?, ?> arrayJoin) {
if (field == RuleField.SHELF) {
return arrayJoin.get("id").as(String.class);
}
return arrayJoin.get("name");
}
@@ -53,7 +53,7 @@ public class OpdsBookService {
return user.getAssignedLibraries();
}
public Page<Book> getBooksPage(Long userId, String query, Long libraryId, Long shelfId, int page, int size) {
public Page<Book> getBooksPage(Long userId, String query, Long libraryId, Set<Long> shelfIds, int page, int size) {
if (userId == null) {
throw ApiError.FORBIDDEN.createException("Authentication required");
}
@@ -72,9 +72,12 @@ public class OpdsBookService {
.map(Library::getId)
.collect(Collectors.toSet());
if (shelfId != null) {
validateShelfAccess(shelfId, user.getId(), isAdmin);
return getBooksByShelfIdPageInternal(shelfId, page, size);
if (shelfIds != null && !shelfIds.isEmpty()) {
validateShelfAccess(shelfIds, user.getId(), isAdmin);
Page<Book> books = query != null && !query.isBlank()
? searchByMetadataInShelvesPageInternal(BookUtils.normalizeForSearch(query), shelfIds, page, size)
: getBooksByShelfIdsPageInternal(shelfIds, page, size);
return applyBookFilters(books, userId);
}
if (libraryId != null) {
@@ -335,6 +338,18 @@ public class OpdsBookService {
return createPageFromEntities(books, idPage, pageable);
}
private Page<Book> getBooksByShelfIdsPageInternal(Set<Long> shelfIds, int page, int size) {
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
Page<Long> idPage = bookOpdsRepository.findBookIdsByShelfIds(shelfIds, pageable);
if (idPage.isEmpty()) {
return new PageImpl<>(List.of(), pageable, 0);
}
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIdsAndShelfIds(idPage.getContent(), shelfIds);
return createPageFromEntities(books, idPage, pageable);
}
private Page<Book> searchByMetadataPageInternal(String text, int page, int size) {
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
@@ -359,6 +374,18 @@ public class OpdsBookService {
return createPageFromEntities(books, idPage, pageable);
}
private Page<Book> searchByMetadataInShelvesPageInternal(String text, Set<Long> shelfIds, int page, int size) {
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
Page<Long> idPage = bookOpdsRepository.findBookIdsByMetadataSearchAndShelfIds(text, shelfIds, pageable);
if (idPage.isEmpty()) {
return new PageImpl<>(List.of(), pageable, 0);
}
List<BookEntity> books = bookOpdsRepository.findAllWithFullMetadataByIdsAndShelfIds(idPage.getContent(), shelfIds);
return createPageFromEntities(books, idPage, pageable);
}
private void validateShelfAccess(Long shelfId, Long userId, boolean isAdmin) {
var shelf = shelfRepository.findById(shelfId)
.orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
@@ -367,6 +394,12 @@ public class OpdsBookService {
}
}
private void validateShelfAccess(Set<Long> shelfIds, Long userId, boolean isAdmin) {
for (Long shelfId : shelfIds) {
validateShelfAccess(shelfId, userId, isAdmin);
}
}
private void validateLibraryAccess(Long libraryId, Set<Long> userLibraryIds, boolean isAdmin) {
if (!isAdmin && !userLibraryIds.contains(libraryId)) {
throw ApiError.FORBIDDEN.createException("You are not allowed to access this library");
@@ -6,13 +6,12 @@ import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.Library;
import com.adityachandel.booklore.model.enums.OpdsSortOrder;
import com.adityachandel.booklore.service.MagicShelfService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.ArchiveUtils;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.util.RequestUtils;
import java.io.File;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Set;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -317,7 +316,7 @@ public class OpdsFeedService {
public String generateCatalogFeed(HttpServletRequest request) {
Long libraryId = parseLongParam(request, "libraryId", null);
Long shelfId = parseLongParam(request, "shelfId", null);
Set<Long> shelfIds = parseShelfIds(request);
Long magicShelfId = parseLongParam(request, "magicShelfId", null);
String query = request.getParameter("q");
String author = request.getParameter("author");
@@ -336,14 +335,14 @@ public class OpdsFeedService {
} else if (series != null && !series.isBlank()) {
booksPage = opdsBookService.getBooksBySeriesName(userId, series, page - 1, size);
} else {
booksPage = opdsBookService.getBooksPage(userId, query, libraryId, shelfId, page - 1, size);
booksPage = opdsBookService.getBooksPage(userId, query, libraryId, shelfIds, page - 1, size);
}
// Apply user's preferred sort order
booksPage = opdsBookService.applySortOrder(booksPage, sortOrder);
String feedTitle = determineFeedTitle(libraryId, shelfId, magicShelfId, author, series);
String feedId = determineFeedId(libraryId, shelfId, magicShelfId, author, series);
String feedTitle = determineFeedTitle(libraryId, shelfIds, magicShelfId, author, series);
String feedId = determineFeedId(libraryId, shelfIds, magicShelfId, author, series);
var feed = new StringBuilder("""
<?xml version="1.0" encoding="UTF-8"?>
@@ -558,12 +557,15 @@ public class OpdsFeedService {
}
}
private String determineFeedTitle(Long libraryId, Long shelfId, Long magicShelfId, String author, String series) {
private String determineFeedTitle(Long libraryId, Set<Long> shelfIds, Long magicShelfId, String author, String series) {
if (magicShelfId != null) {
return magicShelfBookService.getMagicShelfName(magicShelfId);
}
if (shelfId != null) {
return opdsBookService.getShelfName(shelfId);
if (shelfIds != null && !shelfIds.isEmpty()) {
if (shelfIds.size() == 1) {
return opdsBookService.getShelfName(shelfIds.iterator().next());
}
return "Multiple Shelves";
}
if (libraryId != null) {
return opdsBookService.getLibraryName(libraryId);
@@ -577,12 +579,15 @@ public class OpdsFeedService {
return "Booklore Catalog";
}
private String determineFeedId(Long libraryId, Long shelfId, Long magicShelfId, String author, String series) {
private String determineFeedId(Long libraryId, Set<Long> shelfIds, Long magicShelfId, String author, String series) {
if (magicShelfId != null) {
return "urn:booklore:magic-shelf:" + magicShelfId;
}
if (shelfId != null) {
return "urn:booklore:shelf:" + shelfId;
if (shelfIds != null && !shelfIds.isEmpty()) {
if (shelfIds.size() == 1) {
return "urn:booklore:shelf:" + shelfIds.iterator().next();
}
return "urn:booklore:shelves:" + String.join(",", shelfIds.stream().map(String::valueOf).sorted().toList());
}
if (libraryId != null) {
return "urn:booklore:library:" + libraryId;
@@ -666,6 +671,34 @@ public class OpdsFeedService {
}
}
private Set<Long> parseShelfIds(HttpServletRequest request) {
String shelfIdParam = request.getParameter("shelfId");
String shelfIdsParam = request.getParameter("shelfIds");
Set<Long> shelfIds = new HashSet<>();
// Support both single shelfId and comma-separated shelfIds
if (shelfIdParam != null && !shelfIdParam.isBlank()) {
try {
shelfIds.add(Long.parseLong(shelfIdParam));
} catch (NumberFormatException e) {
log.warn("Invalid shelfId parameter: {}", shelfIdParam);
}
}
if (shelfIdsParam != null && !shelfIdsParam.isBlank()) {
for (String id : shelfIdsParam.split(",")) {
try {
shelfIds.add(Long.parseLong(id.trim()));
} catch (NumberFormatException e) {
log.warn("Invalid shelf ID in shelfIds parameter: {}", id);
}
}
}
return shelfIds.isEmpty() ? null : shelfIds;
}
private Long getUserId() {
OpdsUserDetails details = authenticationService.getOpdsUser();
return details != null && details.getOpdsUserV2() != null