diff --git a/booklore-api/src/main/java/org/booklore/mobile/controller/MobileBookController.java b/booklore-api/src/main/java/org/booklore/mobile/controller/MobileBookController.java index 65229f008..d6011e7f4 100644 --- a/booklore-api/src/main/java/org/booklore/mobile/controller/MobileBookController.java +++ b/booklore-api/src/main/java/org/booklore/mobile/controller/MobileBookController.java @@ -2,6 +2,7 @@ package org.booklore.mobile.controller; import org.booklore.mobile.dto.*; import org.booklore.mobile.service.MobileBookService; +import org.booklore.model.enums.BookFileType; import org.booklore.model.enums.ReadStatus; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -38,10 +39,16 @@ public class MobileBookController { @Parameter(description = "Filter by library ID") @RequestParam(required = false) Long libraryId, @Parameter(description = "Filter by shelf ID") @RequestParam(required = false) Long shelfId, @Parameter(description = "Filter by read status") @RequestParam(required = false) ReadStatus status, - @Parameter(description = "Search in title, author, series") @RequestParam(required = false) String search) { + @Parameter(description = "Search in title, author, series") @RequestParam(required = false) String search, + @Parameter(description = "Filter by file type (EBOOK, AUDIOBOOK, PDF, CBX, etc.)") @RequestParam(required = false) BookFileType fileType, + @Parameter(description = "Minimum personal rating (1-5)") @RequestParam(required = false) Integer minRating, + @Parameter(description = "Maximum personal rating (1-5, 0 for unrated)") @RequestParam(required = false) Integer maxRating, + @Parameter(description = "Filter by author name") @RequestParam(required = false) String authors, + @Parameter(description = "Filter by language code (e.g. en, fr)") @RequestParam(required = false) String language) { return ResponseEntity.ok(mobileBookService.getBooks( - page, size, sort, dir, libraryId, shelfId, status, search)); + page, size, sort, dir, libraryId, shelfId, status, search, + fileType, minRating, maxRating, authors, language)); } @Operation(summary = "Get book details", diff --git a/booklore-api/src/main/java/org/booklore/mobile/controller/MobileFilterController.java b/booklore-api/src/main/java/org/booklore/mobile/controller/MobileFilterController.java new file mode 100644 index 000000000..0ec1b57b3 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/mobile/controller/MobileFilterController.java @@ -0,0 +1,29 @@ +package org.booklore.mobile.controller; + +import org.booklore.mobile.dto.MobileFilterOptions; +import org.booklore.mobile.service.MobileBookService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +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.RestController; + +@AllArgsConstructor +@RestController +@RequestMapping("/api/mobile/v1") +@Tag(name = "Mobile Filters", description = "Filter options for mobile book browsing") +public class MobileFilterController { + + private final MobileBookService mobileBookService; + + @Operation(summary = "Get available filter options", + 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 getFilterOptions() { + return ResponseEntity.ok(mobileBookService.getFilterOptions()); + } +} diff --git a/booklore-api/src/main/java/org/booklore/mobile/dto/MobileFilterOptions.java b/booklore-api/src/main/java/org/booklore/mobile/dto/MobileFilterOptions.java new file mode 100644 index 000000000..cf62f33a4 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/mobile/dto/MobileFilterOptions.java @@ -0,0 +1,40 @@ +package org.booklore.mobile.dto; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class MobileFilterOptions { + private List authors; + private List languages; + private List readStatuses; + private List fileTypes; + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class AuthorOption { + private String name; + private long count; + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class LanguageOption { + private String code; + private String label; + private long count; + } +} diff --git a/booklore-api/src/main/java/org/booklore/mobile/service/MobileBookService.java b/booklore-api/src/main/java/org/booklore/mobile/service/MobileBookService.java index 6a14c19f5..68fee1b5d 100644 --- a/booklore-api/src/main/java/org/booklore/mobile/service/MobileBookService.java +++ b/booklore-api/src/main/java/org/booklore/mobile/service/MobileBookService.java @@ -4,6 +4,7 @@ import org.booklore.config.security.service.AuthenticationService; import org.booklore.exception.ApiError; import org.booklore.mobile.dto.MobileBookDetail; import org.booklore.mobile.dto.MobileBookSummary; +import org.booklore.mobile.dto.MobileFilterOptions; import org.booklore.mobile.dto.MobilePageResponse; import org.booklore.mobile.mapper.MobileBookMapper; import org.booklore.mobile.specification.MobileBookSpecification; @@ -11,6 +12,7 @@ import org.booklore.model.dto.Book; import org.booklore.model.dto.BookLoreUser; import org.booklore.model.dto.Library; import org.booklore.model.entity.*; +import org.booklore.model.enums.BookFileType; import org.booklore.model.enums.ReadStatus; import org.booklore.repository.BookRepository; import org.booklore.repository.ShelfRepository; @@ -26,6 +28,8 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import jakarta.persistence.EntityManager; +import jakarta.persistence.Tuple; import java.time.Instant; import java.util.*; import java.util.function.Function; @@ -45,6 +49,7 @@ public class MobileBookService { private final AuthenticationService authenticationService; private final MobileBookMapper mobileBookMapper; private final MagicShelfBookService magicShelfBookService; + private final EntityManager entityManager; @Transactional(readOnly = true) public MobilePageResponse getBooks( @@ -55,7 +60,12 @@ public class MobileBookService { Long libraryId, Long shelfId, ReadStatus status, - String search) { + String search, + BookFileType fileType, + Integer minRating, + Integer maxRating, + String authors, + String language) { BookLoreUser user = authenticationService.getAuthenticatedUser(); Long userId = user.getId(); @@ -68,7 +78,8 @@ public class MobileBookService { Pageable pageable = PageRequest.of(pageNum, pageSize, sort); Specification spec = buildSpecification( - accessibleLibraryIds, libraryId, shelfId, status, search, userId); + accessibleLibraryIds, libraryId, shelfId, status, search, userId, + fileType, minRating, maxRating, authors, language); Page bookPage = bookRepository.findAll(spec, pageable); @@ -293,6 +304,87 @@ public class MobileBookService { return MobilePageResponse.of(summaries, pageNum, pageSize, booksPage.getTotalElements()); } + @Transactional(readOnly = true) + public MobileFilterOptions getFilterOptions() { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + Set accessibleLibraryIds = getAccessibleLibraryIds(user); + + // Base filter: non-deleted digital books in accessible libraries + String libraryClause = accessibleLibraryIds != null + ? "AND b.library.id IN :libraryIds" + : ""; + + // 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 + """; + var authorQ = entityManager.createQuery(authorQuery, Tuple.class); + if (accessibleLibraryIds != null) authorQ.setParameter("libraryIds", accessibleLibraryIds); + authorQ.setMaxResults(200); + + List authors = authorQ.getResultList().stream() + .map(t -> MobileFilterOptions.AuthorOption.builder() + .name(t.get(0, String.class)) + .count(t.get(1, Long.class)) + .build()) + .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 + """; + var langQ = entityManager.createQuery(langQuery, Tuple.class); + if (accessibleLibraryIds != null) langQ.setParameter("libraryIds", accessibleLibraryIds); + + List languages = langQ.getResultList().stream() + .map(t -> MobileFilterOptions.LanguageOption.builder() + .code(t.get(0, String.class)) + .label(Locale.forLanguageTag(t.get(0, String.class)).getDisplayLanguage(Locale.ENGLISH)) + .count(t.get(1, Long.class)) + .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; + var ftQ = entityManager.createQuery(fileTypeQuery, BookFileType.class); + if (accessibleLibraryIds != null) ftQ.setParameter("libraryIds", accessibleLibraryIds); + + List fileTypes = ftQ.getResultList().stream() + .map(Enum::name) + .sorted() + .toList(); + + // Read statuses — return all meaningful values + List readStatuses = Arrays.stream(ReadStatus.values()) + .filter(s -> s != ReadStatus.UNSET) + .map(Enum::name) + .toList(); + + return MobileFilterOptions.builder() + .authors(authors) + .languages(languages) + .fileTypes(fileTypes) + .readStatuses(readStatuses) + .build(); + } + @Transactional public void updateReadStatus(Long bookId, ReadStatus status) { UserBookProgressEntity progress = validateAccessAndGetProgress(bookId); @@ -372,7 +464,12 @@ public class MobileBookService { Long shelfId, ReadStatus status, String search, - Long userId) { + Long userId, + BookFileType fileType, + Integer minRating, + Integer maxRating, + String authors, + String language) { List> specs = new ArrayList<>(); specs.add(MobileBookSpecification.notDeleted()); @@ -407,6 +504,26 @@ public class MobileBookService { specs.add(MobileBookSpecification.searchText(search)); } + if (fileType != null) { + specs.add(MobileBookSpecification.withFileType(fileType)); + } + + if (minRating != null) { + specs.add(MobileBookSpecification.withMinRating(minRating, userId)); + } + + if (maxRating != null) { + specs.add(MobileBookSpecification.withMaxRating(maxRating, userId)); + } + + if (authors != null && !authors.trim().isEmpty()) { + specs.add(MobileBookSpecification.withAuthor(authors.trim())); + } + + if (language != null && !language.trim().isEmpty()) { + specs.add(MobileBookSpecification.withLanguage(language.trim())); + } + return MobileBookSpecification.combine(specs.toArray(new Specification[0])); } diff --git a/booklore-api/src/main/java/org/booklore/mobile/specification/MobileBookSpecification.java b/booklore-api/src/main/java/org/booklore/mobile/specification/MobileBookSpecification.java index 94e57ad03..b6fe0c7e2 100644 --- a/booklore-api/src/main/java/org/booklore/mobile/specification/MobileBookSpecification.java +++ b/booklore-api/src/main/java/org/booklore/mobile/specification/MobileBookSpecification.java @@ -139,6 +139,96 @@ public class MobileBookSpecification { }; } + /** + * Filter books that have at least one file of the given type. + */ + public static Specification withFileType(BookFileType fileType) { + return (root, query, cb) -> { + if (fileType == null) { + return cb.conjunction(); + } + Subquery subquery = query.subquery(Long.class); + Root bookFileRoot = subquery.from(BookFileEntity.class); + subquery.select(bookFileRoot.get("book").get("id")) + .where(cb.equal(bookFileRoot.get("bookType"), fileType)); + return root.get("id").in(subquery); + }; + } + + /** + * Filter books where the user's personal rating is >= minRating. + */ + public static Specification withMinRating(int minRating, Long userId) { + return (root, query, cb) -> { + Subquery subquery = query.subquery(Long.class); + Root progressRoot = subquery.from(UserBookProgressEntity.class); + subquery.select(progressRoot.get("book").get("id")) + .where( + cb.equal(progressRoot.get("user").get("id"), userId), + cb.greaterThanOrEqualTo(progressRoot.get("personalRating"), minRating) + ); + return root.get("id").in(subquery); + }; + } + + /** + * Filter books where the user's personal rating is <= maxRating. + * Use maxRating=0 to find unrated books. + */ + public static Specification withMaxRating(int maxRating, Long userId) { + return (root, query, cb) -> { + Subquery subquery = query.subquery(Long.class); + Root progressRoot = subquery.from(UserBookProgressEntity.class); + + if (maxRating == 0) { + // Unrated: books with no progress entry or null personalRating + Subquery ratedSubquery = query.subquery(Long.class); + Root ratedRoot = ratedSubquery.from(UserBookProgressEntity.class); + ratedSubquery.select(ratedRoot.get("book").get("id")) + .where( + cb.equal(ratedRoot.get("user").get("id"), userId), + cb.isNotNull(ratedRoot.get("personalRating")) + ); + return cb.not(root.get("id").in(ratedSubquery)); + } + + subquery.select(progressRoot.get("book").get("id")) + .where( + cb.equal(progressRoot.get("user").get("id"), userId), + cb.lessThanOrEqualTo(progressRoot.get("personalRating"), maxRating) + ); + return root.get("id").in(subquery); + }; + } + + /** + * Filter books by author name (case-insensitive exact match). + */ + public static Specification withAuthor(String authorName) { + return (root, query, cb) -> { + if (authorName == null || authorName.trim().isEmpty()) { + return cb.conjunction(); + } + Join metadataJoin = root.join("metadata", JoinType.LEFT); + Join authorsJoin = metadataJoin.join("authors", JoinType.LEFT); + query.distinct(true); + return cb.equal(cb.lower(authorsJoin.get("name")), authorName.toLowerCase().trim()); + }; + } + + /** + * Filter books by language code (case-insensitive). + */ + public static Specification withLanguage(String language) { + return (root, query, cb) -> { + if (language == null || language.trim().isEmpty()) { + return cb.conjunction(); + } + Join metadataJoin = root.join("metadata", JoinType.LEFT); + return cb.equal(cb.lower(metadataJoin.get("language")), language.toLowerCase().trim()); + }; + } + @SafeVarargs public static Specification combine(Specification... specs) { Specification result = (root, query, cb) -> cb.conjunction();