feat(mobile): add author and series endpoints

This commit is contained in:
acx10
2026-02-28 18:39:52 -07:00
parent e26ac45ae9
commit a1666932cb
12 changed files with 1831 additions and 0 deletions
@@ -0,0 +1,56 @@
package org.booklore.mobile.controller;
import org.booklore.mobile.dto.MobileAuthorDetail;
import org.booklore.mobile.dto.MobileAuthorSummary;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.mobile.service.MobileAuthorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@AllArgsConstructor
@RestController
@RequestMapping("/api/mobile/v1/authors")
@Tag(name = "Mobile Authors", description = "Mobile-optimized endpoints for browsing authors")
public class MobileAuthorController {
private final MobileAuthorService mobileAuthorService;
@Operation(summary = "Get paginated author list",
description = "Retrieve a paginated list of authors with optional filtering by library, search text, and photo availability.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Authors retrieved successfully"),
@ApiResponse(responseCode = "403", description = "Access denied")
})
@GetMapping
public ResponseEntity<MobilePageResponse<MobileAuthorSummary>> getAuthors(
@Parameter(description = "Page number (0-indexed)") @RequestParam(required = false, defaultValue = "0") Integer page,
@Parameter(description = "Page size (max 50)") @RequestParam(required = false, defaultValue = "30") Integer size,
@Parameter(description = "Sort field (name, bookCount, recent)") @RequestParam(required = false, defaultValue = "name") String sort,
@Parameter(description = "Sort direction (asc, desc)") @RequestParam(required = false, defaultValue = "asc") String dir,
@Parameter(description = "Filter by library ID") @RequestParam(required = false) Long libraryId,
@Parameter(description = "Search by author name") @RequestParam(required = false) String search,
@Parameter(description = "Filter by photo availability") @RequestParam(required = false) Boolean hasPhoto) {
return ResponseEntity.ok(mobileAuthorService.getAuthors(page, size, sort, dir, libraryId, search, hasPhoto));
}
@Operation(summary = "Get author details",
description = "Retrieve full details for a specific author including description and book count.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Author details retrieved successfully"),
@ApiResponse(responseCode = "403", description = "Access denied"),
@ApiResponse(responseCode = "404", description = "Author not found")
})
@GetMapping("/{authorId}")
public ResponseEntity<MobileAuthorDetail> getAuthorDetail(
@Parameter(description = "Author ID") @PathVariable Long authorId) {
return ResponseEntity.ok(mobileAuthorService.getAuthorDetail(authorId));
}
}
@@ -0,0 +1,50 @@
package org.booklore.mobile.controller;
import lombok.AllArgsConstructor;
import org.booklore.mobile.dto.MobileBookSummary;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.mobile.dto.MobileSeriesSummary;
import org.booklore.mobile.service.MobileSeriesService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@AllArgsConstructor
@RestController
@RequestMapping("/api/mobile/v1/series")
public class MobileSeriesController {
private final MobileSeriesService mobileSeriesService;
@GetMapping
public ResponseEntity<MobilePageResponse<MobileSeriesSummary>> getSeries(
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size,
@RequestParam(required = false, defaultValue = "recentlyAdded") String sort,
@RequestParam(required = false, defaultValue = "desc") String dir,
@RequestParam(required = false) Long libraryId,
@RequestParam(required = false) String search,
@RequestParam(required = false) String status) {
boolean inProgressOnly = "in-progress".equalsIgnoreCase(status);
MobilePageResponse<MobileSeriesSummary> response = mobileSeriesService.getSeries(
page, size, sort, dir, libraryId, search, inProgressOnly);
return ResponseEntity.ok(response);
}
@GetMapping("/{seriesName}/books")
public ResponseEntity<MobilePageResponse<MobileBookSummary>> getSeriesBooks(
@PathVariable String seriesName,
@RequestParam(required = false, defaultValue = "0") Integer page,
@RequestParam(required = false, defaultValue = "20") Integer size,
@RequestParam(required = false, defaultValue = "seriesNumber") String sort,
@RequestParam(required = false, defaultValue = "asc") String dir,
@RequestParam(required = false) Long libraryId) {
MobilePageResponse<MobileBookSummary> response = mobileSeriesService.getSeriesBooks(
seriesName, page, size, sort, dir, libraryId);
return ResponseEntity.ok(response);
}
}
@@ -0,0 +1,21 @@
package org.booklore.mobile.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileAuthorDetail {
private Long id;
private String name;
private String description;
private String asin;
private int bookCount;
private boolean hasPhoto;
}
@@ -0,0 +1,20 @@
package org.booklore.mobile.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileAuthorSummary {
private Long id;
private String name;
private String asin;
private int bookCount;
private boolean hasPhoto;
}
@@ -0,0 +1,22 @@
package org.booklore.mobile.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
import java.time.Instant;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MobileSeriesSummary {
private String seriesName;
private int bookCount;
private Integer seriesTotal;
private List<String> authors;
private int booksRead;
private Instant latestAddedOn;
private List<SeriesCoverBook> coverBooks;
}
@@ -0,0 +1,18 @@
package org.booklore.mobile.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
import java.time.Instant;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SeriesCoverBook {
private Long bookId;
private Instant coverUpdatedOn;
private Float seriesNumber;
private String primaryFileType;
}
@@ -0,0 +1,221 @@
package org.booklore.mobile.service;
import lombok.AllArgsConstructor;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.mobile.dto.MobileAuthorDetail;
import org.booklore.mobile.dto.MobileAuthorSummary;
import org.booklore.mobile.dto.MobilePageResponse;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.AuthorEntity;
import org.booklore.repository.AuthorRepository;
import org.booklore.util.FileService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class MobileAuthorService {
private static final int DEFAULT_PAGE_SIZE = 30;
private static final int MAX_PAGE_SIZE = 50;
private final AuthorRepository authorRepository;
private final AuthenticationService authenticationService;
private final FileService fileService;
private final EntityManager entityManager;
@Transactional(readOnly = true)
public MobilePageResponse<MobileAuthorSummary> getAuthors(
Integer page,
Integer size,
String sortBy,
String sortDir,
Long libraryId,
String search,
Boolean hasPhoto) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
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;
StringBuilder whereClause = new StringBuilder(" WHERE (1=1)");
buildLibraryFilter(whereClause, accessibleLibraryIds, libraryId);
buildSearchFilter(whereClause, search);
String fromClause = " FROM AuthorEntity a LEFT JOIN a.bookMetadataEntityList bm LEFT JOIN bm.book b";
// Count query
String countJpql = "SELECT COUNT(DISTINCT a.id)" + fromClause + whereClause;
TypedQuery<Long> countQuery = entityManager.createQuery(countJpql, Long.class);
setQueryParams(countQuery, accessibleLibraryIds, libraryId, search);
long totalElements = countQuery.getSingleResult();
if (totalElements == 0) {
return MobilePageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
}
// Data query with book count
String orderClause = buildOrderClause(sortBy, sortDir);
String dataJpql = "SELECT a, COUNT(DISTINCT bm.id)" + fromClause + whereClause
+ " GROUP BY a" + orderClause;
TypedQuery<Object[]> dataQuery = entityManager.createQuery(dataJpql, Object[].class);
setQueryParams(dataQuery, accessibleLibraryIds, libraryId, search);
dataQuery.setFirstResult(pageNum * pageSize);
dataQuery.setMaxResults(pageSize);
List<Object[]> results = dataQuery.getResultList();
List<MobileAuthorSummary> summaries = results.stream()
.map(row -> {
AuthorEntity author = (AuthorEntity) row[0];
long bookCount = (Long) row[1];
boolean authorHasPhoto = Files.exists(Paths.get(fileService.getAuthorThumbnailFile(author.getId())));
return MobileAuthorSummary.builder()
.id(author.getId())
.name(author.getName())
.asin(author.getAsin())
.bookCount((int) bookCount)
.hasPhoto(authorHasPhoto)
.build();
})
.collect(Collectors.toList());
// Post-filter by hasPhoto if requested
if (hasPhoto != null) {
summaries = summaries.stream()
.filter(s -> s.isHasPhoto() == hasPhoto)
.collect(Collectors.toList());
// Adjust total count for hasPhoto filter — requires a separate count
long filteredTotal = countAuthorsWithPhotoFilter(accessibleLibraryIds, libraryId, search, hasPhoto);
return MobilePageResponse.of(summaries, pageNum, pageSize, filteredTotal);
}
return MobilePageResponse.of(summaries, pageNum, pageSize, totalElements);
}
@Transactional(readOnly = true)
public MobileAuthorDetail getAuthorDetail(Long authorId) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
AuthorEntity author = authorRepository.findById(authorId)
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
// Verify access for non-admin users
if (accessibleLibraryIds != null) {
if (accessibleLibraryIds.isEmpty() || !authorRepository.existsByIdAndLibraryIds(authorId, accessibleLibraryIds)) {
throw ApiError.AUTHOR_NOT_FOUND.createException(authorId);
}
}
// Count books accessible to this user
int bookCount = countAccessibleBooks(authorId, accessibleLibraryIds);
boolean authorHasPhoto = Files.exists(Paths.get(fileService.getAuthorThumbnailFile(author.getId())));
return MobileAuthorDetail.builder()
.id(author.getId())
.name(author.getName())
.description(author.getDescription())
.asin(author.getAsin())
.bookCount(bookCount)
.hasPhoto(authorHasPhoto)
.build();
}
private int countAccessibleBooks(Long authorId, Set<Long> accessibleLibraryIds) {
StringBuilder jpql = new StringBuilder(
"SELECT COUNT(DISTINCT bm.id) FROM AuthorEntity a JOIN a.bookMetadataEntityList bm JOIN bm.book b"
+ " WHERE a.id = :authorId AND (b.deleted IS NULL OR b.deleted = false)"
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)");
if (accessibleLibraryIds != null) {
jpql.append(" AND b.library.id IN :libraryIds");
}
TypedQuery<Long> query = entityManager.createQuery(jpql.toString(), Long.class);
query.setParameter("authorId", authorId);
if (accessibleLibraryIds != null) {
query.setParameter("libraryIds", accessibleLibraryIds);
}
return query.getSingleResult().intValue();
}
private long countAuthorsWithPhotoFilter(Set<Long> accessibleLibraryIds, Long libraryId, String search, boolean hasPhoto) {
// Since hasPhoto is file-system based, we need to count all matching authors
// and check their photos. For large datasets this could be optimized with a DB column.
StringBuilder whereClause = new StringBuilder(" WHERE (1=1)");
buildLibraryFilter(whereClause, accessibleLibraryIds, libraryId);
buildSearchFilter(whereClause, search);
String jpql = "SELECT DISTINCT a FROM AuthorEntity a LEFT JOIN a.bookMetadataEntityList bm LEFT JOIN bm.book b"
+ whereClause;
TypedQuery<AuthorEntity> query = entityManager.createQuery(jpql, AuthorEntity.class);
setQueryParams(query, accessibleLibraryIds, libraryId, search);
return query.getResultList().stream()
.filter(a -> Files.exists(Paths.get(fileService.getAuthorThumbnailFile(a.getId()))) == hasPhoto)
.count();
}
private void buildLibraryFilter(StringBuilder whereClause, Set<Long> accessibleLibraryIds, Long libraryId) {
if (libraryId != null) {
whereClause.append(" AND b.library.id = :libraryId");
} else if (accessibleLibraryIds != null) {
whereClause.append(" AND b.library.id IN :libraryIds");
}
// Always filter out deleted/physical books when library filtering
whereClause.append(" AND (b.deleted IS NULL OR b.deleted = false)");
whereClause.append(" AND (b.isPhysical IS NULL OR b.isPhysical = false)");
}
private void buildSearchFilter(StringBuilder whereClause, String search) {
if (search != null && !search.trim().isEmpty()) {
whereClause.append(" AND LOWER(a.name) LIKE :search");
}
}
private String buildOrderClause(String sortBy, String sortDir) {
String direction = "asc".equalsIgnoreCase(sortDir) ? "ASC" : "DESC";
String field = switch (sortBy != null ? sortBy.toLowerCase() : "") {
case "name" -> "a.name";
case "bookcount", "book_count" -> "COUNT(DISTINCT bm.id)";
case "recent", "id" -> "a.id";
default -> "a.name";
};
return " ORDER BY " + field + " " + direction;
}
private void setQueryParams(TypedQuery<?> query, Set<Long> accessibleLibraryIds, Long libraryId, String search) {
if (libraryId != null) {
query.setParameter("libraryId", libraryId);
} else if (accessibleLibraryIds != null) {
query.setParameter("libraryIds", accessibleLibraryIds);
}
if (search != null && !search.trim().isEmpty()) {
query.setParameter("search", "%" + search.trim().toLowerCase() + "%");
}
}
private Set<Long> getAccessibleLibraryIds(BookLoreUser user) {
if (user.getPermissions().isAdmin()) {
return null;
}
if (user.getAssignedLibraries() == null || user.getAssignedLibraries().isEmpty()) {
return Collections.emptySet();
}
return user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
}
}
@@ -0,0 +1,390 @@
package org.booklore.mobile.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Tuple;
import lombok.AllArgsConstructor;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.mobile.dto.*;
import org.booklore.mobile.mapper.MobileBookMapper;
import org.booklore.mobile.specification.MobileBookSpecification;
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.repository.BookRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class MobileSeriesService {
private static final int DEFAULT_PAGE_SIZE = 20;
private static final int MAX_PAGE_SIZE = 50;
private final EntityManager entityManager;
private final AuthenticationService authenticationService;
private final BookRepository bookRepository;
private final UserBookProgressRepository userBookProgressRepository;
private final MobileBookMapper mobileBookMapper;
@Transactional(readOnly = true)
public MobilePageResponse<MobileSeriesSummary> getSeries(
Integer page,
Integer size,
String sortBy,
String sortDir,
Long libraryId,
String search,
boolean inProgressOnly) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
if (libraryId != null) {
validateLibraryAccess(accessibleLibraryIds, libraryId);
}
int pageNum = page != null && page >= 0 ? page : 0;
int pageSize = size != null && size > 0 ? Math.min(size, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
// Build WHERE clause fragments
String libraryClause = buildLibraryClause(accessibleLibraryIds, libraryId);
String searchClause = (search != null && !search.trim().isEmpty())
? " AND LOWER(m.seriesName) LIKE :searchPattern"
: "";
String havingClause = inProgressOnly
? " HAVING SUM(CASE WHEN p.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING) THEN 1 ELSE 0 END) > 0"
: "";
String orderBy = buildSeriesOrderBy(sortBy, sortDir, inProgressOnly);
// Phase 1: Aggregate query
String aggregateQuery = "SELECT m.seriesName, COUNT(b.id), MAX(m.seriesTotal), MAX(b.addedOn),"
+ " SUM(CASE WHEN p.readStatus = org.booklore.model.enums.ReadStatus.READ THEN 1 ELSE 0 END)"
+ (inProgressOnly ? ", MAX(p.lastReadTime)" : "")
+ " FROM BookEntity b JOIN b.metadata m"
+ " LEFT JOIN b.userBookProgress p ON p.user.id = :userId"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
+ " AND m.seriesName IS NOT NULL"
+ libraryClause
+ searchClause
+ " GROUP BY m.seriesName"
+ havingClause
+ " ORDER BY " + orderBy;
var aggregateQ = entityManager.createQuery(aggregateQuery, Tuple.class);
aggregateQ.setParameter("userId", userId);
setLibraryParams(aggregateQ, accessibleLibraryIds, libraryId);
if (!searchClause.isEmpty()) {
aggregateQ.setParameter("searchPattern", "%" + search.trim().toLowerCase() + "%");
}
aggregateQ.setFirstResult(pageNum * pageSize);
aggregateQ.setMaxResults(pageSize);
List<Tuple> aggregateResults = aggregateQ.getResultList();
// Count query
String countQuery = "SELECT COUNT(DISTINCT m.seriesName) FROM BookEntity b JOIN b.metadata m"
+ (inProgressOnly ? " LEFT JOIN b.userBookProgress p ON p.user.id = :userId" : "")
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
+ " AND m.seriesName IS NOT NULL"
+ libraryClause
+ searchClause;
if (inProgressOnly) {
// For in-progress, we need the HAVING filter in the count — use a subquery approach
String countWithHaving = "SELECT COUNT(*) FROM ("
+ "SELECT m.seriesName FROM BookEntity b JOIN b.metadata m"
+ " LEFT JOIN b.userBookProgress p ON p.user.id = :userId"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
+ " AND m.seriesName IS NOT NULL"
+ libraryClause
+ searchClause
+ " GROUP BY m.seriesName"
+ " HAVING SUM(CASE WHEN p.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING) THEN 1 ELSE 0 END) > 0"
+ ")";
// JPQL doesn't support subqueries in FROM — count via result list size instead
String countAlt = "SELECT m.seriesName FROM BookEntity b JOIN b.metadata m"
+ " LEFT JOIN b.userBookProgress p ON p.user.id = :userId"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
+ " AND m.seriesName IS NOT NULL"
+ libraryClause
+ searchClause
+ " GROUP BY m.seriesName"
+ " HAVING SUM(CASE WHEN p.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING) THEN 1 ELSE 0 END) > 0";
var countQ = entityManager.createQuery(countAlt, String.class);
countQ.setParameter("userId", userId);
setLibraryParams(countQ, accessibleLibraryIds, libraryId);
if (!searchClause.isEmpty()) {
countQ.setParameter("searchPattern", "%" + search.trim().toLowerCase() + "%");
}
long totalElements = countQ.getResultList().size();
return buildSeriesPage(aggregateResults, userId, accessibleLibraryIds, libraryId, inProgressOnly, pageNum, pageSize, totalElements);
}
var countQ = entityManager.createQuery(countQuery, Long.class);
if (inProgressOnly) {
countQ.setParameter("userId", userId);
}
setLibraryParams(countQ, accessibleLibraryIds, libraryId);
if (!searchClause.isEmpty()) {
countQ.setParameter("searchPattern", "%" + search.trim().toLowerCase() + "%");
}
long totalElements = countQ.getSingleResult();
return buildSeriesPage(aggregateResults, userId, accessibleLibraryIds, libraryId, inProgressOnly, pageNum, pageSize, totalElements);
}
private MobilePageResponse<MobileSeriesSummary> buildSeriesPage(
List<Tuple> aggregateResults,
Long userId,
Set<Long> accessibleLibraryIds,
Long libraryId,
boolean inProgressOnly,
int pageNum,
int pageSize,
long totalElements) {
if (aggregateResults.isEmpty()) {
return MobilePageResponse.of(Collections.emptyList(), pageNum, pageSize, totalElements);
}
List<String> seriesNames = aggregateResults.stream()
.map(t -> t.get(0, String.class))
.toList();
// Phase 2: Fetch books for enrichment
String libraryClause = buildLibraryClause(accessibleLibraryIds, libraryId);
String booksQuery = "SELECT b FROM BookEntity b"
+ " JOIN FETCH b.metadata m LEFT JOIN FETCH m.authors"
+ " LEFT JOIN FETCH b.bookFiles"
+ " WHERE m.seriesName IN :seriesNames"
+ " AND (b.deleted IS NULL OR b.deleted = false)"
+ " AND (b.isPhysical IS NULL OR b.isPhysical = false)"
+ libraryClause;
var booksQ = entityManager.createQuery(booksQuery, BookEntity.class);
booksQ.setParameter("seriesNames", seriesNames);
setLibraryParams(booksQ, accessibleLibraryIds, libraryId);
List<BookEntity> books = booksQ.getResultList();
// Group books by series name
Map<String, List<BookEntity>> booksBySeries = books.stream()
.collect(Collectors.groupingBy(b -> b.getMetadata().getSeriesName()));
// Build aggregates map from Phase 1
Map<String, Tuple> aggregateMap = new LinkedHashMap<>();
for (Tuple t : aggregateResults) {
aggregateMap.put(t.get(0, String.class), t);
}
// Merge into summaries, preserving Phase 1 order
List<MobileSeriesSummary> summaries = new ArrayList<>();
for (String seriesName : seriesNames) {
Tuple agg = aggregateMap.get(seriesName);
List<BookEntity> seriesBooks = booksBySeries.getOrDefault(seriesName, Collections.emptyList());
// Distinct authors across all books in series
List<String> authors = seriesBooks.stream()
.filter(b -> b.getMetadata() != null && b.getMetadata().getAuthors() != null)
.flatMap(b -> b.getMetadata().getAuthors().stream())
.map(AuthorEntity::getName)
.distinct()
.toList();
// Cover books sorted by seriesNumber ASC nulls last
List<SeriesCoverBook> coverBooks = seriesBooks.stream()
.sorted(Comparator.comparing(
(BookEntity b) -> b.getMetadata().getSeriesNumber(),
Comparator.nullsLast(Comparator.naturalOrder())))
.map(b -> {
BookFileEntity primaryFile = b.getPrimaryBookFile();
String fileType = (primaryFile != null && primaryFile.getBookType() != null)
? primaryFile.getBookType().name()
: null;
return SeriesCoverBook.builder()
.bookId(b.getId())
.coverUpdatedOn(b.getMetadata().getCoverUpdatedOn())
.seriesNumber(b.getMetadata().getSeriesNumber())
.primaryFileType(fileType)
.build();
})
.toList();
Long booksReadLong = agg.get(4, Long.class);
int booksRead = booksReadLong != null ? booksReadLong.intValue() : 0;
summaries.add(MobileSeriesSummary.builder()
.seriesName(agg.get(0, String.class))
.bookCount(agg.get(1, Long.class).intValue())
.seriesTotal(agg.get(2, Integer.class))
.latestAddedOn(agg.get(3, Instant.class))
.booksRead(booksRead)
.authors(authors)
.coverBooks(coverBooks)
.build());
}
return MobilePageResponse.of(summaries, pageNum, pageSize, totalElements);
}
@Transactional(readOnly = true)
public MobilePageResponse<MobileBookSummary> getSeriesBooks(
String seriesName,
Integer page,
Integer size,
String sortBy,
String sortDir,
Long libraryId) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
if (libraryId != null) {
validateLibraryAccess(accessibleLibraryIds, libraryId);
}
int pageNum = page != null && page >= 0 ? page : 0;
int pageSize = size != null && size > 0 ? Math.min(size, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
Sort sort = buildBookSort(sortBy, sortDir);
Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
Specification<BookEntity> spec = buildSeriesBooksSpec(accessibleLibraryIds, libraryId, seriesName);
Page<BookEntity> bookPage = bookRepository.findAll(spec, pageable);
Set<Long> bookIds = bookPage.getContent().stream()
.map(BookEntity::getId)
.collect(Collectors.toSet());
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, bookIds);
List<MobileBookSummary> summaries = bookPage.getContent().stream()
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
.toList();
return MobilePageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
}
// --- Access control helpers (duplicated from MobileBookService to minimize blast radius) ---
private Set<Long> getAccessibleLibraryIds(BookLoreUser user) {
if (user.getPermissions().isAdmin()) {
return null;
}
if (user.getAssignedLibraries() == null || user.getAssignedLibraries().isEmpty()) {
return Collections.emptySet();
}
return user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
}
private void validateLibraryAccess(Set<Long> accessibleLibraryIds, Long libraryId) {
if (accessibleLibraryIds != null && !accessibleLibraryIds.contains(libraryId)) {
throw ApiError.FORBIDDEN.createException("Access denied to library " + libraryId);
}
}
// --- Query helpers ---
private String buildLibraryClause(Set<Long> accessibleLibraryIds, Long libraryId) {
if (libraryId != null) {
return " AND b.library.id = :libraryId";
} else if (accessibleLibraryIds != null) {
return " AND b.library.id IN :libraryIds";
}
return "";
}
private void setLibraryParams(jakarta.persistence.Query query, Set<Long> accessibleLibraryIds, Long libraryId) {
if (libraryId != null) {
query.setParameter("libraryId", libraryId);
} else if (accessibleLibraryIds != null) {
query.setParameter("libraryIds", accessibleLibraryIds);
}
}
private String buildSeriesOrderBy(String sortBy, String sortDir, boolean inProgressOnly) {
String dir = "asc".equalsIgnoreCase(sortDir) ? "ASC" : "DESC";
String nullsClause = "ASC".equals(dir) ? " NULLS LAST" : " NULLS FIRST";
return switch (sortBy != null ? sortBy.toLowerCase() : "") {
case "name" -> "m.seriesName " + dir;
case "bookcount" -> "COUNT(b.id) " + dir;
case "readprogress" -> "SUM(CASE WHEN p.readStatus = org.booklore.model.enums.ReadStatus.READ THEN 1 ELSE 0 END) " + dir;
case "lastreadtime" -> {
if (inProgressOnly) {
yield "MAX(p.lastReadTime) " + dir + nullsClause;
}
yield "MAX(b.addedOn) " + dir + nullsClause;
}
default -> {
if (inProgressOnly) {
yield "MAX(p.lastReadTime) " + dir + nullsClause;
}
yield "MAX(b.addedOn) " + dir + nullsClause;
}
};
}
private Sort buildBookSort(String sortBy, String sortDir) {
Sort.Direction direction = "asc".equalsIgnoreCase(sortDir) ? Sort.Direction.ASC : Sort.Direction.DESC;
String field = switch (sortBy != null ? sortBy.toLowerCase() : "") {
case "title" -> "metadata.title";
case "seriesnumber" -> "metadata.seriesNumber";
case "recentlyadded" -> "addedOn";
default -> "metadata.seriesNumber";
};
return Sort.by(direction, field);
}
private Specification<BookEntity> buildSeriesBooksSpec(Set<Long> accessibleLibraryIds, Long libraryId, String seriesName) {
List<Specification<BookEntity>> specs = new ArrayList<>();
specs.add(MobileBookSpecification.notDeleted());
specs.add(MobileBookSpecification.hasDigitalFile());
specs.add(MobileBookSpecification.inSeries(seriesName));
if (accessibleLibraryIds != null) {
specs.add(libraryId != null
? MobileBookSpecification.inLibrary(libraryId)
: MobileBookSpecification.inLibraries(accessibleLibraryIds));
} else if (libraryId != null) {
specs.add(MobileBookSpecification.inLibrary(libraryId));
}
return MobileBookSpecification.combine(specs.toArray(new Specification[0]));
}
private Map<Long, UserBookProgressEntity> getProgressMap(Long userId, Set<Long> bookIds) {
if (bookIds.isEmpty()) {
return Collections.emptyMap();
}
return userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds).stream()
.collect(Collectors.toMap(
p -> p.getBook().getId(),
Function.identity()
));
}
}
@@ -229,6 +229,16 @@ public class MobileBookSpecification {
};
}
public static Specification<BookEntity> inSeries(String seriesName) {
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);
};
}
@SafeVarargs
public static Specification<BookEntity> combine(Specification<BookEntity>... specs) {
Specification<BookEntity> result = (root, query, cb) -> cb.conjunction();