feat(mobile): scope filter options to library, shelf, or magic shelf (#2838)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-02-21 12:32:44 -07:00
committed by GitHub
co-authored by acx10
parent b28fa3c994
commit ead04b3f1a
4 changed files with 466 additions and 39 deletions
@@ -9,6 +9,7 @@ import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@AllArgsConstructor
@@ -23,7 +24,10 @@ public class MobileFilterController {
description = "Returns available authors, languages, file types, and read statuses for filtering books.")
@ApiResponse(responseCode = "200", description = "Filter options retrieved successfully")
@GetMapping("/filter-options")
public ResponseEntity<MobileFilterOptions> getFilterOptions() {
return ResponseEntity.ok(mobileBookService.getFilterOptions());
public ResponseEntity<MobileFilterOptions> getFilterOptions(
@RequestParam(required = false) Long libraryId,
@RequestParam(required = false) Long shelfId,
@RequestParam(required = false) Long magicShelfId) {
return ResponseEntity.ok(mobileBookService.getFilterOptions(libraryId, shelfId, magicShelfId));
}
}
@@ -305,26 +305,68 @@ public class MobileBookService {
}
@Transactional(readOnly = true)
public MobileFilterOptions getFilterOptions() {
public MobileFilterOptions getFilterOptions(Long libraryId, Long shelfId, Long magicShelfId) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
// Base filter: non-deleted digital books in accessible libraries
String libraryClause = accessibleLibraryIds != null
? "AND b.library.id IN :libraryIds"
: "";
// Resolve magic shelf to a set of book IDs if requested
Set<Long> magicBookIds = null;
if (magicShelfId != null) {
magicBookIds = resolveMagicShelfBookIds(magicShelfId, userId);
if (magicBookIds.isEmpty()) {
return MobileFilterOptions.builder()
.authors(Collections.emptyList())
.languages(Collections.emptyList())
.fileTypes(Collections.emptyList())
.readStatuses(getReadStatusOptions())
.build();
}
}
// Validate library access
if (libraryId != null && accessibleLibraryIds != null && !accessibleLibraryIds.contains(libraryId)) {
throw ApiError.FORBIDDEN.createException("Access denied to library " + libraryId);
}
// Validate shelf access
if (shelfId != null) {
ShelfEntity shelf = shelfRepository.findById(shelfId)
.orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
if (!shelf.isPublic() && !shelf.getUser().getId().equals(userId)) {
throw ApiError.FORBIDDEN.createException("Access denied to shelf " + shelfId);
}
}
// Build scoping clauses
String libraryClause = "";
String shelfClause = "";
String magicBookClause = "";
if (magicBookIds != null) {
magicBookClause = "AND b.id IN :magicBookIds";
} else if (shelfId != null) {
shelfClause = "AND b.id IN (SELECT sb.id FROM ShelfEntity s JOIN s.books sb WHERE s.id = :shelfId)";
}
if (libraryId != null) {
libraryClause = "AND b.library.id = :libraryId";
} else if (accessibleLibraryIds != null) {
libraryClause = "AND b.library.id IN :libraryIds";
}
// Build the optional WHERE suffix once — each clause already starts with "AND"
String scopeClause = buildScopeClause(libraryClause, shelfClause, magicBookClause);
// Authors with book count (top 200 by count)
String authorQuery = """
SELECT a.name, COUNT(DISTINCT b.id) FROM BookEntity b
JOIN b.metadata m JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false)
AND (b.isPhysical IS NULL OR b.isPhysical = false)
""" + libraryClause + """
GROUP BY a.name ORDER BY COUNT(DISTINCT b.id) DESC
""";
String authorQuery = "SELECT a.name, COUNT(DISTINCT b.id) FROM BookEntity b"
+ " JOIN b.metadata m JOIN m.authors a"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
+ scopeClause
+ " GROUP BY a.name ORDER BY COUNT(DISTINCT b.id) DESC";
var authorQ = entityManager.createQuery(authorQuery, Tuple.class);
if (accessibleLibraryIds != null) authorQ.setParameter("libraryIds", accessibleLibraryIds);
setFilterQueryParams(authorQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
authorQ.setMaxResults(200);
List<MobileFilterOptions.AuthorOption> authors = authorQ.getResultList().stream()
@@ -335,17 +377,15 @@ public class MobileBookService {
.toList();
// Languages with book count
String langQuery = """
SELECT m.language, COUNT(DISTINCT b.id) FROM BookEntity b
JOIN b.metadata m
WHERE (b.deleted IS NULL OR b.deleted = false)
AND (b.isPhysical IS NULL OR b.isPhysical = false)
AND m.language IS NOT NULL AND m.language <> ''
""" + libraryClause + """
GROUP BY m.language ORDER BY COUNT(DISTINCT b.id) DESC
""";
String langQuery = "SELECT m.language, COUNT(DISTINCT b.id) FROM BookEntity b"
+ " JOIN b.metadata m"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
+ " AND m.language IS NOT NULL AND m.language <> ''"
+ scopeClause
+ " GROUP BY m.language ORDER BY COUNT(DISTINCT b.id) DESC";
var langQ = entityManager.createQuery(langQuery, Tuple.class);
if (accessibleLibraryIds != null) langQ.setParameter("libraryIds", accessibleLibraryIds);
setFilterQueryParams(langQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<MobileFilterOptions.LanguageOption> languages = langQ.getResultList().stream()
.map(t -> MobileFilterOptions.LanguageOption.builder()
@@ -355,16 +395,15 @@ public class MobileBookService {
.build())
.toList();
// Distinct file types present in accessible books
String fileTypeQuery = """
SELECT DISTINCT bf.bookType FROM BookEntity b
JOIN b.bookFiles bf
WHERE (b.deleted IS NULL OR b.deleted = false)
AND (b.isPhysical IS NULL OR b.isPhysical = false)
AND bf.isBookFormat = true
""" + libraryClause;
// Distinct file types present in scoped books
String fileTypeQuery = "SELECT DISTINCT bf.bookType FROM BookEntity b"
+ " JOIN b.bookFiles bf"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
+ " AND bf.isBookFormat = true"
+ scopeClause;
var ftQ = entityManager.createQuery(fileTypeQuery, BookFileType.class);
if (accessibleLibraryIds != null) ftQ.setParameter("libraryIds", accessibleLibraryIds);
setFilterQueryParams(ftQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<String> fileTypes = ftQ.getResultList().stream()
.map(Enum::name)
@@ -372,10 +411,7 @@ public class MobileBookService {
.toList();
// Read statuses — return all meaningful values
List<String> readStatuses = Arrays.stream(ReadStatus.values())
.filter(s -> s != ReadStatus.UNSET)
.map(Enum::name)
.toList();
List<String> readStatuses = getReadStatusOptions();
return MobileFilterOptions.builder()
.authors(authors)
@@ -385,6 +421,44 @@ public class MobileBookService {
.build();
}
private String buildScopeClause(String libraryClause, String shelfClause, String magicBookClause) {
var sb = new StringBuilder();
if (!libraryClause.isEmpty()) sb.append(" ").append(libraryClause);
if (!shelfClause.isEmpty()) sb.append(" ").append(shelfClause);
if (!magicBookClause.isEmpty()) sb.append(" ").append(magicBookClause);
return sb.toString();
}
private void setFilterQueryParams(jakarta.persistence.Query query, Set<Long> accessibleLibraryIds, Long libraryId, Long shelfId, Set<Long> magicBookIds) {
if (libraryId != null) {
query.setParameter("libraryId", libraryId);
} else if (accessibleLibraryIds != null) {
query.setParameter("libraryIds", accessibleLibraryIds);
}
if (shelfId != null && magicBookIds == null) {
query.setParameter("shelfId", shelfId);
}
if (magicBookIds != null) {
query.setParameter("magicBookIds", magicBookIds);
}
}
private Set<Long> resolveMagicShelfBookIds(Long magicShelfId, Long userId) {
// Reuse MagicShelfBookService which already handles access validation,
// rule evaluation, and library filtering.
var booksPage = magicShelfBookService.getBooksByMagicShelfId(userId, magicShelfId, 0, 10000);
return booksPage.getContent().stream()
.map(Book::getId)
.collect(Collectors.toSet());
}
private List<String> getReadStatusOptions() {
return Arrays.stream(ReadStatus.values())
.filter(s -> s != ReadStatus.UNSET)
.map(Enum::name)
.toList();
}
@Transactional
public void updateReadStatus(Long bookId, ReadStatus status) {
UserBookProgressEntity progress = validateAccessAndGetProgress(bookId);
@@ -0,0 +1,89 @@
package org.booklore.mobile.controller;
import org.booklore.mobile.dto.MobileFilterOptions;
import org.booklore.mobile.service.MobileBookService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.ResponseEntity;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class MobileFilterControllerTest {
@Mock
private MobileBookService mobileBookService;
@InjectMocks
private MobileFilterController controller;
@Test
void getFilterOptions_noParams_delegatesWithNulls() {
MobileFilterOptions expected = buildOptions(List.of("Author A"), List.of("EPUB"), List.of("en"));
when(mobileBookService.getFilterOptions(null, null, null)).thenReturn(expected);
ResponseEntity<MobileFilterOptions> response = controller.getFilterOptions(null, null, null);
assertEquals(200, response.getStatusCode().value());
assertSame(expected, response.getBody());
verify(mobileBookService).getFilterOptions(null, null, null);
}
@Test
void getFilterOptions_withLibraryId_passesLibraryId() {
MobileFilterOptions expected = buildOptions(List.of("Author B"), List.of("PDF"), List.of("fr"));
when(mobileBookService.getFilterOptions(5L, null, null)).thenReturn(expected);
ResponseEntity<MobileFilterOptions> response = controller.getFilterOptions(5L, null, null);
assertEquals(200, response.getStatusCode().value());
assertEquals(1, response.getBody().getAuthors().size());
assertEquals("Author B", response.getBody().getAuthors().getFirst().getName());
verify(mobileBookService).getFilterOptions(5L, null, null);
}
@Test
void getFilterOptions_withShelfId_passesShelfId() {
MobileFilterOptions expected = buildOptions(List.of(), List.of("EPUB"), List.of());
when(mobileBookService.getFilterOptions(null, 10L, null)).thenReturn(expected);
ResponseEntity<MobileFilterOptions> response = controller.getFilterOptions(null, 10L, null);
assertEquals(200, response.getStatusCode().value());
assertTrue(response.getBody().getAuthors().isEmpty());
verify(mobileBookService).getFilterOptions(null, 10L, null);
}
@Test
void getFilterOptions_withMagicShelfId_passesMagicShelfId() {
MobileFilterOptions expected = buildOptions(List.of("Author C"), List.of("MOBI"), List.of("de"));
when(mobileBookService.getFilterOptions(null, null, 7L)).thenReturn(expected);
ResponseEntity<MobileFilterOptions> response = controller.getFilterOptions(null, null, 7L);
assertEquals(200, response.getStatusCode().value());
assertEquals("Author C", response.getBody().getAuthors().getFirst().getName());
verify(mobileBookService).getFilterOptions(null, null, 7L);
}
private MobileFilterOptions buildOptions(List<String> authorNames, List<String> fileTypes, List<String> langCodes) {
List<MobileFilterOptions.AuthorOption> authors = authorNames.stream()
.map(name -> MobileFilterOptions.AuthorOption.builder().name(name).count(1L).build())
.toList();
List<MobileFilterOptions.LanguageOption> languages = langCodes.stream()
.map(code -> MobileFilterOptions.LanguageOption.builder().code(code).label(code).count(1L).build())
.toList();
return MobileFilterOptions.builder()
.authors(authors)
.languages(languages)
.fileTypes(fileTypes)
.readStatuses(List.of("READ", "READING", "UNREAD"))
.build();
}
}
@@ -0,0 +1,260 @@
package org.booklore.mobile.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.mobile.dto.MobileFilterOptions;
import org.booklore.mobile.mapper.MobileBookMapper;
import org.booklore.model.dto.Book;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.ShelfEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookRepository;
import org.booklore.repository.ShelfRepository;
import org.booklore.repository.UserBookFileProgressRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.booklore.service.opds.MagicShelfBookService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class MobileBookServiceFilterOptionsTest {
@Mock private BookRepository bookRepository;
@Mock private UserBookProgressRepository userBookProgressRepository;
@Mock private UserBookFileProgressRepository userBookFileProgressRepository;
@Mock private ShelfRepository shelfRepository;
@Mock private AuthenticationService authenticationService;
@Mock private MobileBookMapper mobileBookMapper;
@Mock private MagicShelfBookService magicShelfBookService;
@Mock private EntityManager entityManager;
private MobileBookService service;
private final Long userId = 1L;
@BeforeEach
void setUp() {
service = new MobileBookService(
bookRepository, userBookProgressRepository, userBookFileProgressRepository,
shelfRepository, authenticationService, mobileBookMapper,
magicShelfBookService, entityManager
);
}
// -------------------------------------------------------------------------
// Global (no scoping params)
// -------------------------------------------------------------------------
@Test
void getFilterOptions_noParams_returnsGlobalOptions() {
mockAdminUser();
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(null, null, null);
assertNotNull(result);
assertNotNull(result.getAuthors());
assertNotNull(result.getLanguages());
assertNotNull(result.getFileTypes());
assertFalse(result.getReadStatuses().isEmpty());
}
// -------------------------------------------------------------------------
// Library scoping
// -------------------------------------------------------------------------
@Test
void getFilterOptions_withLibraryId_admin_succeeds() {
mockAdminUser();
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(5L, null, null);
assertNotNull(result);
verify(entityManager, times(3)).createQuery(anyString(), any(Class.class));
}
@Test
void getFilterOptions_withLibraryId_nonAdminWithAccess_succeeds() {
mockNonAdminUser(Set.of(5L, 10L));
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(5L, null, null);
assertNotNull(result);
}
@Test
void getFilterOptions_withLibraryId_nonAdminNoAccess_throwsForbidden() {
mockNonAdminUser(Set.of(10L));
assertThrows(APIException.class, () -> service.getFilterOptions(5L, null, null));
}
// -------------------------------------------------------------------------
// Shelf scoping
// -------------------------------------------------------------------------
@Test
void getFilterOptions_withShelfId_publicShelf_succeeds() {
mockAdminUser();
ShelfEntity shelf = ShelfEntity.builder().id(10L).isPublic(true)
.user(BookLoreUserEntity.builder().id(99L).build()).build();
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(null, 10L, null);
assertNotNull(result);
}
@Test
void getFilterOptions_withShelfId_ownPrivateShelf_succeeds() {
mockAdminUser();
ShelfEntity shelf = ShelfEntity.builder().id(10L).isPublic(false)
.user(BookLoreUserEntity.builder().id(userId).build()).build();
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(null, 10L, null);
assertNotNull(result);
}
@Test
void getFilterOptions_withShelfId_otherPrivateShelf_throwsForbidden() {
mockAdminUser();
ShelfEntity shelf = ShelfEntity.builder().id(10L).isPublic(false)
.user(BookLoreUserEntity.builder().id(99L).build()).build();
when(shelfRepository.findById(10L)).thenReturn(Optional.of(shelf));
assertThrows(APIException.class, () -> service.getFilterOptions(null, 10L, null));
}
@Test
void getFilterOptions_withShelfId_notFound_throwsException() {
mockAdminUser();
when(shelfRepository.findById(10L)).thenReturn(Optional.empty());
assertThrows(APIException.class, () -> service.getFilterOptions(null, 10L, null));
}
// -------------------------------------------------------------------------
// Magic shelf scoping
// -------------------------------------------------------------------------
@Test
void getFilterOptions_withMagicShelfId_emptyResult_returnsEmptyOptions() {
mockAdminUser();
mockMagicShelfBooks(7L, Collections.emptyList());
MobileFilterOptions result = service.getFilterOptions(null, null, 7L);
assertNotNull(result);
assertTrue(result.getAuthors().isEmpty());
assertTrue(result.getLanguages().isEmpty());
assertTrue(result.getFileTypes().isEmpty());
assertFalse(result.getReadStatuses().isEmpty());
}
@Test
void getFilterOptions_withMagicShelfId_withBooks_returnsFilteredOptions() {
mockAdminUser();
Book book1 = Book.builder().id(100L).build();
Book book2 = Book.builder().id(200L).build();
mockMagicShelfBooks(7L, List.of(book1, book2));
mockJpqlQueries();
MobileFilterOptions result = service.getFilterOptions(null, null, 7L);
assertNotNull(result);
verify(magicShelfBookService).getBooksByMagicShelfId(eq(userId), eq(7L), eq(0), anyInt());
}
@Test
void getFilterOptions_withMagicShelfId_serviceThrows_propagatesException() {
mockAdminUser();
when(magicShelfBookService.getBooksByMagicShelfId(eq(userId), eq(7L), eq(0), anyInt()))
.thenThrow(new RuntimeException("Magic shelf not found"));
assertThrows(RuntimeException.class, () -> service.getFilterOptions(null, null, 7L));
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
private void mockAdminUser() {
var permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(true);
BookLoreUser user = BookLoreUser.builder()
.id(userId)
.permissions(permissions)
.build();
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
}
private void mockNonAdminUser(Set<Long> libraryIds) {
List<Library> assignedLibraries = libraryIds.stream()
.map(id -> Library.builder().id(id).build())
.toList();
var permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(false);
BookLoreUser user = BookLoreUser.builder()
.id(userId)
.permissions(permissions)
.assignedLibraries(assignedLibraries)
.build();
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
}
private void mockMagicShelfBooks(Long magicShelfId, List<Book> books) {
var page = new PageImpl<>(books, PageRequest.of(0, Math.max(books.size(), 1)), books.size());
when(magicShelfBookService.getBooksByMagicShelfId(eq(userId), eq(magicShelfId), eq(0), anyInt()))
.thenReturn(page);
}
@SuppressWarnings("unchecked")
private void mockJpqlQueries() {
TypedQuery<Tuple> authorQuery = mock(TypedQuery.class);
when(authorQuery.setMaxResults(anyInt())).thenReturn(authorQuery);
when(authorQuery.setParameter(anyString(), any())).thenReturn(authorQuery);
when(authorQuery.getResultList()).thenReturn(Collections.emptyList());
TypedQuery<Tuple> langQuery = mock(TypedQuery.class);
when(langQuery.setParameter(anyString(), any())).thenReturn(langQuery);
when(langQuery.getResultList()).thenReturn(Collections.emptyList());
TypedQuery<BookFileType> ftQuery = mock(TypedQuery.class);
when(ftQuery.setParameter(anyString(), any())).thenReturn(ftQuery);
when(ftQuery.getResultList()).thenReturn(Collections.emptyList());
when(entityManager.createQuery(anyString(), eq(Tuple.class)))
.thenReturn(authorQuery)
.thenReturn(langQuery);
when(entityManager.createQuery(anyString(), eq(BookFileType.class)))
.thenReturn(ftQuery);
}
}