refactor(api): optimize caching mechanisms and improve book filtering (#372)

* refactor(api): optimize caching mechanisms and improve book filtering logic

* refactor(preferences): remove unused ExternalDocLinkComponent and enhance translate function typing

* refactor(initializer): add Duration import for improved cache management

* refactor(docker): increase MaxMetaspaceSize for improved memory management

* refactor(repository): replace findAllForSummaryByIds with findAllById

* refactor(cache): implement invalidateAppBooksQueries for improved cache management

* refactor(AppBookService): increase default page size and optimize magic shelf book resolution

* refactor(AppBookSpecification, MagicShelfBookService, TaskCancellationManager, magic-shelf-component): streamline join handling and improve memory management

* refactor(AppBookService, MagicShelfBookService): enhance book retrieval logic and improve error handling

* chore: fix formatting

* chore: fix formatting
This commit is contained in:
brios
2026-04-22 17:27:10 -04:00
committed by Zach Yale
parent 402c6f07c8
commit 3e5a6a9de8
40 changed files with 1296 additions and 429 deletions
@@ -4,8 +4,6 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.booklore.app.dto.*;
import org.booklore.app.service.AppBookService;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ReadStatus;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
@@ -28,23 +26,9 @@ public class AppBookController {
)
@GetMapping
public ResponseEntity<AppPageResponse<AppBookSummary>> getBooks(
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "50") Integer size,
@RequestParam(required = false, defaultValue = "addedOn") String sort,
@RequestParam(required = false, defaultValue = "desc") String dir,
@RequestParam(required = false) Long libraryId,
@RequestParam(required = false) Long shelfId,
@RequestParam(required = false) ReadStatus status,
@RequestParam(required = false) String search,
@RequestParam(required = false) BookFileType fileType,
@RequestParam(required = false) Integer minRating,
@RequestParam(required = false) Integer maxRating,
@RequestParam(required = false) String authors,
@RequestParam(required = false) String language) {
@ModelAttribute BookListRequest request) {
return ResponseEntity.ok(mobileBookService.getBooks(
page, size, sort, dir, libraryId, shelfId, status, search,
fileType, minRating, maxRating, authors, language));
return ResponseEntity.ok(mobileBookService.getBooks(request));
}
@Operation(
@@ -1,40 +1,25 @@
package org.booklore.app.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 AppFilterOptions {
private List<AuthorOption> authors;
private List<LanguageOption> languages;
private List<String> readStatuses;
private List<String> fileTypes;
public record AppFilterOptions(
List<CountedOption> authors,
List<LanguageOption> languages,
List<String> readStatuses,
List<String> fileTypes,
List<CountedOption> categories,
List<CountedOption> publishers,
List<CountedOption> series,
List<CountedOption> tags,
List<CountedOption> moods,
List<CountedOption> narrators) {
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class AuthorOption {
private String name;
private long count;
}
public record LanguageOption(String code, String label, long count) {}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class LanguageOption {
private String code;
private String label;
private long count;
}
public record CountedOption(String name, long count) {}
}
@@ -0,0 +1,58 @@
package org.booklore.app.dto;
import jakarta.validation.constraints.Size;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ReadStatus;
import java.util.List;
public record BookListRequest(
Integer page,
Integer size,
String sort,
String dir,
Long libraryId,
Long shelfId,
ReadStatus status,
String search,
BookFileType fileType,
Integer minRating,
Integer maxRating,
@Size(max = 20) List<String> authors,
@Size(max = 20) List<String> language,
@Size(max = 20) List<String> series,
@Size(max = 20) List<String> category,
@Size(max = 20) List<String> publisher,
@Size(max = 20) List<String> tag,
@Size(max = 20) List<String> mood,
@Size(max = 20) List<String> narrator,
Long magicShelfId,
Boolean unshelved,
String filterMode) {
/**
* Returns the effective filter mode, defaulting to "or" when not specified.
*/
public String effectiveFilterMode() {
if (filterMode == null || filterMode.isBlank()) return "or";
return switch (filterMode.toLowerCase()) {
case "and", "not" -> filterMode.toLowerCase();
default -> "or";
};
}
private static boolean hasValues(List<String> list) {
return list != null && !list.isEmpty() && list.stream().anyMatch(s -> s != null && !s.isBlank());
}
/**
* Returns non-blank trimmed values from the given list, or an empty list.
*/
public static List<String> cleanValues(List<String> list) {
if (list == null) return List.of();
return list.stream()
.filter(s -> s != null && !s.isBlank())
.map(String::trim)
.toList();
}
}
@@ -1,12 +1,15 @@
package org.booklore.app.service;
import lombok.AllArgsConstructor;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.app.dto.AppBookDetail;
import org.booklore.app.dto.AppBookSummary;
import org.booklore.app.dto.AppFilterOptions;
import org.booklore.app.dto.AppPageResponse;
import org.booklore.app.dto.BookListRequest;
import org.booklore.app.mapper.AppBookMapper;
import org.booklore.app.specification.AppBookSpecification;
import org.booklore.model.dto.Book;
@@ -36,12 +39,14 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class AppBookService {
private static final int DEFAULT_PAGE_SIZE = 20;
private static final int DEFAULT_PAGE_SIZE = 50;
private static final int MAX_PAGE_SIZE = 50;
private final BookRepository bookRepository;
@@ -53,34 +58,64 @@ public class AppBookService {
private final MagicShelfBookService magicShelfBookService;
private final EntityManager entityManager;
public AppPageResponse<AppBookSummary> getBooks(
Integer page,
Integer size,
String sortBy,
String sortDir,
Long libraryId,
Long shelfId,
ReadStatus status,
String search,
BookFileType fileType,
Integer minRating,
Integer maxRating,
String authors,
String language) {
private final Cache<String, AppFilterOptions> filterOptionsCache = Caffeine.newBuilder()
.expireAfterWrite(java.time.Duration.ofSeconds(30))
.maximumSize(50)
.build();
public AppBookService(BookRepository bookRepository,
UserBookProgressRepository userBookProgressRepository,
UserBookFileProgressRepository userBookFileProgressRepository,
ShelfRepository shelfRepository,
AuthenticationService authenticationService,
AppBookMapper mobileBookMapper,
MagicShelfBookService magicShelfBookService,
EntityManager entityManager) {
this.bookRepository = bookRepository;
this.userBookProgressRepository = userBookProgressRepository;
this.userBookFileProgressRepository = userBookFileProgressRepository;
this.shelfRepository = shelfRepository;
this.authenticationService = authenticationService;
this.mobileBookMapper = mobileBookMapper;
this.magicShelfBookService = magicShelfBookService;
this.entityManager = entityManager;
}
public AppPageResponse<AppBookSummary> getBooks(BookListRequest req) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
int pageNum = page != null && page >= 0 ? page : 0;
int pageSize = size != null && size > 0 ? Math.min(size, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
int pageNum = req.page() != null && req.page() >= 0 ? req.page() : 0;
int pageSize = req.size() != null && req.size() > 0 ? Math.min(req.size(), MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
Sort sort = buildSort(sortBy, sortDir);
// Handle magic shelf: compose the DB-side specification directly (no IN-list)
if (req.magicShelfId() != null) {
Sort sort = buildSort(req.sort(), req.dir());
Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
Specification<BookEntity> spec = buildSpecification(
accessibleLibraryIds, userId, req);
spec = spec.and(magicShelfBookService.toSpecification(userId, req.magicShelfId()));
if (Boolean.TRUE.equals(req.unshelved())) {
spec = spec.and(AppBookSpecification.unshelved());
}
Page<BookEntity> bookPage = bookRepository.findAll(spec, pageable);
return buildPageResponse(bookPage, userId, pageNum, pageSize);
}
Sort sort = buildSort(req.sort(), req.dir());
Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
Specification<BookEntity> spec = buildSpecification(
accessibleLibraryIds, libraryId, shelfId, status, search, userId,
fileType, minRating, maxRating, authors, language);
accessibleLibraryIds, userId, req);
if (Boolean.TRUE.equals(req.unshelved())) {
spec = spec.and(AppBookSpecification.unshelved());
}
Page<BookEntity> bookPage = bookRepository.findAll(spec, pageable);
return buildPageResponse(bookPage, userId, pageNum, pageSize);
@@ -152,7 +187,7 @@ public class AppBookService {
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, new HashSet<>(topIds));
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(topIds)
Map<Long, BookEntity> enrichedMap = bookRepository.findAllById(topIds)
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
return topIds.stream()
@@ -175,7 +210,7 @@ public class AppBookService {
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, new HashSet<>(topIds));
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(topIds)
Map<Long, BookEntity> enrichedMap = bookRepository.findAllById(topIds)
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
return topIds.stream()
@@ -271,18 +306,21 @@ public class AppBookService {
var booksPage = magicShelfBookService.getBooksByMagicShelfId(userId, magicShelfId, pageNum, pageSize);
Set<Long> bookIds = booksPage.getContent().stream()
List<Long> orderedBookIds = booksPage.getContent().stream()
.map(Book::getId)
.collect(Collectors.toSet());
.toList();
if (bookIds.isEmpty()) {
if (orderedBookIds.isEmpty()) {
return AppPageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
}
List<BookEntity> bookEntities = bookRepository.findAllForSummaryByIds(bookIds);
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, bookEntities);
Map<Long, BookEntity> bookEntitiesById = bookRepository.findAllById(orderedBookIds).stream()
.collect(Collectors.toMap(BookEntity::getId, Function.identity()));
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, bookEntitiesById.keySet());
List<AppBookSummary> summaries = bookEntities.stream()
List<AppBookSummary> summaries = orderedBookIds.stream()
.map(bookEntitiesById::get)
.filter(Objects::nonNull)
.filter(BookEntity::hasFiles)
.map(bookEntity -> mobileBookMapper.toSummary(bookEntity, progressMap.get(bookEntity.getId())))
.collect(Collectors.toList());
@@ -295,20 +333,6 @@ public class AppBookService {
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
// 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 AppFilterOptions.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);
@@ -323,6 +347,34 @@ public class AppBookService {
}
}
// Cache lookup avoid re-running 9 aggregate queries within the TTL window
String cacheKey = userId + ":" + libraryId + ":" + shelfId + ":" + magicShelfId;
AppFilterOptions cached = filterOptionsCache.getIfPresent(cacheKey);
if (cached != null) {
return cached;
}
Set<Long> magicBookIds = null;
if (magicShelfId != null) {
magicBookIds = resolveMagicShelfBookIds(magicShelfId, userId);
if (magicBookIds.isEmpty()) {
AppFilterOptions empty = AppFilterOptions.builder()
.authors(Collections.emptyList())
.languages(Collections.emptyList())
.fileTypes(Collections.emptyList())
.readStatuses(getReadStatusOptions())
.categories(Collections.emptyList())
.publishers(Collections.emptyList())
.series(Collections.emptyList())
.tags(Collections.emptyList())
.moods(Collections.emptyList())
.narrators(Collections.emptyList())
.build();
filterOptionsCache.put(cacheKey, empty);
return empty;
}
}
// Build scoping clauses
String libraryClause = "";
String shelfClause = "";
@@ -343,44 +395,20 @@ public class AppBookService {
// 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.bookFiles IS NOT EMPTY"
+ scopeClause
+ " GROUP BY a.name ORDER BY COUNT(DISTINCT b.id) DESC";
var authorQ = entityManager.createQuery(authorQuery, Tuple.class);
setFilterQueryParams(authorQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
authorQ.setMaxResults(200);
List<AppFilterOptions.CountedOption> authors = queryCountedOptions(
"a.name", "JOIN b.metadata m JOIN m.authors a", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.AuthorOption> authors = authorQ.getResultList().stream()
.map(t -> AppFilterOptions.AuthorOption.builder()
.name(t.get(0, String.class))
.count(t.get(1, Long.class))
.build())
List<AppFilterOptions.LanguageOption> languages = queryCountedOptions(
"m.language", "JOIN b.metadata m",
"AND m.language IS NOT NULL AND m.language <> ''",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds).stream()
.map(c -> new AppFilterOptions.LanguageOption(
c.name(),
Locale.forLanguageTag(c.name()).getDisplayLanguage(Locale.ENGLISH),
c.count()))
.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.bookFiles IS NOT EMPTY"
+ " 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);
setFilterQueryParams(langQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.LanguageOption> languages = langQ.getResultList().stream()
.map(t -> AppFilterOptions.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 scoped books
String fileTypeQuery = "SELECT DISTINCT bf.bookType FROM BookEntity b"
+ " JOIN b.bookFiles bf"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
@@ -389,21 +417,68 @@ public class AppBookService {
+ scopeClause;
var ftQ = entityManager.createQuery(fileTypeQuery, BookFileType.class);
setFilterQueryParams(ftQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<String> fileTypes = ftQ.getResultList().stream().map(Enum::name).sorted().toList();
List<String> fileTypes = ftQ.getResultList().stream()
.map(Enum::name)
.sorted()
.toList();
List<AppFilterOptions.CountedOption> categories = queryCountedOptions(
"c.name", "JOIN b.metadata m JOIN m.categories c", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
// Read statuses — return all meaningful values
List<String> readStatuses = getReadStatusOptions();
List<AppFilterOptions.CountedOption> publishers = queryCountedOptions(
"m.publisher", "JOIN b.metadata m",
"AND m.publisher IS NOT NULL AND m.publisher <> ''",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
return AppFilterOptions.builder()
List<AppFilterOptions.CountedOption> seriesOptions = queryCountedOptions(
"m.seriesName", "JOIN b.metadata m",
"AND m.seriesName IS NOT NULL AND m.seriesName <> ''",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> tags = queryCountedOptions(
"t.name", "JOIN b.metadata m JOIN m.tags t", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> moods = queryCountedOptions(
"mo.name", "JOIN b.metadata m JOIN m.moods mo", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> narrators = queryCountedOptions(
"m.narrator", "JOIN b.metadata m",
"AND m.narrator IS NOT NULL AND m.narrator <> ''",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
AppFilterOptions result = AppFilterOptions.builder()
.authors(authors)
.languages(languages)
.fileTypes(fileTypes)
.readStatuses(readStatuses)
.readStatuses(getReadStatusOptions())
.categories(categories)
.publishers(publishers)
.series(seriesOptions)
.tags(tags)
.moods(moods)
.narrators(narrators)
.build();
filterOptionsCache.put(cacheKey, result);
return result;
}
private List<AppFilterOptions.CountedOption> queryCountedOptions(
String selectExpr, String joins, String extraWhere,
String scopeClause, Set<Long> accessibleLibraryIds,
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
String jpql = "SELECT " + selectExpr + ", COUNT(DISTINCT b.id) FROM BookEntity b"
+ " " + joins
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND b.bookFiles IS NOT EMPTY"
+ (extraWhere.isEmpty() ? "" : " " + extraWhere)
+ scopeClause
+ " GROUP BY " + selectExpr + " ORDER BY COUNT(DISTINCT b.id) DESC";
var q = entityManager.createQuery(jpql, Tuple.class);
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
q.setMaxResults(200);
return q.getResultList().stream()
.map(t -> new AppFilterOptions.CountedOption(t.get(0, String.class), t.get(1, Long.class)))
.toList();
}
private String buildScopeClause(String libraryClause, String shelfClause, String magicBookClause) {
@@ -429,12 +504,14 @@ public class AppBookService {
}
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());
Specification<BookEntity> spec = magicShelfBookService.toSpecification(userId, magicShelfId);
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<BookEntity> root = cq.from(BookEntity.class);
cq.select(root.get("id"));
cq.where(spec.toPredicate(root, cq, cb));
return new HashSet<>(entityManager.createQuery(cq)
.getResultList());
}
private List<String> getReadStatusOptions() {
@@ -519,68 +596,108 @@ public class AppBookService {
private Specification<BookEntity> buildSpecification(
Set<Long> accessibleLibraryIds,
Long libraryId,
Long shelfId,
ReadStatus status,
String search,
Long userId,
BookFileType fileType,
Integer minRating,
Integer maxRating,
String authors,
String language) {
BookListRequest req) {
List<Specification<BookEntity>> specs = new ArrayList<>();
specs.add(AppBookSpecification.notDeleted());
specs.add(AppBookSpecification.hasDigitalFile());
if (accessibleLibraryIds != null) {
if (libraryId != null && accessibleLibraryIds.contains(libraryId)) {
specs.add(AppBookSpecification.inLibrary(libraryId));
} else if (libraryId != null) {
throw ApiError.FORBIDDEN.createException("Access denied to library " + libraryId);
if (req.libraryId() != null && accessibleLibraryIds.contains(req.libraryId())) {
specs.add(AppBookSpecification.inLibrary(req.libraryId()));
} else if (req.libraryId() != null) {
throw ApiError.FORBIDDEN.createException("Access denied to library " + req.libraryId());
} else {
specs.add(AppBookSpecification.inLibraries(accessibleLibraryIds));
}
} else if (libraryId != null) {
specs.add(AppBookSpecification.inLibrary(libraryId));
} else if (req.libraryId() != null) {
specs.add(AppBookSpecification.inLibrary(req.libraryId()));
}
if (shelfId != null) {
ShelfEntity shelf = shelfRepository.findById(shelfId)
.orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
if (req.shelfId() != null) {
ShelfEntity shelf = shelfRepository.findById(req.shelfId())
.orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(req.shelfId()));
if (!shelf.isPublic() && !shelf.getUser().getId().equals(userId)) {
throw ApiError.FORBIDDEN.createException("Access denied to shelf " + shelfId);
throw ApiError.FORBIDDEN.createException("Access denied to shelf " + req.shelfId());
}
specs.add(AppBookSpecification.inShelf(shelfId));
specs.add(AppBookSpecification.inShelf(req.shelfId()));
}
if (status != null) {
specs.add(AppBookSpecification.withReadStatus(status, userId));
if (req.status() != null) {
specs.add(AppBookSpecification.withReadStatus(req.status(), userId));
}
if (search != null && !search.trim().isEmpty()) {
specs.add(AppBookSpecification.searchText(search));
if (req.search() != null && !req.search().trim().isEmpty()) {
specs.add(AppBookSpecification.searchText(req.search()));
}
if (fileType != null) {
specs.add(AppBookSpecification.withFileType(fileType));
if (req.fileType() != null) {
specs.add(AppBookSpecification.withFileType(req.fileType()));
}
if (minRating != null) {
specs.add(AppBookSpecification.withMinRating(minRating, userId));
if (req.minRating() != null) {
specs.add(AppBookSpecification.withMinRating(req.minRating(), userId));
}
if (maxRating != null) {
specs.add(AppBookSpecification.withMaxRating(maxRating, userId));
if (req.maxRating() != null) {
specs.add(AppBookSpecification.withMaxRating(req.maxRating(), userId));
}
if (authors != null && !authors.trim().isEmpty()) {
specs.add(AppBookSpecification.withAuthor(authors.trim()));
if (req.authors() != null && !req.authors().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.authors());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withAuthors(cleaned, req.effectiveFilterMode()));
}
}
if (language != null && !language.trim().isEmpty()) {
specs.add(AppBookSpecification.withLanguage(language.trim()));
if (req.language() != null && !req.language().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.language());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withLanguages(cleaned, req.effectiveFilterMode()));
}
}
if (req.series() != null && !req.series().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.series());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.inSeriesMulti(cleaned, req.effectiveFilterMode()));
}
}
if (req.category() != null && !req.category().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.category());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withCategories(cleaned, req.effectiveFilterMode()));
}
}
if (req.publisher() != null && !req.publisher().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.publisher());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withPublishers(cleaned, req.effectiveFilterMode()));
}
}
if (req.tag() != null && !req.tag().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.tag());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withTags(cleaned, req.effectiveFilterMode()));
}
}
if (req.mood() != null && !req.mood().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.mood());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withMoods(cleaned, req.effectiveFilterMode()));
}
}
if (req.narrator() != null && !req.narrator().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.narrator());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withNarrators(cleaned, req.effectiveFilterMode()));
}
}
return AppBookSpecification.combine(specs.toArray(new Specification[0]));
@@ -591,10 +708,17 @@ public class AppBookService {
? Sort.Direction.ASC
: Sort.Direction.DESC;
// "author" needs a join to the authors collection, which can't be expressed
// as a simple property path, fall through to the default (addedOn) for now.
String field = switch (sortBy != null ? sortBy.toLowerCase() : "") {
case "title" -> "metadata.title";
case "seriesname", "series" -> "metadata.seriesName";
case "lastreadtime" -> "addedOn";
case "seriesnumber" -> "metadata.seriesNumber";
case "publisher" -> "metadata.publisher";
case "language" -> "metadata.language";
case "publisheddate" -> "metadata.publishedDate";
case "lastreadtime" -> "lastReadTime";
case "pagecount" -> "metadata.pageCount";
default -> "addedOn";
};
@@ -638,25 +762,16 @@ public class AppBookService {
int pageNum,
int pageSize) {
List<BookEntity> enriched = enrichBooksForSummary(bookPage.getContent());
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, enriched);
List<BookEntity> books = bookPage.getContent();
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, books);
List<AppBookSummary> summaries = enriched.stream()
List<AppBookSummary> summaries = books.stream()
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
.collect(Collectors.toList());
return AppPageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
}
private List<BookEntity> enrichBooksForSummary(List<BookEntity> books) {
if (books.isEmpty()) return books;
Set<Long> ids = books.stream().map(BookEntity::getId).collect(Collectors.toSet());
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(ids)
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
return books.stream()
.map(b -> enrichedMap.getOrDefault(b.getId(), b))
.collect(Collectors.toList());
}
private Map<Long, UserBookProgressEntity> getProgressMapForBooks(Long userId, List<BookEntity> books) {
if (books.isEmpty()) {
@@ -17,6 +17,16 @@ public class AppBookSpecification {
private AppBookSpecification() {
}
@SuppressWarnings("unchecked")
private static <X, Y> Join<X, Y> getOrCreateJoin(From<?, X> from, String attribute, JoinType joinType) {
for (Join<X, ?> join : from.getJoins()) {
if (join.getAttribute().getName().equals(attribute) && join.getJoinType() == joinType) {
return (Join<X, Y>) join;
}
}
return from.join(attribute, joinType);
}
public static Specification<BookEntity> inLibraries(Collection<Long> libraryIds) {
return (root, query, cb) -> {
if (libraryIds == null || libraryIds.isEmpty()) {
@@ -92,16 +102,22 @@ public class AppBookSpecification {
String pattern = "%" + searchQuery.toLowerCase().trim() + "%";
Join<BookEntity, BookMetadataEntity> metadataJoin = root.join("metadata", JoinType.LEFT);
Join<BookMetadataEntity, AuthorEntity> authorsJoin = metadataJoin.join("authors", JoinType.LEFT);
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.like(cb.lower(metadataJoin.get("title")), pattern));
predicates.add(cb.like(cb.lower(metadataJoin.get("seriesName")), pattern));
predicates.add(cb.like(cb.lower(authorsJoin.get("name")), pattern));
// Use EXISTS subquery for author search to avoid DISTINCT and cartesian products
Subquery<Long> authorSubquery = query.subquery(Long.class);
Root<BookMetadataEntity> metaRoot = authorSubquery.from(BookMetadataEntity.class);
Join<BookMetadataEntity, AuthorEntity> authorJoin = metaRoot.join("authors", JoinType.INNER);
authorSubquery.select(cb.literal(1L))
.where(
cb.equal(metaRoot.get("id"), root.get("id")),
cb.like(cb.lower(authorJoin.get("name")), pattern)
);
query.distinct(true);
return cb.or(predicates.toArray(new Predicate[0]));
return cb.or(
cb.like(cb.lower(metadataJoin.get("title")), pattern),
cb.like(cb.lower(metadataJoin.get("seriesName")), pattern),
cb.exists(authorSubquery)
);
};
}
@@ -206,14 +222,22 @@ public class AppBookSpecification {
* Filter books by author name (case-insensitive exact match).
*/
public static Specification<BookEntity> withAuthor(String authorName) {
return withAuthors(authorName == null ? List.of() : List.of(authorName), "or");
}
/**
* Filter books by multiple author names with mode support.
* OR = books with ANY of the authors
* AND = books with ALL of the authors
* NOT = books with NONE of the authors
*/
public static Specification<BookEntity> withAuthors(List<String> authorNames, String mode) {
return (root, query, cb) -> {
if (authorName == null || authorName.trim().isEmpty()) {
return cb.conjunction();
}
Join<BookEntity, BookMetadataEntity> metadataJoin = root.join("metadata", JoinType.LEFT);
Join<BookMetadataEntity, AuthorEntity> authorsJoin = metadataJoin.join("authors", JoinType.LEFT);
query.distinct(true);
return cb.equal(cb.lower(authorsJoin.get("name")), authorName.toLowerCase().trim());
List<String> cleaned = cleanLowerCase(authorNames);
if (cleaned.isEmpty()) return cb.conjunction();
return buildManyToManySpec(root, query, cb, cleaned, mode,
"metadata", "authors", "name");
};
}
@@ -221,25 +245,203 @@ public class AppBookSpecification {
* Filter books by language code (case-insensitive).
*/
public static Specification<BookEntity> withLanguage(String language) {
return withLanguages(language == null ? List.of() : List.of(language), "or");
}
/**
* Filter books by multiple language codes with mode support.
*/
public static Specification<BookEntity> withLanguages(List<String> languages, String mode) {
return (root, query, cb) -> {
if (language == null || language.trim().isEmpty()) {
return cb.conjunction();
}
Join<BookEntity, BookMetadataEntity> metadataJoin = root.join("metadata", JoinType.LEFT);
return cb.equal(cb.lower(metadataJoin.get("language")), language.toLowerCase().trim());
List<String> cleaned = cleanLowerCase(languages);
if (cleaned.isEmpty()) return cb.conjunction();
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "language");
};
}
public static Specification<BookEntity> inSeries(String seriesName) {
return inSeriesMulti(seriesName == null ? List.of() : List.of(seriesName), "or");
}
/**
* Filter books by multiple series names with mode support.
*/
public static Specification<BookEntity> inSeriesMulti(List<String> seriesNames, String mode) {
return (root, query, cb) -> {
if (seriesName == null || seriesName.trim().isEmpty()) {
return cb.conjunction();
}
Join<BookEntity, BookMetadataEntity> metadataJoin = root.join("metadata", JoinType.LEFT);
return cb.equal(metadataJoin.get("seriesName"), seriesName);
List<String> cleaned = cleanLowerCase(seriesNames);
if (cleaned.isEmpty()) return cb.conjunction();
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "seriesName");
};
}
public static Specification<BookEntity> withCategory(String categoryName) {
return withCategories(categoryName == null ? List.of() : List.of(categoryName), "or");
}
/**
* Filter books by multiple categories with mode support.
*/
public static Specification<BookEntity> withCategories(List<String> categoryNames, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(categoryNames);
if (cleaned.isEmpty()) return cb.conjunction();
return buildManyToManySpec(root, query, cb, cleaned, mode,
"metadata", "categories", "name");
};
}
public static Specification<BookEntity> withPublisher(String publisher) {
return withPublishers(publisher == null ? List.of() : List.of(publisher), "or");
}
/**
* Filter books by multiple publishers with mode support.
*/
public static Specification<BookEntity> withPublishers(List<String> publishers, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(publishers);
if (cleaned.isEmpty()) return cb.conjunction();
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "publisher");
};
}
public static Specification<BookEntity> withTag(String tagName) {
return withTags(tagName == null ? List.of() : List.of(tagName), "or");
}
/**
* Filter books by multiple tags with mode support.
*/
public static Specification<BookEntity> withTags(List<String> tagNames, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(tagNames);
if (cleaned.isEmpty()) return cb.conjunction();
return buildManyToManySpec(root, query, cb, cleaned, mode,
"metadata", "tags", "name");
};
}
public static Specification<BookEntity> withMood(String moodName) {
return withMoods(moodName == null ? List.of() : List.of(moodName), "or");
}
/**
* Filter books by multiple moods with mode support.
*/
public static Specification<BookEntity> withMoods(List<String> moodNames, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(moodNames);
if (cleaned.isEmpty()) return cb.conjunction();
return buildManyToManySpec(root, query, cb, cleaned, mode,
"metadata", "moods", "name");
};
}
public static Specification<BookEntity> withNarrator(String narrator) {
return withNarrators(narrator == null ? List.of() : List.of(narrator), "or");
}
/**
* Filter books by multiple narrators with mode support.
*/
public static Specification<BookEntity> withNarrators(List<String> narrators, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(narrators);
if (cleaned.isEmpty()) return cb.conjunction();
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "narrator");
};
}
public static Specification<BookEntity> unshelved() {
return (root, query, cb) -> {
Subquery<Long> subquery = query.subquery(Long.class);
Root<BookEntity> subRoot = subquery.correlate(root);
Join<BookEntity, ShelfEntity> shelvesJoin = subRoot.join("shelves", JoinType.INNER);
subquery.select(cb.literal(1L));
return cb.not(cb.exists(subquery));
};
}
private static List<String> cleanLowerCase(List<String> values) {
if (values == null) return List.of();
return values.stream()
.filter(s -> s != null && !s.isBlank())
.map(s -> s.trim().toLowerCase())
.toList();
}
/**
* Builds a specification for a scalar field on BookMetadataEntity (language, seriesName, publisher, narrator).
* OR = metadata field IN (values)
* AND = impossible for scalar fields with multiple values (treated as OR since a scalar can only be one value)
* NOT = metadata field NOT IN (values)
*/
private static Predicate buildMetadataFieldSpec(
Root<BookEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
List<String> values, String mode, String fieldName) {
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
Expression<String> fieldExpr = cb.lower(metadataJoin.get(fieldName));
if ("not".equals(mode)) {
return fieldExpr.in(values).not();
}
// Both "or" and "and" use IN for scalar fields (a single field can only match one value)
return fieldExpr.in(values);
}
/**
* Builds a specification for a many-to-many collection (authors, categories, tags, moods).
* Uses EXISTS subqueries to avoid DISTINCT and cartesian product issues.
*
* OR = book has at least one related entity whose name is IN (values)
* AND = book has ALL of the named entities (one EXISTS per value)
* NOT = book has NONE of the named entities
*/
private static Predicate buildManyToManySpec(
Root<BookEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
List<String> values, String mode,
String metadataAttr, String collectionAttr, String nameAttr) {
if ("and".equals(mode)) {
// AND: book must have ALL values one EXISTS subquery per value
List<Predicate> predicates = new ArrayList<>();
for (String value : values) {
Subquery<Long> sub = query.subquery(Long.class);
Root<BookMetadataEntity> metaRoot = sub.from(BookMetadataEntity.class);
Join<?, ?> collJoin = metaRoot.join(collectionAttr, JoinType.INNER);
sub.select(cb.literal(1L))
.where(
cb.equal(metaRoot.get("id"), root.get("id")),
cb.equal(cb.lower(collJoin.get(nameAttr)), value)
);
predicates.add(cb.exists(sub));
}
return cb.and(predicates.toArray(new Predicate[0]));
}
// OR or NOT: single EXISTS subquery with IN clause
Subquery<Long> sub = query.subquery(Long.class);
Root<BookMetadataEntity> metaRoot = sub.from(BookMetadataEntity.class);
Join<?, ?> collJoin = metaRoot.join(collectionAttr, JoinType.INNER);
sub.select(cb.literal(1L))
.where(
cb.equal(metaRoot.get("id"), root.get("id")),
cb.lower(collJoin.get(nameAttr)).in(values)
);
if ("not".equals(mode)) {
return cb.not(cb.exists(sub));
}
return cb.exists(sub);
}
@SafeVarargs
public static Specification<BookEntity> combine(Specification<BookEntity>... specs) {
Specification<BookEntity> result = (root, query, cb) -> cb.conjunction();
@@ -23,6 +23,7 @@ import java.util.Set;
@AllArgsConstructor
@DynamicUpdate
@Table(name = "book_metadata")
@BatchSize(size = 20)
public class BookMetadataEntity {
@Id
@@ -9,7 +9,7 @@ import org.booklore.model.enums.LibraryOrganizationMode;
import org.booklore.model.enums.MetadataSource;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.BatchSize;
import java.util.*;
@Entity
@@ -19,6 +19,7 @@ import java.util.*;
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "library")
@BatchSize(size = 20)
public class LibraryEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@@ -33,12 +33,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
Optional<BookEntity> findByIdFull(@Param("id") Long id);
// Minimal graph for summary mapping: metadata (OneToOne), library (ManyToOne), bookFiles (OneToMany).
// metadata.authors is intentionally excluded — @BatchSize on BookMetadataEntity.authors
// triggers a batched query when first accessed, so no N+1 occurs.
@EntityGraph(attributePaths = { "metadata", "library", "bookFiles" })
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllForSummaryByIds(@Param("bookIds") Collection<Long> bookIds);
@EntityGraph(attributePaths = {"bookFiles", "metadata", "library", "libraryPath"})
@Query("SELECT b FROM BookEntity b JOIN b.bookFiles bf WHERE bf.currentHash = :currentHash AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)")
@@ -21,10 +21,12 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@Slf4j
@RequiredArgsConstructor
@Service
@@ -33,12 +35,14 @@ public class IconService {
private static final Pattern INVALID_FILENAME_CHARS_PATTERN = Pattern.compile("[^a-zA-Z0-9._-]");
private final AppProperties appProperties;
private final ConcurrentHashMap<String, String> svgCache = new ConcurrentHashMap<>();
private final Cache<String, String> svgCache = Caffeine.newBuilder()
.maximumSize(200)
.expireAfterAccess(java.time.Duration.ofHours(1))
.build();
private static final String ICONS_DIR = "icons";
private static final String SVG_DIR = "svg";
private static final String SVG_EXTENSION = ".svg";
private static final int MAX_CACHE_SIZE = 200;
private static final String SVG_START_TAG = "<svg";
private static final String XML_DECLARATION = "<?xml";
private static final String SVG_END_TAG = "</svg>";
@@ -109,7 +113,7 @@ public class IconService {
public String getSvgIcon(String name) {
String filename = normalizeFilename(name);
String cachedSvg = svgCache.get(filename);
String cachedSvg = svgCache.getIfPresent(filename);
if (cachedSvg != null) {
return cachedSvg;
@@ -146,7 +150,7 @@ public class IconService {
}
Files.delete(filePath);
svgCache.remove(filename);
svgCache.invalidate(filename);
log.info("SVG icon deleted successfully: {}", filename);
} catch (IOException e) {
@@ -192,10 +196,6 @@ public class IconService {
}
private void updateCache(String filename, String content) {
if (!svgCache.containsKey(filename) && svgCache.size() >= MAX_CACHE_SIZE) {
String firstKey = svgCache.keys().nextElement();
svgCache.remove(firstKey);
}
svgCache.put(filename, content);
}
@@ -236,7 +236,7 @@ public class IconService {
return sanitized.endsWith(SVG_EXTENSION) ? sanitized : sanitized + SVG_EXTENSION;
}
ConcurrentHashMap<String, String> getSvgCache() {
Cache<String, String> getSvgCache() {
return svgCache;
}
@@ -256,7 +256,14 @@ public class IconService {
try {
String filename = path.getFileName().toString();
String iconName = filename.replace(SVG_EXTENSION, "");
String content = svgCache.getOrDefault(filename, Files.readString(path));
String cached = svgCache.getIfPresent(filename);
String content;
if (cached != null) {
content = cached;
} else {
content = Files.readString(path);
svgCache.put(filename, content);
}
iconMap.put(iconName, content);
} catch (IOException e) {
log.warn("Failed to read icon: {}", path.getFileName(), e);
@@ -30,7 +30,7 @@ public class FilenamePatternExtractor {
private static final Pattern PATTERN = Pattern.compile("[,;&]");
private final BookdropFileRepository bookdropFileRepository;
private final BookdropMetadataHelper metadataHelper;
private final ExecutorService regexExecutor;
private final ExecutorService regexExecutor = Executors.newVirtualThreadPerTaskExecutor();
private static final int PREVIEW_FILE_LIMIT = 5;
private static final long REGEX_TIMEOUT_SECONDS = 5;
@@ -26,6 +26,8 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tools.jackson.databind.ObjectMapper;
import org.booklore.exception.APIException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@@ -44,13 +46,12 @@ public class MagicShelfBookService {
private final ContentRestrictionService contentRestrictionService;
private final ObjectMapper objectMapper;
private record ShelfAccess(MagicShelfEntity shelf, BookLoreUserEntity user) {}
@Transactional(readOnly = true)
public Page<Book> getBooksByMagicShelfId(Long userId, Long magicShelfId, int page, int size) {
MagicShelfEntity shelf = validateMagicShelfAccess(userId, magicShelfId);
Specification<BookEntity> specification = toSpecification(userId, magicShelfId);
try {
GroupRule groupRule = objectMapper.readValue(shelf.getFilterJson(), GroupRule.class);
Specification<BookEntity> specification = ruleEvaluatorService.toSpecification(groupRule, userId);
specification = specification.and(createLibraryFilterSpecification(userId));
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
Page<BookEntity> booksPage = bookRepository.findAll(specification, pageable);
@@ -61,27 +62,45 @@ public class MagicShelfBookService {
.map(book -> filterBook(book, userId))
.toList();
return new PageImpl<>(books, pageable, booksPage.getTotalElements());
} catch (APIException e) {
throw e;
} catch (Exception e) {
log.error("Failed to parse or execute magic shelf rules", e);
throw new RuntimeException("Failed to parse or execute magic shelf rules: " + e.getMessage(), e);
}
}
public Specification<BookEntity> toSpecification(Long userId, Long magicShelfId) {
ShelfAccess access = validateMagicShelfAccess(userId, magicShelfId);
try {
GroupRule groupRule = objectMapper.readValue(access.shelf().getFilterJson(), GroupRule.class);
Specification<BookEntity> specification = ruleEvaluatorService.toSpecification(groupRule, userId);
return specification.and(createLibraryFilterSpecification(access.user()));
} catch (APIException e) {
throw e;
} catch (Exception e) {
log.error("Failed to parse magic shelf rules", e);
throw new RuntimeException("Failed to parse magic shelf rules: " + e.getMessage(), e);
}
}
public List<Long> getBookIdsByMagicShelfId(Long userId, Long magicShelfId) {
return getBookIdsByMagicShelfId(userId, magicShelfId, Integer.MAX_VALUE);
}
public List<Long> getBookIdsByMagicShelfId(Long userId, Long magicShelfId, int limit) {
MagicShelfEntity shelf = validateMagicShelfAccess(userId, magicShelfId);
ShelfAccess access = validateMagicShelfAccess(userId, magicShelfId);
try {
GroupRule groupRule = objectMapper.readValue(shelf.getFilterJson(), GroupRule.class);
GroupRule groupRule = objectMapper.readValue(access.shelf().getFilterJson(), GroupRule.class);
Specification<BookEntity> specification = ruleEvaluatorService.toSpecification(groupRule, userId);
specification = specification.and(createLibraryFilterSpecification(userId));
specification = specification.and(createLibraryFilterSpecification(access.user()));
Pageable pageable = PageRequest.of(0, limit);
Page<BookEntity> booksPage = bookRepository.findAll(specification, pageable);
List<BookEntity> filtered = contentRestrictionService.applyRestrictions(booksPage.getContent(), userId);
return filtered.stream().map(BookEntity::getId).toList();
} catch (APIException e) {
throw e;
} catch (Exception e) {
log.error("Failed to parse or execute magic shelf rules", e);
throw new RuntimeException("Failed to parse or execute magic shelf rules: " + e.getMessage(), e);
@@ -94,7 +113,7 @@ public class MagicShelfBookService {
.orElse("Magic Shelf Books");
}
private MagicShelfEntity validateMagicShelfAccess(Long userId, Long magicShelfId) {
private ShelfAccess validateMagicShelfAccess(Long userId, Long magicShelfId) {
MagicShelfEntity shelf = magicShelfRepository.findById(magicShelfId)
.orElseThrow(() -> ApiError.MAGIC_SHELF_NOT_FOUND.createException(magicShelfId));
@@ -102,7 +121,7 @@ public class MagicShelfBookService {
if (!shelf.isPublic()) {
throw ApiError.FORBIDDEN.createException("You are not allowed to access this magic shelf");
}
return shelf;
return new ShelfAccess(shelf, null);
}
BookLoreUserEntity entity = userRepository.findByIdWithDetails(userId)
@@ -121,26 +140,25 @@ public class MagicShelfBookService {
throw ApiError.FORBIDDEN.createException("You are not allowed to access this magic shelf");
}
return shelf;
return new ShelfAccess(shelf, entity);
}
private Specification<BookEntity> createLibraryFilterSpecification(Long userId) {
return (root, query, cb) -> {
BookLoreUserEntity entity = userRepository.findByIdWithDetails(userId)
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
private Specification<BookEntity> createLibraryFilterSpecification(BookLoreUserEntity entity) {
if (entity == null) {
return (root, query, cb) -> cb.conjunction();
}
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
if (user.getPermissions() != null && user.getPermissions().isAdmin()) {
return cb.conjunction();
}
if (user.getPermissions() != null && user.getPermissions().isAdmin()) {
return (root, query, cb) -> cb.conjunction();
}
Set<Long> userLibraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
Set<Long> userLibraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
return root.get("library").get("id").in(userLibraryIds);
};
return (root, query, cb) -> root.get("library").get("id").in(userLibraryIds);
}
private Book filterBook(Book dto, Long userId) {
@@ -19,36 +19,38 @@ import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@Slf4j
@Service
@RequiredArgsConstructor
public class PdfReaderService {
private static final int MAX_CACHE_ENTRIES = 50;
private static final int MAX_CACHE_ENTRIES = 15;
private static final float DEFAULT_DPI = 200f;
private final BookRepository bookRepository;
private final Map<String, CachedPdfMetadata> metadataCache = new ConcurrentHashMap<>();
private final Cache<String, CachedPdfMetadata> metadataCache = Caffeine.newBuilder()
.maximumSize(MAX_CACHE_ENTRIES)
.expireAfterAccess(Duration.ofMinutes(30))
.build();
private static class CachedPdfMetadata {
final int pageCount;
final long lastModified;
final List<PdfOutlineItem> outline;
volatile long lastAccessed;
CachedPdfMetadata(int pageCount, long lastModified, List<PdfOutlineItem> outline) {
this.pageCount = pageCount;
this.lastModified = lastModified;
this.outline = outline;
this.lastAccessed = System.currentTimeMillis();
}
}
@@ -120,16 +122,14 @@ public class PdfReaderService {
private CachedPdfMetadata getCachedMetadata(Path pdfPath) throws IOException {
String cacheKey = pdfPath.toString();
long currentModified = Files.getLastModifiedTime(pdfPath).toMillis();
CachedPdfMetadata cached = metadataCache.get(cacheKey);
CachedPdfMetadata cached = metadataCache.getIfPresent(cacheKey);
if (cached != null && cached.lastModified == currentModified) {
cached.lastAccessed = System.currentTimeMillis();
log.debug("Cache hit for PDF: {}", pdfPath.getFileName());
return cached;
}
log.debug("Cache miss for PDF: {}, scanning...", pdfPath.getFileName());
CachedPdfMetadata newMetadata = scanPdfMetadata(pdfPath);
metadataCache.put(cacheKey, newMetadata);
evictOldestCacheEntries();
return newMetadata;
}
@@ -190,21 +190,6 @@ public class PdfReaderService {
}
}
private void evictOldestCacheEntries() {
if (metadataCache.size() <= MAX_CACHE_ENTRIES) {
return;
}
List<String> keysToRemove = metadataCache.entrySet().stream()
.sorted(Comparator.comparingLong(e -> e.getValue().lastAccessed))
.limit(metadataCache.size() - MAX_CACHE_ENTRIES)
.map(Map.Entry::getKey)
.toList();
keysToRemove.forEach(key -> {
metadataCache.remove(key);
log.debug("Evicted cache entry: {}", key);
});
}
private void renderPageToStream(Path pdfPath, int page, OutputStream outputStream) throws IOException {
try (PdfDocument doc = PdfDocument.open(pdfPath)) {
// page is 1-based from the API, renderPageToBytes expects 0-based
@@ -12,11 +12,13 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import tools.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.time.Duration;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@RequiredArgsConstructor
@Service
@@ -26,25 +28,28 @@ public class DefaultSettingInitializer {
private final UserRepository userRepository;
private final ObjectMapper objectMapper;
private final DefaultUserSettingsProvider settingsProvider;
private static final Set<Long> initializedUsers = Collections.newSetFromMap(new ConcurrentHashMap<>());
private static final Cache<Long, Boolean> initializedUsers = Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(Duration.ofHours(24))
.build();
private static final ConcurrentHashMap<Long, Lock> userLocks = new ConcurrentHashMap<>();
@Transactional
public void ensureDefaultSettings(BookLoreUser bookLoreUser) {
if (initializedUsers.contains(bookLoreUser.getId())) {
if (initializedUsers.getIfPresent(bookLoreUser.getId()) != null) {
return;
}
Lock lock = userLocks.computeIfAbsent(bookLoreUser.getId(), _ -> new ReentrantLock());
lock.lock();
try {
if (initializedUsers.contains(bookLoreUser.getId())) return;
if (initializedUsers.getIfPresent(bookLoreUser.getId()) != null) return;
BookLoreUserEntity user = userRepository.findByIdWithSettings(bookLoreUser.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
for (UserSettingKey key : settingsProvider.getAllKeys()) {
addSettingIfMissing(user, key, settingsProvider.getDefaultValue(key));
}
patchPerBookSetting(user);
userRepository.save(user);
initializedUsers.add(bookLoreUser.getId());
initializedUsers.put(bookLoreUser.getId(), Boolean.TRUE);
} finally {
lock.unlock();
userLocks.remove(bookLoreUser.getId());
@@ -90,4 +95,3 @@ public class DefaultSettingInitializer {
});
}
}
@@ -1,25 +1,29 @@
package org.booklore.task;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.time.Duration;
@Component
public class TaskCancellationManager {
private final Set<String> cancelledTasks = ConcurrentHashMap.newKeySet();
private final Cache<String, Boolean> cancelledTasks = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofHours(24))
.build();
public void cancelTask(String taskId) {
cancelledTasks.add(taskId);
cancelledTasks.put(taskId, Boolean.TRUE);
}
public boolean isTaskCancelled(String taskId) {
return cancelledTasks.contains(taskId);
return cancelledTasks.getIfPresent(taskId) != null;
}
public void clearCancellation(String taskId) {
cancelledTasks.remove(taskId);
cancelledTasks.invalidate(taskId);
}
}
@@ -23,7 +23,6 @@ public class EpubCfiService {
this.documentCache = Caffeine.newBuilder()
.maximumSize(10)
.expireAfterAccess(Duration.ofMinutes(5))
.softValues()
.build();
}
@@ -66,8 +66,8 @@ spring:
max-lifetime: 580000 # 9.6 minutes (avoid DB-side connection cuts)
connection-test-query: SELECT 1
connection-timeout: 30000 # 30s to acquire a connection before timeout
maximum-pool-size: 10 # Virtual threads don't need large pools
minimum-idle: 2 # Minimal warm connections; virtual threads handle bursts
maximum-pool-size: 5 # Virtual threads don't need large pools; 5 is enough for a self-hosted app
minimum-idle: 1 # Minimal warm connections; virtual threads handle bursts
idle-timeout: 300000 # 5 minutes before idle connections are closed
jpa:
open-in-view: false
@@ -0,0 +1,16 @@
-- Indexes for filterable columns used by AppBookSpecification.
-- All additive; safe to run on existing data without downtime.
CREATE INDEX IF NOT EXISTS idx_author_name ON author (name);
CREATE INDEX IF NOT EXISTS idx_book_metadata_language ON book_metadata (language);
CREATE INDEX IF NOT EXISTS idx_book_metadata_publisher ON book_metadata (publisher);
CREATE INDEX IF NOT EXISTS idx_book_metadata_series_name ON book_metadata (series_name);
CREATE INDEX IF NOT EXISTS idx_book_metadata_narrator ON book_metadata (narrator);
CREATE INDEX IF NOT EXISTS idx_category_name ON category (name);
CREATE INDEX IF NOT EXISTS idx_tag_name ON tag (name);
CREATE INDEX IF NOT EXISTS idx_mood_name ON mood (name);
-- Composite index for personal-rating filter subqueries
CREATE INDEX IF NOT EXISTS idx_user_book_progress_rating ON user_book_progress (user_id, personal_rating, book_id);
@@ -43,8 +43,8 @@ class AppFilterControllerTest {
ResponseEntity<AppFilterOptions> 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());
assertEquals(1, response.getBody().authors().size());
assertEquals("Author B", response.getBody().authors().getFirst().name());
verify(mobileBookService).getFilterOptions(5L, null, null);
}
@@ -56,7 +56,7 @@ class AppFilterControllerTest {
ResponseEntity<AppFilterOptions> response = controller.getFilterOptions(null, 10L, null);
assertEquals(200, response.getStatusCode().value());
assertTrue(response.getBody().getAuthors().isEmpty());
assertTrue(response.getBody().authors().isEmpty());
verify(mobileBookService).getFilterOptions(null, 10L, null);
}
@@ -68,16 +68,16 @@ class AppFilterControllerTest {
ResponseEntity<AppFilterOptions> response = controller.getFilterOptions(null, null, 7L);
assertEquals(200, response.getStatusCode().value());
assertEquals("Author C", response.getBody().getAuthors().getFirst().getName());
assertEquals("Author C", response.getBody().authors().getFirst().name());
verify(mobileBookService).getFilterOptions(null, null, 7L);
}
private AppFilterOptions buildOptions(List<String> authorNames, List<String> fileTypes, List<String> langCodes) {
List<AppFilterOptions.AuthorOption> authors = authorNames.stream()
.map(name -> AppFilterOptions.AuthorOption.builder().name(name).count(1L).build())
List<AppFilterOptions.CountedOption> authors = authorNames.stream()
.map(name -> new AppFilterOptions.CountedOption(name, 1L))
.toList();
List<AppFilterOptions.LanguageOption> languages = langCodes.stream()
.map(code -> AppFilterOptions.LanguageOption.builder().code(code).label(code).count(1L).build())
.map(code -> new AppFilterOptions.LanguageOption(code, code, 1L))
.toList();
return AppFilterOptions.builder()
.authors(authors)
@@ -7,10 +7,10 @@ import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.app.dto.AppFilterOptions;
import org.booklore.app.mapper.AppBookMapper;
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.BookEntity;
import org.booklore.model.entity.ShelfEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookRepository;
@@ -25,9 +25,12 @@ 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 org.springframework.data.jpa.domain.Specification;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Root;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@@ -75,10 +78,10 @@ class AppBookServiceFilterOptionsTest {
AppFilterOptions result = service.getFilterOptions(null, null, null);
assertNotNull(result);
assertNotNull(result.getAuthors());
assertNotNull(result.getLanguages());
assertNotNull(result.getFileTypes());
assertFalse(result.getReadStatuses().isEmpty());
assertNotNull(result.authors());
assertNotNull(result.languages());
assertNotNull(result.fileTypes());
assertFalse(result.readStatuses().isEmpty());
}
// -------------------------------------------------------------------------
@@ -93,7 +96,7 @@ class AppBookServiceFilterOptionsTest {
AppFilterOptions result = service.getFilterOptions(5L, null, null);
assertNotNull(result);
verify(entityManager, times(3)).createQuery(anyString(), any(Class.class));
verify(entityManager, times(9)).createQuery(anyString(), any(Class.class));
}
@Test
@@ -168,35 +171,33 @@ class AppBookServiceFilterOptionsTest {
@Test
void getFilterOptions_withMagicShelfId_emptyResult_returnsEmptyOptions() {
mockAdminUser();
mockMagicShelfBooks(7L, Collections.emptyList());
mockMagicShelfSpec(7L, Collections.emptyList());
AppFilterOptions result = service.getFilterOptions(null, null, 7L);
assertNotNull(result);
assertTrue(result.getAuthors().isEmpty());
assertTrue(result.getLanguages().isEmpty());
assertTrue(result.getFileTypes().isEmpty());
assertFalse(result.getReadStatuses().isEmpty());
assertTrue(result.authors().isEmpty());
assertTrue(result.languages().isEmpty());
assertTrue(result.fileTypes().isEmpty());
assertFalse(result.readStatuses().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));
mockMagicShelfSpec(7L, List.of(100L, 200L));
mockJpqlQueries();
AppFilterOptions result = service.getFilterOptions(null, null, 7L);
assertNotNull(result);
verify(magicShelfBookService).getBooksByMagicShelfId(eq(userId), eq(7L), eq(0), anyInt());
verify(magicShelfBookService).toSpecification(eq(userId), eq(7L));
}
@Test
void getFilterOptions_withMagicShelfId_serviceThrows_propagatesException() {
mockAdminUser();
when(magicShelfBookService.getBooksByMagicShelfId(eq(userId), eq(7L), eq(0), anyInt()))
when(magicShelfBookService.toSpecification(eq(userId), eq(7L)))
.thenThrow(new RuntimeException("Magic shelf not found"));
assertThrows(RuntimeException.class, () -> service.getFilterOptions(null, null, 7L));
@@ -230,30 +231,44 @@ class AppBookServiceFilterOptionsTest {
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 mockMagicShelfSpec(Long magicShelfId, List<Long> bookIds) {
Specification<BookEntity> mockSpec = mock(Specification.class);
when(magicShelfBookService.toSpecification(eq(userId), eq(magicShelfId)))
.thenReturn(mockSpec);
jakarta.persistence.criteria.Predicate mockPredicate = mock(jakarta.persistence.criteria.Predicate.class);
CriteriaBuilder cb = mock(CriteriaBuilder.class);
CriteriaQuery<Long> cq = mock(CriteriaQuery.class);
Root<BookEntity> root = mock(Root.class);
Path<Long> idPath = mock(Path.class);
jakarta.persistence.TypedQuery<Long> typedQuery = mock(jakarta.persistence.TypedQuery.class);
when(entityManager.getCriteriaBuilder()).thenReturn(cb);
when(cb.createQuery(Long.class)).thenReturn(cq);
when(cq.from(BookEntity.class)).thenReturn(root);
when(root.get("id")).thenReturn((Path) idPath);
when(cq.select(idPath)).thenReturn(cq);
when(mockSpec.toPredicate(root, cq, cb)).thenReturn(mockPredicate);
when(cq.where(mockPredicate)).thenReturn(cq);
when(entityManager.createQuery(cq)).thenReturn(typedQuery);
when(typedQuery.setMaxResults(anyInt())).thenReturn(typedQuery);
when(typedQuery.getResultList()).thenReturn(bookIds);
}
@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<Tuple> tupleQuery = mock(TypedQuery.class);
when(tupleQuery.setParameter(anyString(), any())).thenReturn(tupleQuery);
when(tupleQuery.setMaxResults(anyInt())).thenReturn(tupleQuery);
when(tupleQuery.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);
.thenReturn(tupleQuery);
when(entityManager.createQuery(anyString(), eq(BookFileType.class)))
.thenReturn(ftQuery);
}
@@ -46,7 +46,7 @@ class IconServiceTest {
Files.deleteIfExists(entry);
}
}
iconService.getSvgCache().clear();
iconService.getSvgCache().invalidateAll();
}
@AfterAll
@@ -164,7 +164,7 @@ class IconServiceTest {
@Test
void cacheEviction_worksWhenMaxSizeExceeded() {
iconService.getSvgCache().clear();
iconService.getSvgCache().invalidateAll();
for (int i = 0; i < 1002; i++) {
SvgIconCreateRequest req = new SvgIconCreateRequest();
@@ -173,7 +173,8 @@ class IconServiceTest {
iconService.saveSvgIcon(req);
}
assertEquals(1002, iconService.getIconNames(0, 2000).getContent().size());
assertTrue(iconService.getSvgCache().size() <= 1000);
iconService.getSvgCache().cleanUp();
assertTrue(iconService.getSvgCache().estimatedSize() <= 200);
}
@Test
@@ -183,11 +184,11 @@ class IconServiceTest {
req.setSvgData(SVG_DATA);
iconService.saveSvgIcon(req);
int initialSize = iconService.getSvgCache().size();
long initialSize = iconService.getSvgCache().estimatedSize();
req.setSvgData("<svg><circle r=\"50\"/></svg>");
assertThrows(APIException.class, () -> iconService.saveSvgIcon(req));
assertEquals(initialSize, iconService.getSvgCache().size());
assertEquals(initialSize, iconService.getSvgCache().estimatedSize());
}
}