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
@@ -29,6 +29,7 @@ import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
class OpdsBookServiceTest {
@@ -147,15 +148,19 @@ class OpdsBookServiceTest {
when(bookOpdsRepository.findRecentBookIds(any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByLibraryIds(anySet(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByShelfId(anyLong(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByShelfIds(anySet(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByMetadataSearch(anyString(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByMetadataSearchAndLibraryIds(anyString(), anySet(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByMetadataSearchAndShelfIds(anyString(), anySet(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findAllWithMetadataByIds(anyList())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(anyList(), anySet())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithMetadataByIdsAndShelfId(anyList(), anyLong())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithMetadataByIdsAndShelfIds(anyList(), anySet())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithFullMetadataByIds(anyList())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithFullMetadataByIdsAndLibraryIds(anyList(), anySet())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithFullMetadataByIdsAndShelfIds(anyList(), anySet())).thenReturn(List.of());
opdsBookService.getBooksPage(details.getOpdsUserV2().getUserId(), "q", 1L, 2L, 0, 10);
opdsBookService.getBooksPage(details.getOpdsUserV2().getUserId(), "q", 1L, Set.of(2L), 0, 10);
}
@Test
@@ -165,12 +170,16 @@ class OpdsBookServiceTest {
when(bookOpdsRepository.findRecentBookIds(any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByLibraryIds(anySet(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByShelfId(anyLong(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByShelfIds(anySet(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByMetadataSearch(anyString(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findBookIdsByMetadataSearchAndShelfIds(anyString(), anySet(), any())).thenReturn(Page.empty());
when(bookOpdsRepository.findAllWithMetadataByIds(anyList())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(anyList(), anySet())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithMetadataByIdsAndShelfId(anyList(), anyLong())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithMetadataByIdsAndShelfIds(anyList(), anySet())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithFullMetadataByIds(anyList())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithFullMetadataByIdsAndLibraryIds(anyList(), anySet())).thenReturn(List.of());
when(bookOpdsRepository.findAllWithFullMetadataByIdsAndShelfIds(anyList(), anySet())).thenReturn(List.of());
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
var permissionsEntity = mock(com.adityachandel.booklore.model.entity.UserPermissionsEntity.class);
@@ -191,7 +200,7 @@ class OpdsBookServiceTest {
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(anyLong())).thenReturn(Optional.of(shelf));
opdsBookService.getBooksPage(details.getOpdsUserV2().getUserId(), "q", 1L, 2L, 0, 10);
opdsBookService.getBooksPage(details.getOpdsUserV2().getUserId(), "q", 1L, Set.of(2L), 0, 10);
}
@Test
@@ -331,4 +340,191 @@ class OpdsBookServiceTest {
).hasMessageContaining("You are not allowed to access this resource");
}
@Test
void getBooksPage_withSingleShelfId_returnsShelfBooks() {
OpdsUserDetails details = v2UserDetails(1L, false, Set.of(1L));
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
var permissionsEntity = mock(com.adityachandel.booklore.model.entity.UserPermissionsEntity.class);
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
when(user.getPermissions()).thenReturn(perms);
when(perms.isAdmin()).thenReturn(false);
when(perms.isCanAccessOpds()).thenReturn(true);
when(user.getId()).thenReturn(1L);
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(1L).watch(false).build()));
ShelfEntity shelf = mock(ShelfEntity.class);
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(1L);
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
BookEntity bookEntity = mock(BookEntity.class);
when(bookEntity.getId()).thenReturn(1L);
Book book = Book.builder().id(1L).build();
when(bookMapper.toBook(bookEntity)).thenReturn(book);
when(bookOpdsRepository.findBookIdsByShelfIds(eq(Set.of(10L)), any())).thenReturn(new PageImpl<>(List.of(1L)));
when(bookOpdsRepository.findAllWithMetadataByIdsAndShelfIds(eq(List.of(1L)), eq(Set.of(10L)))).thenReturn(List.of(bookEntity));
Page<Book> result = opdsBookService.getBooksPage(1L, null, null, Set.of(10L), 0, 10);
assertThat(result.getContent()).hasSize(1);
verify(bookOpdsRepository).findBookIdsByShelfIds(eq(Set.of(10L)), any());
}
@Test
void getBooksPage_withMultipleShelfIds_returnsShelfBooks() {
OpdsUserDetails details = v2UserDetails(1L, false, Set.of(1L));
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
var permissionsEntity = mock(com.adityachandel.booklore.model.entity.UserPermissionsEntity.class);
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
when(user.getPermissions()).thenReturn(perms);
when(perms.isAdmin()).thenReturn(false);
when(perms.isCanAccessOpds()).thenReturn(true);
when(user.getId()).thenReturn(1L);
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(1L).watch(false).build()));
ShelfEntity shelf1 = mock(ShelfEntity.class);
ShelfEntity shelf2 = mock(ShelfEntity.class);
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(1L);
when(shelf1.getUser()).thenReturn(shelfUser);
when(shelf2.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf1));
when(shelfRepository.findById(20L)).thenReturn(Optional.of(shelf2));
BookEntity bookEntity1 = mock(BookEntity.class);
BookEntity bookEntity2 = mock(BookEntity.class);
when(bookEntity1.getId()).thenReturn(1L);
when(bookEntity2.getId()).thenReturn(2L);
Book book1 = Book.builder().id(1L).build();
Book book2 = Book.builder().id(2L).build();
when(bookMapper.toBook(bookEntity1)).thenReturn(book1);
when(bookMapper.toBook(bookEntity2)).thenReturn(book2);
when(bookOpdsRepository.findBookIdsByShelfIds(eq(Set.of(10L, 20L)), any())).thenReturn(new PageImpl<>(List.of(1L, 2L)));
when(bookOpdsRepository.findAllWithMetadataByIdsAndShelfIds(eq(List.of(1L, 2L)), eq(Set.of(10L, 20L)))).thenReturn(List.of(bookEntity1, bookEntity2));
Page<Book> result = opdsBookService.getBooksPage(1L, null, null, Set.of(10L, 20L), 0, 10);
assertThat(result.getContent()).hasSize(2);
verify(bookOpdsRepository).findBookIdsByShelfIds(eq(Set.of(10L, 20L)), any());
}
@Test
void getBooksPage_withShelfIdAndQuery_searchesInShelf() {
OpdsUserDetails details = v2UserDetails(1L, false, Set.of(1L));
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
var permissionsEntity = mock(com.adityachandel.booklore.model.entity.UserPermissionsEntity.class);
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
when(user.getPermissions()).thenReturn(perms);
when(perms.isAdmin()).thenReturn(false);
when(perms.isCanAccessOpds()).thenReturn(true);
when(user.getId()).thenReturn(1L);
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(1L).watch(false).build()));
ShelfEntity shelf = mock(ShelfEntity.class);
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(1L);
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
BookEntity bookEntity = mock(BookEntity.class);
when(bookEntity.getId()).thenReturn(1L);
Book book = Book.builder().id(1L).build();
when(bookMapper.toBook(bookEntity)).thenReturn(book);
when(bookOpdsRepository.findBookIdsByMetadataSearchAndShelfIds(eq("test"), eq(Set.of(10L)), any())).thenReturn(new PageImpl<>(List.of(1L)));
when(bookOpdsRepository.findAllWithFullMetadataByIdsAndShelfIds(eq(List.of(1L)), eq(Set.of(10L)))).thenReturn(List.of(bookEntity));
Page<Book> result = opdsBookService.getBooksPage(1L, "test", null, Set.of(10L), 0, 10);
assertThat(result.getContent()).hasSize(1);
verify(bookOpdsRepository).findBookIdsByMetadataSearchAndShelfIds(eq("test"), eq(Set.of(10L)), any());
}
@Test
void getBooksPage_withShelfId_throwsForbidden_whenNotOwner() {
OpdsUserDetails details = v2UserDetails(1L, false, Set.of(1L));
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
var permissionsEntity = mock(com.adityachandel.booklore.model.entity.UserPermissionsEntity.class);
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
when(user.getPermissions()).thenReturn(perms);
when(perms.isAdmin()).thenReturn(false);
when(perms.isCanAccessOpds()).thenReturn(true);
when(user.getId()).thenReturn(1L);
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(1L).watch(false).build()));
ShelfEntity shelf = mock(ShelfEntity.class);
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(999L); // Different user
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
assertThatThrownBy(() ->
opdsBookService.getBooksPage(1L, null, null, Set.of(10L), 0, 10)
).hasMessageContaining("You are not allowed to access this shelf");
}
@Test
void getBooksPage_withShelfId_allowsAdmin_evenIfNotOwner() {
OpdsUserDetails details = v2UserDetails(1L, true, Set.of(1L));
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
var permissionsEntity = mock(com.adityachandel.booklore.model.entity.UserPermissionsEntity.class);
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
when(permissionsEntity.isPermissionAdmin()).thenReturn(true);
when(entity.getPermissions()).thenReturn(permissionsEntity);
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
BookLoreUser user = mock(BookLoreUser.class);
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
when(user.getPermissions()).thenReturn(perms);
when(perms.isAdmin()).thenReturn(true);
when(perms.isCanAccessOpds()).thenReturn(true);
when(user.getId()).thenReturn(1L);
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(1L).watch(false).build()));
ShelfEntity shelf = mock(ShelfEntity.class);
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
when(shelfUser.getId()).thenReturn(999L); // Different user, but admin
when(shelf.getUser()).thenReturn(shelfUser);
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
when(bookOpdsRepository.findBookIdsByShelfIds(eq(Set.of(10L)), any())).thenReturn(Page.empty());
Page<Book> result = opdsBookService.getBooksPage(1L, null, null, Set.of(10L), 0, 10);
assertThat(result).isNotNull();
verify(bookOpdsRepository).findBookIdsByShelfIds(eq(Set.of(10L)), any());
}
}
@@ -311,4 +311,168 @@ class OpdsFeedServiceTest {
assertThat(userId).isNull();
}
@Test
void parseShelfIds_shouldParseSingleShelfId() throws Exception {
when(request.getParameter("shelfId")).thenReturn("10");
when(request.getParameter("shelfIds")).thenReturn(null);
var method = OpdsFeedService.class.getDeclaredMethod("parseShelfIds", HttpServletRequest.class);
method.setAccessible(true);
Set<Long> result = (Set<Long>) method.invoke(opdsFeedService, request);
assertThat(result).containsExactly(10L);
}
@Test
void parseShelfIds_shouldParseCommaSeparatedShelfIds() throws Exception {
when(request.getParameter("shelfId")).thenReturn(null);
when(request.getParameter("shelfIds")).thenReturn("10,20,30");
var method = OpdsFeedService.class.getDeclaredMethod("parseShelfIds", HttpServletRequest.class);
method.setAccessible(true);
Set<Long> result = (Set<Long>) method.invoke(opdsFeedService, request);
assertThat(result).containsExactlyInAnyOrder(10L, 20L, 30L);
}
@Test
void parseShelfIds_shouldCombineShelfIdAndShelfIds() throws Exception {
when(request.getParameter("shelfId")).thenReturn("5");
when(request.getParameter("shelfIds")).thenReturn("10,20");
var method = OpdsFeedService.class.getDeclaredMethod("parseShelfIds", HttpServletRequest.class);
method.setAccessible(true);
Set<Long> result = (Set<Long>) method.invoke(opdsFeedService, request);
assertThat(result).containsExactlyInAnyOrder(5L, 10L, 20L);
}
@Test
void parseShelfIds_shouldReturnNullWhenNoShelfIds() throws Exception {
when(request.getParameter("shelfId")).thenReturn(null);
when(request.getParameter("shelfIds")).thenReturn(null);
var method = OpdsFeedService.class.getDeclaredMethod("parseShelfIds", HttpServletRequest.class);
method.setAccessible(true);
Set<Long> result = (Set<Long>) method.invoke(opdsFeedService, request);
assertThat(result).isNull();
}
@Test
void parseShelfIds_shouldHandleInvalidIds() throws Exception {
when(request.getParameter("shelfId")).thenReturn("invalid");
when(request.getParameter("shelfIds")).thenReturn("10,abc,20");
var method = OpdsFeedService.class.getDeclaredMethod("parseShelfIds", HttpServletRequest.class);
method.setAccessible(true);
Set<Long> result = (Set<Long>) method.invoke(opdsFeedService, request);
// Should only parse valid IDs
assertThat(result).containsExactlyInAnyOrder(10L, 20L);
}
@Test
void generateCatalogFeed_withSingleShelfId_shouldFilterByShelf() {
mockAuthenticatedUser();
when(request.getParameter("libraryId")).thenReturn(null);
when(request.getParameter("shelfId")).thenReturn("10");
when(request.getParameter("shelfIds")).thenReturn(null);
when(request.getParameter("magicShelfId")).thenReturn(null);
when(request.getParameter("q")).thenReturn(null);
when(request.getParameter("author")).thenReturn(null);
when(request.getParameter("series")).thenReturn(null);
when(request.getParameter("page")).thenReturn(null);
when(request.getParameter("size")).thenReturn(null);
when(request.getRequestURI()).thenReturn("/api/v1/opds/catalog");
when(request.getQueryString()).thenReturn("shelfId=10");
Book book = Book.builder()
.id(1L)
.bookType(BookFileType.EPUB)
.addedOn(FIXED_INSTANT)
.metadata(BookMetadata.builder().title("Shelf Book").build())
.build();
Page<Book> page = new PageImpl<>(List.of(book), PageRequest.of(0, 50), 1);
when(opdsBookService.getBooksPage(eq(TEST_USER_ID), isNull(), isNull(), eq(Set.of(10L)), eq(0), eq(50))).thenReturn(page);
when(opdsBookService.applySortOrder(any(), any())).thenReturn(page);
when(opdsBookService.getShelfName(10L)).thenReturn("My Shelf - Shelf");
String xml = opdsFeedService.generateCatalogFeed(request);
assertThat(xml).contains("Shelf Book");
assertThat(xml).contains("My Shelf - Shelf");
assertThat(xml).contains("</feed>");
verify(opdsBookService).getBooksPage(TEST_USER_ID, null, null, Set.of(10L), 0, 50);
}
@Test
void generateCatalogFeed_withMultipleShelfIds_shouldFilterByMultipleShelves() {
mockAuthenticatedUser();
when(request.getParameter("libraryId")).thenReturn(null);
when(request.getParameter("shelfId")).thenReturn(null);
when(request.getParameter("shelfIds")).thenReturn("10,20");
when(request.getParameter("magicShelfId")).thenReturn(null);
when(request.getParameter("q")).thenReturn(null);
when(request.getParameter("author")).thenReturn(null);
when(request.getParameter("series")).thenReturn(null);
when(request.getParameter("page")).thenReturn(null);
when(request.getParameter("size")).thenReturn(null);
when(request.getRequestURI()).thenReturn("/api/v1/opds/catalog");
when(request.getQueryString()).thenReturn("shelfIds=10,20");
Book book = Book.builder()
.id(1L)
.bookType(BookFileType.EPUB)
.addedOn(FIXED_INSTANT)
.metadata(BookMetadata.builder().title("Multi Shelf Book").build())
.build();
Page<Book> page = new PageImpl<>(List.of(book), PageRequest.of(0, 50), 1);
when(opdsBookService.getBooksPage(eq(TEST_USER_ID), isNull(), isNull(), eq(Set.of(10L, 20L)), eq(0), eq(50))).thenReturn(page);
when(opdsBookService.applySortOrder(any(), any())).thenReturn(page);
String xml = opdsFeedService.generateCatalogFeed(request);
assertThat(xml).contains("Multi Shelf Book");
assertThat(xml).contains("Multiple Shelves");
assertThat(xml).contains("</feed>");
verify(opdsBookService).getBooksPage(TEST_USER_ID, null, null, Set.of(10L, 20L), 0, 50);
}
@Test
void generateCatalogFeed_withShelfIdAndQuery_shouldSearchInShelf() {
mockAuthenticatedUser();
when(request.getParameter("libraryId")).thenReturn(null);
when(request.getParameter("shelfId")).thenReturn("10");
when(request.getParameter("shelfIds")).thenReturn(null);
when(request.getParameter("magicShelfId")).thenReturn(null);
when(request.getParameter("q")).thenReturn("fantasy");
when(request.getParameter("author")).thenReturn(null);
when(request.getParameter("series")).thenReturn(null);
when(request.getParameter("page")).thenReturn(null);
when(request.getParameter("size")).thenReturn(null);
when(request.getRequestURI()).thenReturn("/api/v1/opds/catalog");
when(request.getQueryString()).thenReturn("shelfId=10&q=fantasy");
Book book = Book.builder()
.id(1L)
.bookType(BookFileType.EPUB)
.addedOn(FIXED_INSTANT)
.metadata(BookMetadata.builder().title("Fantasy Book").build())
.build();
Page<Book> page = new PageImpl<>(List.of(book), PageRequest.of(0, 50), 1);
when(opdsBookService.getBooksPage(eq(TEST_USER_ID), eq("fantasy"), isNull(), eq(Set.of(10L)), eq(0), eq(50))).thenReturn(page);
when(opdsBookService.applySortOrder(any(), any())).thenReturn(page);
when(opdsBookService.getShelfName(10L)).thenReturn("Fantasy Shelf - Shelf");
String xml = opdsFeedService.generateCatalogFeed(request);
assertThat(xml).contains("Fantasy Book");
assertThat(xml).contains("</feed>");
verify(opdsBookService).getBooksPage(TEST_USER_ID, "fantasy", null, Set.of(10L), 0, 50);
}
}