diff --git a/backend/src/main/java/org/booklore/app/specification/AppBookSpecification.java b/backend/src/main/java/org/booklore/app/specification/AppBookSpecification.java index ea18d99ad..474e17c3d 100644 --- a/backend/src/main/java/org/booklore/app/specification/AppBookSpecification.java +++ b/backend/src/main/java/org/booklore/app/specification/AppBookSpecification.java @@ -15,6 +15,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; +import java.util.function.Function; public class AppBookSpecification { @@ -61,6 +62,70 @@ public class AppBookSpecification { return result; } + private record NumericRange(T min, T max) { + } + + private static > List> parseNumericRanges(List values, Function parser, String paramName) { + List invalid = new ArrayList<>(); + List> ranges = new ArrayList<>(); + for (String value : values) { + if (value == null || value.isBlank()) { + continue; + } + NumericRange range = parseNumericRange(value.trim(), parser); + if (range == null) { + invalid.add(value.trim()); + } else { + ranges.add(range); + } + } + if (!invalid.isEmpty()) { + throw new APIException("Invalid " + paramName + " values: " + invalid + + ". Expected a number, min..max, min..*, or *..max. Minimum must not exceed maximum.", HttpStatus.BAD_REQUEST); + } + return ranges; + } + + private static > NumericRange parseNumericRange(String value, Function parser) { + try { + int separator = value.indexOf(".."); + if (separator < 0) { + T exact = parser.apply(value); + return new NumericRange<>(exact, exact); + } + String minPart = value.substring(0, separator).trim(); + String maxPart = value.substring(separator + 2).trim(); + if (minPart.equals("*") && maxPart.equals("*")) { + return null; + } + T min = minPart.equals("*") ? null : parser.apply(minPart); + T max = maxPart.equals("*") ? null : parser.apply(maxPart); + if (min != null && max != null && min.compareTo(max) > 0) { + return null; + } + return new NumericRange<>(min, max); + } catch (NumberFormatException e) { + return null; + } + } + + private static > Predicate rangesPredicate( + CriteriaBuilder cb, Expression field, List> ranges) { + List predicates = new ArrayList<>(); + for (NumericRange range : ranges) { + if (range.min() != null && range.max() != null) { + predicates.add(cb.and( + cb.greaterThanOrEqualTo(field, range.min()), + cb.lessThanOrEqualTo(field, range.max()))); + } else if (range.min() != null) { + predicates.add(cb.greaterThanOrEqualTo(field, range.min())); + } else { + predicates.add(cb.lessThanOrEqualTo(field, range.max())); + } + } + return cb.or(predicates.toArray(Predicate[]::new)); + } + @SuppressWarnings("unchecked") private static Join getOrCreateJoin(From from, String attribute, JoinType joinType) { for (Join join : from.getJoins()) { @@ -566,29 +631,13 @@ public class AppBookSpecification { }; } - public static Specification withAgeRatings(List rangeIds, String mode) { + public static Specification withAgeRatings(List values, String mode) { return (root, query, cb) -> { - List ids = parseIntList(rangeIds, "ageRating"); - if (ids.isEmpty()) return cb.conjunction(); + List> ranges = parseNumericRanges(values, Integer::valueOf, "ageRating"); + if (ranges.isEmpty()) return cb.conjunction(); Join metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER); Expression ageRating = metadataJoin.get("ageRating"); - - // Age rating ranges from frontend config (mirrored here for performance) - // 0: [0, 6), 6: [6, 10), 10: [10, 13), 13: [13, 16), 16: [16, 18), 18: [18, 21), 21: [21, inf) - List predicates = new ArrayList<>(); - for (Integer id : ids) { - predicates.add(switch (id) { - case 0 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 0), cb.lessThan(ageRating, 6)); - case 6 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 6), cb.lessThan(ageRating, 10)); - case 10 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 10), cb.lessThan(ageRating, 13)); - case 13 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 13), cb.lessThan(ageRating, 16)); - case 16 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 16), cb.lessThan(ageRating, 18)); - case 18 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 18), cb.lessThan(ageRating, 21)); - case 21 -> cb.greaterThanOrEqualTo(ageRating, 21); - default -> throw new APIException("Invalid ageRating bucket ID: " + id, HttpStatus.BAD_REQUEST); - }); - } - Predicate combined = cb.or(predicates.toArray(Predicate[]::new)); + Predicate combined = rangesPredicate(cb, ageRating, ranges); return "not".equals(mode) ? cb.not(combined) : combined; }; } @@ -601,76 +650,46 @@ public class AppBookSpecification { }; } - public static Specification withMatchScores(List rangeIds, String mode) { + public static Specification withMatchScores(List values, String mode) { return (root, query, cb) -> { - List ids = parseIntList(rangeIds, "matchScore"); - if (ids.isEmpty()) return cb.conjunction(); + List> ranges = parseNumericRanges(values, Float::valueOf, "matchScore"); + if (ranges.isEmpty()) return cb.conjunction(); Expression score = root.get("metadataMatchScore"); - - List predicates = new ArrayList<>(); - for (Integer id : ids) { - predicates.add(switch (id) { - case 0 -> cb.greaterThanOrEqualTo(score, 0.95f); - case 1 -> cb.and(cb.greaterThanOrEqualTo(score, 0.90f), cb.lessThan(score, 0.95f)); - case 2 -> cb.and(cb.greaterThanOrEqualTo(score, 0.80f), cb.lessThan(score, 0.90f)); - case 3 -> cb.and(cb.greaterThanOrEqualTo(score, 0.70f), cb.lessThan(score, 0.80f)); - case 4 -> cb.and(cb.greaterThanOrEqualTo(score, 0.50f), cb.lessThan(score, 0.70f)); - case 5 -> cb.and(cb.greaterThanOrEqualTo(score, 0.30f), cb.lessThan(score, 0.50f)); - case 6 -> cb.and(cb.greaterThanOrEqualTo(score, 0.00f), cb.lessThan(score, 0.30f)); - default -> throw new APIException("Invalid matchScore bucket ID: " + id, HttpStatus.BAD_REQUEST); - }); - } - Predicate combined = cb.or(predicates.toArray(Predicate[]::new)); + Predicate combined = rangesPredicate(cb, score, ranges); return "not".equals(mode) ? cb.not(combined) : combined; }; } public static Specification withPublishedYears(List years, String mode) { return (root, query, cb) -> { - if (years.isEmpty()) return cb.conjunction(); - List parsedYears = parseIntList(years, "publishedDate"); - if (parsedYears.isEmpty()) return cb.conjunction(); + List> ranges = parseNumericRanges(years, Integer::valueOf, "publishedDate"); + if (ranges.isEmpty()) return cb.conjunction(); Join metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER); Expression yearExpr = cb.function("YEAR", Integer.class, metadataJoin.get("publishedDate")); - Predicate combined = yearExpr.in(parsedYears); + Predicate combined = rangesPredicate(cb, yearExpr, ranges); return "not".equals(mode) ? cb.not(combined) : combined; }; } - public static Specification withFileSizes(List rangeIds, String mode) { + public static Specification withFileSizes(List values, String mode) { return (root, query, cb) -> { - List ids = parseIntList(rangeIds, "fileSize"); - if (ids.isEmpty()) return cb.conjunction(); - - Subquery sub = query.subquery(Long.class); - Root subRoot = sub.correlate(root); - Join bfJoin = subRoot.join("bookFiles", JoinType.INNER); - - Subquery minIdSub = query.subquery(Long.class); - Root minIdRoot = minIdSub.correlate(root); - Join minIdJoin = minIdRoot.join("bookFiles", JoinType.INNER); - minIdSub.select(cb.min(minIdJoin.get("id"))) - .where(cb.equal(minIdJoin.get("isBookFormat"), true)); + List> ranges = parseNumericRanges(values, Long::valueOf, "fileSize"); + if (ranges.isEmpty()) return cb.conjunction(); - Expression size = bfJoin.get("fileSizeKb"); - List predicates = new ArrayList<>(); - for (Integer id : ids) { - predicates.add(switch (id) { - case 0 -> cb.and(cb.greaterThanOrEqualTo(size, 0L), cb.lessThan(size, 1024L)); - case 1 -> cb.and(cb.greaterThanOrEqualTo(size, 1024L), cb.lessThan(size, 10240L)); - case 2 -> cb.and(cb.greaterThanOrEqualTo(size, 10240L), cb.lessThan(size, 51200L)); - case 3 -> cb.and(cb.greaterThanOrEqualTo(size, 51200L), cb.lessThan(size, 102400L)); - case 4 -> cb.and(cb.greaterThanOrEqualTo(size, 102400L), cb.lessThan(size, 512000L)); - case 5 -> cb.and(cb.greaterThanOrEqualTo(size, 512000L), cb.lessThan(size, 1048576L)); - case 6 -> cb.and(cb.greaterThanOrEqualTo(size, 1048576L), cb.lessThan(size, 2097152L)); - case 7 -> cb.greaterThanOrEqualTo(size, 2097152L); - default -> throw new APIException("Invalid fileSize bucket ID: " + id, HttpStatus.BAD_REQUEST); - }); - } - - sub.select(cb.literal(1L)) - .where(cb.equal(bfJoin.get("id"), minIdSub), - cb.or(predicates.toArray(Predicate[]::new))); + // Matches against the book's first book-format file. + Subquery sub = query.subquery(Long.class); + Root file = sub.from(BookFileEntity.class); + Subquery earlier = sub.subquery(Long.class); + Root earlierFile = earlier.from(BookFileEntity.class); + earlier.select(cb.literal(1L)).where( + cb.equal(earlierFile.get("book").get("id"), root.get("id")), + cb.equal(earlierFile.get("isBookFormat"), true), + cb.lessThan(earlierFile.get("id"), file.get("id"))); + sub.select(cb.literal(1L)).where( + cb.equal(file.get("book").get("id"), root.get("id")), + cb.equal(file.get("isBookFormat"), true), + cb.not(cb.exists(earlier)), + rangesPredicate(cb, file.get("fileSizeKb"), ranges)); return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub); }; @@ -717,49 +736,24 @@ public class AppBookSpecification { } private static Specification buildRatingRangeSpec( - List rangeIds, String mode, String fieldName) { + List values, String mode, String fieldName) { return (root, query, cb) -> { - List ids = parseIntList(rangeIds, fieldName); - if (ids.isEmpty()) return cb.conjunction(); + List> ranges = parseNumericRanges(values, Double::valueOf, fieldName); + if (ranges.isEmpty()) return cb.conjunction(); Join metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER); Expression rating = metadataJoin.get(fieldName); - List predicates = new ArrayList<>(); - for (Integer id : ids) { - predicates.add(switch (id) { - case 5 -> cb.greaterThanOrEqualTo(rating, 4.5); - case 4 -> cb.and(cb.greaterThanOrEqualTo(rating, 4.0), cb.lessThan(rating, 4.5)); - case 3 -> cb.and(cb.greaterThanOrEqualTo(rating, 3.0), cb.lessThan(rating, 4.0)); - case 2 -> cb.and(cb.greaterThanOrEqualTo(rating, 2.0), cb.lessThan(rating, 3.0)); - case 1 -> cb.and(cb.greaterThanOrEqualTo(rating, 1.0), cb.lessThan(rating, 2.0)); - case 0 -> cb.lessThan(rating, 1.0); - default -> throw new APIException("Invalid " + fieldName + " bucket ID: " + id, HttpStatus.BAD_REQUEST); - }); - } - Predicate combined = cb.or(predicates.toArray(Predicate[]::new)); + Predicate combined = rangesPredicate(cb, rating, ranges); return "not".equals(mode) ? cb.not(combined) : combined; }; } - public static Specification withPageCounts(List rangeIds, String mode) { + public static Specification withPageCounts(List values, String mode) { return (root, query, cb) -> { - List ids = parseIntList(rangeIds, "pageCount"); - if (ids.isEmpty()) return cb.conjunction(); + List> ranges = parseNumericRanges(values, Integer::valueOf, "pageCount"); + if (ranges.isEmpty()) return cb.conjunction(); Join metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER); Expression count = metadataJoin.get("pageCount"); - List predicates = new ArrayList<>(); - for (Integer id : ids) { - predicates.add(switch (id) { - case 0 -> cb.lessThan(count, 50); - case 1 -> cb.and(cb.greaterThanOrEqualTo(count, 50), cb.lessThan(count, 100)); - case 2 -> cb.and(cb.greaterThanOrEqualTo(count, 100), cb.lessThan(count, 200)); - case 3 -> cb.and(cb.greaterThanOrEqualTo(count, 200), cb.lessThan(count, 400)); - case 4 -> cb.and(cb.greaterThanOrEqualTo(count, 400), cb.lessThan(count, 600)); - case 5 -> cb.and(cb.greaterThanOrEqualTo(count, 600), cb.lessThan(count, 1000)); - case 6 -> cb.greaterThanOrEqualTo(count, 1000); - default -> throw new APIException("Invalid pageCount bucket ID: " + id, HttpStatus.BAD_REQUEST); - }); - } - Predicate combined = cb.or(predicates.toArray(Predicate[]::new)); + Predicate combined = rangesPredicate(cb, count, ranges); return "not".equals(mode) ? cb.not(combined) : combined; }; } diff --git a/backend/src/main/java/org/booklore/service/browse/BookFacetRegistry.java b/backend/src/main/java/org/booklore/service/browse/BookFacetRegistry.java index bfaee39d9..dd6de5676 100644 --- a/backend/src/main/java/org/booklore/service/browse/BookFacetRegistry.java +++ b/backend/src/main/java/org/booklore/service/browse/BookFacetRegistry.java @@ -18,9 +18,10 @@ public class BookFacetRegistry { private static final String MAGIC_SHELF_PREFIX = "magic:"; private static final Set NAMES = Set.of( - "author", "series", "genre", "tag", "mood", "language", "publisher", "library", "shelf", + "author", "series", "genre", "tag", "mood", "language", "publisher", "narrator", "library", "shelf", "file_type", "read_status", "personal_rating", "amazon_rating", "goodreads_rating", - "hardcover_rating", "ranobedb_rating", "age_rating", "content_rating", "match_score", + "hardcover_rating", "ranobedb_rating", "lubimyczytac_rating", "audible_rating", + "age_rating", "content_rating", "match_score", "published_year", "file_size", "page_count", "shelf_status", "comic_character", "comic_team", "comic_location", "comic_creator"); @@ -48,6 +49,7 @@ public class BookFacetRegistry { case "mood" -> AppBookSpecification.withMoods(values, mode); case "language" -> AppBookSpecification.withLanguages(values, mode); case "publisher" -> AppBookSpecification.withPublishers(values, mode); + case "narrator" -> AppBookSpecification.withNarrators(values, mode); case "library" -> AppBookSpecification.inLibraries(values, mode); case "shelf" -> shelves(values, logic, userId); case "file_type" -> AppBookSpecification.withFileTypes(values, mode); @@ -57,6 +59,8 @@ public class BookFacetRegistry { case "goodreads_rating" -> AppBookSpecification.withGoodreadsRatings(values, mode); case "hardcover_rating" -> AppBookSpecification.withHardcoverRatings(values, mode); case "ranobedb_rating" -> AppBookSpecification.withRanobedbRatings(values, mode); + case "lubimyczytac_rating" -> AppBookSpecification.withLubimyczytacRatings(values, mode); + case "audible_rating" -> AppBookSpecification.withAudibleRatings(values, mode); case "age_rating" -> AppBookSpecification.withAgeRatings(values, mode); case "content_rating" -> AppBookSpecification.withContentRatings(values, mode); case "match_score" -> AppBookSpecification.withMatchScores(values, mode); diff --git a/backend/src/main/java/org/booklore/service/browse/BookFacetService.java b/backend/src/main/java/org/booklore/service/browse/BookFacetService.java index ddce8d7a6..d299e6caf 100644 --- a/backend/src/main/java/org/booklore/service/browse/BookFacetService.java +++ b/backend/src/main/java/org/booklore/service/browse/BookFacetService.java @@ -24,6 +24,9 @@ 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.BookFileEntity; +import org.booklore.model.entity.UserBookProgressEntity; +import org.booklore.model.enums.ReadStatus; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -33,7 +36,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.function.Function; @Service @RequiredArgsConstructor @@ -45,15 +47,53 @@ public class BookFacetService { private static final int MAX_VALUES = 100; private static final List FACETS = List.of( - new FacetDef("author", "Authors", root -> metadata(root).join("authors", JoinType.LEFT).get("name")), - new FacetDef("genre", "Genre", root -> metadata(root).join("categories", JoinType.LEFT).get("name")), - new FacetDef("tag", "Tags", root -> metadata(root).join("tags", JoinType.LEFT).get("name")), - new FacetDef("mood", "Moods", root -> metadata(root).join("moods", JoinType.LEFT).get("name")), - new FacetDef("series", "Series", root -> metadata(root).get("seriesName")), - new FacetDef("publisher", "Publisher", root -> metadata(root).get("publisher")), - new FacetDef("language", "Language", root -> metadata(root).get("language")), - new FacetDef("narrator", "Narrator", root -> metadata(root).get("narrator")), - new FacetDef("file_type", "File Type", root -> root.join("bookFiles", JoinType.LEFT).get("bookType"))); + new FacetDef("author", "Authors", (cb, root, userId) -> 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("tag", "Tags", (cb, root, userId) -> 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("series", "Series", (cb, root, userId) -> metadata(root).get("seriesName")), + new FacetDef("publisher", "Publisher", (cb, root, userId) -> metadata(root).get("publisher")), + new FacetDef("language", "Language", (cb, root, userId) -> metadata(root).get("language")), + new FacetDef("narrator", "Narrator", (cb, root, userId) -> metadata(root).get("narrator")), + new FacetDef("file_type", "File Type", (cb, root, userId) -> root.join("bookFiles", JoinType.LEFT).get("bookType")), + new FacetDef("content_rating", "Content Rating", (cb, root, userId) -> metadata(root).get("contentRating")), + new FacetDef("amazon_rating", "Amazon Rating", (cb, root, userId) -> metadata(root).get("amazonRating")), + new FacetDef("goodreads_rating", "Goodreads Rating", (cb, root, userId) -> metadata(root).get("goodreadsRating")), + new FacetDef("hardcover_rating", "Hardcover Rating", (cb, root, userId) -> metadata(root).get("hardcoverRating")), + new FacetDef("ranobedb_rating", "RanobeDB Rating", (cb, root, userId) -> metadata(root).get("ranobedbRating")), + new FacetDef("lubimyczytac_rating", "Lubimyczytac Rating", (cb, root, userId) -> metadata(root).get("lubimyczytacRating")), + new FacetDef("audible_rating", "Audible Rating", (cb, root, userId) -> metadata(root).get("audibleRating")), + new FacetDef("age_rating", "Age Rating", (cb, root, userId) -> metadata(root).get("ageRating")), + new FacetDef("page_count", "Page Count", (cb, root, userId) -> metadata(root).get("pageCount")), + new FacetDef("match_score", "Match Score", (cb, root, userId) -> root.get("metadataMatchScore")), + new FacetDef("published_year", "Published Year", (cb, root, userId) -> + cb.function("YEAR", Integer.class, metadata(root).get("publishedDate"))), + new FacetDef("library", "Library", (cb, root, userId) -> root.join("library").get("id")), + new FacetDef("shelf", "Shelf", (cb, root, userId) -> root.join("shelves", JoinType.LEFT).get("id")), + new FacetDef("shelf_status", "Shelf Status", (cb, root, userId) -> cb.selectCase() + .when(cb.isNotEmpty(root.get("shelves")), "shelved") + .otherwise("unshelved")), + new FacetDef("read_status", "Read Status", (cb, root, userId) -> { + Join progress = root.join("userBookProgress", JoinType.LEFT); + progress.on(cb.equal(progress.get("user").get("id"), userId)); + return cb.selectCase() + .when(progress.get("id").isNull(), ReadStatus.UNSET) + .otherwise(progress.get("readStatus")); + }), + new FacetDef("personal_rating", "Personal Rating", (cb, root, userId) -> { + Join progress = root.join("userBookProgress"); + progress.on(cb.equal(progress.get("user").get("id"), userId)); + return progress.get("personalRating"); + }), + new FacetDef("file_size", "File Size", (cb, root, userId) -> { + Join files = root.join("bookFiles", JoinType.LEFT); + files.on(cb.isTrue(files.get("isBookFormat"))); + 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_team", "Comic Teams", (cb, root, userId) -> 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_creator", "Comic Creators", (cb, root, userId) -> metadata(root).join("comicMetadata", JoinType.LEFT).join("creatorMappings", JoinType.LEFT).join("creator", JoinType.LEFT).get("name"))); private final AuthenticationService authenticationService; private final BookFilterSpecifications filterSpecifications; @@ -83,7 +123,7 @@ public class BookFacetService { groups.add(sortGroup(preserved)); for (FacetDef def : FACETS) { Specification base = filterSpecifications.base(query, facets, facetLogic, userId, isAdmin, libraryIds, def.key()); - groups.add(toGroup(def, count(def, base), facet, preserved)); + groups.add(toGroup(def, count(def, base, userId), facet, preserved)); } List links = List.of(Link.json(List.of("self"), href(FACET_PATH, preserved))); return new FacetGroupsResponse(links, groups); @@ -95,11 +135,11 @@ public class BookFacetService { cache.invalidateAll(); } - private List count(FacetDef def, Specification base) { + private List count(FacetDef def, Specification base, Long userId) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery cq = cb.createTupleQuery(); Root root = cq.from(BookEntity.class); - Expression value = def.value().apply(root); + Expression value = def.value().apply(cb, root, userId); Expression count = cb.countDistinct(root.get("id")); List predicates = new ArrayList<>(); @@ -157,7 +197,11 @@ public class BookFacetService { return root.join("metadata", JoinType.LEFT); } - private record FacetDef(String key, String title, Function, Expression> value) { + private interface FacetValueSource { + Expression apply(CriteriaBuilder cb, Root root, Long userId); + } + + private record FacetDef(String key, String title, FacetValueSource value) { } private record FacetCount(String value, long count) {