fix(hibernate): improve transaction management and optimize entity fetching (#176)
* fix(hibernate): improve transaction management and optimize entity fetching * chore(tests): clean-up comments * chore: fix config issue in the kotlin dsl * fix(hibernate): fix entity equality checks * fix(hibernate): add transactional read-only support to BookService * Update booklore-api/src/main/java/org/booklore/model/entity/BookLoreUserEntity.java Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * fix(hibernate): remove redundant annotations in BookLoreUserEntity * fix(hibernate): import Hibernate * fix(tests): fix merge conflict caused errors * refactor(book): optimize book retrieval methods and reduce cache sizes * refactor(metadata): remove lazy loading from description field in BookMetadataEntity * fix(build): increase max heap size for test tasks --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
coderabbitai[bot]
parent
be0b717ff4
commit
ad3a981ad1
+8
-1
@@ -66,7 +66,14 @@ ENV JAVA_TOOL_OPTIONS="-XX:+UseShenandoahGC \
|
|||||||
-XX:+UseCompactObjectHeaders \
|
-XX:+UseCompactObjectHeaders \
|
||||||
-XX:MaxRAMPercentage=60.0 \
|
-XX:MaxRAMPercentage=60.0 \
|
||||||
-XX:InitialRAMPercentage=8.0 \
|
-XX:InitialRAMPercentage=8.0 \
|
||||||
-XX:+ExitOnOutOfMemoryError"
|
-XX:+ExitOnOutOfMemoryError \
|
||||||
|
-XX:MaxMetaspaceSize=192m \
|
||||||
|
-XX:ReservedCodeCacheSize=64m \
|
||||||
|
-Xss512k \
|
||||||
|
-XX:CICompilerCount=2 \
|
||||||
|
-XX:+UnlockExperimentalVMOptions \
|
||||||
|
-XX:ShenandoahUncommitDelay=5000 \
|
||||||
|
-XX:ShenandoahGuaranteedGCInterval=30000"
|
||||||
|
|
||||||
RUN apk add --no-cache su-exec libstdc++ libgcc libarchive && \
|
RUN apk add --no-cache su-exec libstdc++ libgcc libarchive && \
|
||||||
mkdir -p /bookdrop
|
mkdir -p /bookdrop
|
||||||
|
|||||||
@@ -133,12 +133,14 @@ dependencies {
|
|||||||
|
|
||||||
hibernate {
|
hibernate {
|
||||||
enhancement {
|
enhancement {
|
||||||
enableAssociationManagement = true
|
enableAssociationManagement = false
|
||||||
|
enableLazyInitialization = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named<Test>("test") {
|
tasks.named<Test>("test") {
|
||||||
useJUnitPlatform()
|
useJUnitPlatform()
|
||||||
|
maxHeapSize = "2560m"
|
||||||
jvmArgs("-XX:+EnableDynamicAgentLoading", "--enable-native-access=ALL-UNNAMED")
|
jvmArgs("-XX:+EnableDynamicAgentLoading", "--enable-native-access=ALL-UNNAMED")
|
||||||
finalizedBy(tasks.named("jacocoTestReport"))
|
finalizedBy(tasks.named("jacocoTestReport"))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ import java.util.stream.Collectors;
|
|||||||
|
|
||||||
@Service
|
@Service
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public class AppBookService {
|
public class AppBookService {
|
||||||
|
|
||||||
private static final int DEFAULT_PAGE_SIZE = 20;
|
private static final int DEFAULT_PAGE_SIZE = 20;
|
||||||
@@ -52,7 +53,6 @@ public class AppBookService {
|
|||||||
private final MagicShelfBookService magicShelfBookService;
|
private final MagicShelfBookService magicShelfBookService;
|
||||||
private final EntityManager entityManager;
|
private final EntityManager entityManager;
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public AppPageResponse<AppBookSummary> getBooks(
|
public AppPageResponse<AppBookSummary> getBooks(
|
||||||
Integer page,
|
Integer page,
|
||||||
Integer size,
|
Integer size,
|
||||||
@@ -86,7 +86,6 @@ public class AppBookService {
|
|||||||
return buildPageResponse(bookPage, userId, pageNum, pageSize);
|
return buildPageResponse(bookPage, userId, pageNum, pageSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public AppBookDetail getBookDetail(Long bookId) {
|
public AppBookDetail getBookDetail(Long bookId) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = user.getId();
|
Long userId = user.getId();
|
||||||
@@ -110,7 +109,6 @@ public class AppBookService {
|
|||||||
return mobileBookMapper.toDetail(book, progress, fileProgress);
|
return mobileBookMapper.toDetail(book, progress, fileProgress);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public AppPageResponse<AppBookSummary> searchBooks(
|
public AppPageResponse<AppBookSummary> searchBooks(
|
||||||
String query,
|
String query,
|
||||||
Integer page,
|
Integer page,
|
||||||
@@ -140,7 +138,6 @@ public class AppBookService {
|
|||||||
return buildPageResponse(bookPage, userId, pageNum, pageSize);
|
return buildPageResponse(bookPage, userId, pageNum, pageSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<AppBookSummary> getContinueReading(Integer limit) {
|
public List<AppBookSummary> getContinueReading(Integer limit) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = user.getId();
|
Long userId = user.getId();
|
||||||
@@ -148,33 +145,13 @@ public class AppBookService {
|
|||||||
|
|
||||||
int maxItems = validateLimit(limit, 10);
|
int maxItems = validateLimit(limit, 10);
|
||||||
|
|
||||||
Specification<BookEntity> spec = AppBookSpecification.combine(
|
List<Long> topIds = userBookProgressRepository.findTopContinueReadingBookIds(
|
||||||
AppBookSpecification.notDeleted(),
|
userId, accessibleLibraryIds, PageRequest.of(0, maxItems));
|
||||||
AppBookSpecification.hasDigitalFile(),
|
|
||||||
AppBookSpecification.inLibraries(accessibleLibraryIds),
|
|
||||||
AppBookSpecification.inProgress(userId),
|
|
||||||
AppBookSpecification.hasNonAudiobookFile()
|
|
||||||
);
|
|
||||||
|
|
||||||
List<BookEntity> books = bookRepository.findAll(spec);
|
|
||||||
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, books);
|
|
||||||
|
|
||||||
List<Long> topIds = books.stream()
|
|
||||||
.filter(b -> progressMap.containsKey(b.getId()))
|
|
||||||
.sorted((b1, b2) -> {
|
|
||||||
Instant t1 = progressMap.get(b1.getId()).getLastReadTime();
|
|
||||||
Instant t2 = progressMap.get(b2.getId()).getLastReadTime();
|
|
||||||
if (t1 == null && t2 == null) return 0;
|
|
||||||
if (t1 == null) return 1;
|
|
||||||
if (t2 == null) return -1;
|
|
||||||
return t2.compareTo(t1);
|
|
||||||
})
|
|
||||||
.limit(maxItems)
|
|
||||||
.map(BookEntity::getId)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
if (topIds.isEmpty()) return Collections.emptyList();
|
if (topIds.isEmpty()) return Collections.emptyList();
|
||||||
|
|
||||||
|
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, new HashSet<>(topIds));
|
||||||
|
|
||||||
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(topIds)
|
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(topIds)
|
||||||
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
|
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
|
||||||
|
|
||||||
@@ -184,7 +161,6 @@ public class AppBookService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<AppBookSummary> getContinueListening(Integer limit) {
|
public List<AppBookSummary> getContinueListening(Integer limit) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = user.getId();
|
Long userId = user.getId();
|
||||||
@@ -192,33 +168,13 @@ public class AppBookService {
|
|||||||
|
|
||||||
int maxItems = validateLimit(limit, 10);
|
int maxItems = validateLimit(limit, 10);
|
||||||
|
|
||||||
Specification<BookEntity> spec = AppBookSpecification.combine(
|
List<Long> topIds = userBookProgressRepository.findTopContinueListeningBookIds(
|
||||||
AppBookSpecification.notDeleted(),
|
userId, accessibleLibraryIds, PageRequest.of(0, maxItems));
|
||||||
AppBookSpecification.hasDigitalFile(),
|
|
||||||
AppBookSpecification.inLibraries(accessibleLibraryIds),
|
|
||||||
AppBookSpecification.inProgress(userId),
|
|
||||||
AppBookSpecification.hasAudiobookFile()
|
|
||||||
);
|
|
||||||
|
|
||||||
List<BookEntity> books = bookRepository.findAll(spec);
|
|
||||||
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, books);
|
|
||||||
|
|
||||||
List<Long> topIds = books.stream()
|
|
||||||
.filter(b -> progressMap.containsKey(b.getId()))
|
|
||||||
.sorted((b1, b2) -> {
|
|
||||||
Instant t1 = progressMap.get(b1.getId()).getLastReadTime();
|
|
||||||
Instant t2 = progressMap.get(b2.getId()).getLastReadTime();
|
|
||||||
if (t1 == null && t2 == null) return 0;
|
|
||||||
if (t1 == null) return 1;
|
|
||||||
if (t2 == null) return -1;
|
|
||||||
return t2.compareTo(t1);
|
|
||||||
})
|
|
||||||
.limit(maxItems)
|
|
||||||
.map(BookEntity::getId)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
if (topIds.isEmpty()) return Collections.emptyList();
|
if (topIds.isEmpty()) return Collections.emptyList();
|
||||||
|
|
||||||
|
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, new HashSet<>(topIds));
|
||||||
|
|
||||||
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(topIds)
|
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(topIds)
|
||||||
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
|
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
|
||||||
|
|
||||||
@@ -228,7 +184,6 @@ public class AppBookService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<AppBookSummary> getRecentlyAdded(Integer limit) {
|
public List<AppBookSummary> getRecentlyAdded(Integer limit) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = user.getId();
|
Long userId = user.getId();
|
||||||
@@ -252,7 +207,6 @@ public class AppBookService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<AppBookSummary> getRecentlyScanned(Integer limit) {
|
public List<AppBookSummary> getRecentlyScanned(Integer limit) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = user.getId();
|
Long userId = user.getId();
|
||||||
@@ -275,7 +229,6 @@ public class AppBookService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public AppPageResponse<AppBookSummary> getRandomBooks(
|
public AppPageResponse<AppBookSummary> getRandomBooks(
|
||||||
Integer page,
|
Integer page,
|
||||||
Integer size,
|
Integer size,
|
||||||
@@ -305,7 +258,6 @@ public class AppBookService {
|
|||||||
return buildPageResponse(bookPage, userId, pageNum, pageSize);
|
return buildPageResponse(bookPage, userId, pageNum, pageSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public AppPageResponse<AppBookSummary> getBooksByMagicShelf(
|
public AppPageResponse<AppBookSummary> getBooksByMagicShelf(
|
||||||
Long magicShelfId,
|
Long magicShelfId,
|
||||||
Integer page,
|
Integer page,
|
||||||
@@ -338,7 +290,6 @@ public class AppBookService {
|
|||||||
return AppPageResponse.of(summaries, pageNum, pageSize, booksPage.getTotalElements());
|
return AppPageResponse.of(summaries, pageNum, pageSize, booksPage.getTotalElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public AppFilterOptions getFilterOptions(Long libraryId, Long shelfId, Long magicShelfId) {
|
public AppFilterOptions getFilterOptions(Long libraryId, Long shelfId, Long magicShelfId) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = user.getId();
|
Long userId = user.getId();
|
||||||
|
|||||||
@@ -172,11 +172,10 @@ public class AppSeriesService {
|
|||||||
.map(t -> t.get(0, String.class))
|
.map(t -> t.get(0, String.class))
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
// Phase 2: Fetch books for enrichment
|
// Phase 2: Fetch books for enrichment (only ToOne joins; collections loaded via @BatchSize)
|
||||||
String libraryClause = buildLibraryClause(accessibleLibraryIds, libraryId);
|
String libraryClause = buildLibraryClause(accessibleLibraryIds, libraryId);
|
||||||
String booksQuery = "SELECT b FROM BookEntity b"
|
String booksQuery = "SELECT b FROM BookEntity b"
|
||||||
+ " JOIN FETCH b.metadata m LEFT JOIN FETCH m.authors"
|
+ " JOIN FETCH b.metadata m"
|
||||||
+ " LEFT JOIN FETCH b.bookFiles"
|
|
||||||
+ " WHERE m.seriesName IN :seriesNames"
|
+ " WHERE m.seriesName IN :seriesNames"
|
||||||
+ " AND (b.deleted IS NULL OR b.deleted = false)"
|
+ " AND (b.deleted IS NULL OR b.deleted = false)"
|
||||||
+ " AND b.bookFiles IS NOT EMPTY"
|
+ " AND b.bookFiles IS NOT EMPTY"
|
||||||
|
|||||||
+1
-1
@@ -31,7 +31,7 @@ public class BackchannelLogoutService {
|
|||||||
|
|
||||||
private static final Cache<String, Instant> PROCESSED_JTIS = Caffeine.newBuilder()
|
private static final Cache<String, Instant> PROCESSED_JTIS = Caffeine.newBuilder()
|
||||||
.expireAfterWrite(Duration.ofHours(1))
|
.expireAfterWrite(Duration.ofHours(1))
|
||||||
.maximumSize(10_000)
|
.maximumSize(1_000)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ public class OidcStateService {
|
|||||||
|
|
||||||
private static final Cache<String, Boolean> STATE_CACHE = Caffeine.newBuilder()
|
private static final Cache<String, Boolean> STATE_CACHE = Caffeine.newBuilder()
|
||||||
.expireAfterWrite(Duration.ofMinutes(5))
|
.expireAfterWrite(Duration.ofMinutes(5))
|
||||||
.maximumSize(10_000)
|
.maximumSize(500)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||||
|
|||||||
+1
-1
@@ -23,7 +23,7 @@ public class AuthRateLimitService {
|
|||||||
public AuthRateLimitService(AuditService auditService) {
|
public AuthRateLimitService(AuditService auditService) {
|
||||||
this.auditService = auditService;
|
this.auditService = auditService;
|
||||||
this.attemptCache = Caffeine.newBuilder()
|
this.attemptCache = Caffeine.newBuilder()
|
||||||
.maximumSize(10000)
|
.maximumSize(1000)
|
||||||
.expireAfterWrite(Duration.ofMinutes(15))
|
.expireAfterWrite(Duration.ofMinutes(15))
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|||||||
+1
@@ -23,6 +23,7 @@ public class LoginRateLimitService {
|
|||||||
public LoginRateLimitService(AuditService auditService) {
|
public LoginRateLimitService(AuditService auditService) {
|
||||||
this.auditService = auditService;
|
this.auditService = auditService;
|
||||||
this.attemptCache = Caffeine.newBuilder()
|
this.attemptCache = Caffeine.newBuilder()
|
||||||
|
.maximumSize(1000)
|
||||||
.expireAfterWrite(Duration.ofMinutes(15))
|
.expireAfterWrite(Duration.ofMinutes(15))
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,9 +17,11 @@ import org.booklore.service.appsettings.AppSettingService;
|
|||||||
import org.booklore.service.audit.AuditService;
|
import org.booklore.service.audit.AuditService;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.util.UriComponentsBuilder;
|
import org.springframework.web.util.UriComponentsBuilder;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -34,6 +36,7 @@ public class LogoutService {
|
|||||||
private final AuditService auditService;
|
private final AuditService auditService;
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
|
|
||||||
|
@Transactional
|
||||||
public LogoutResponse logout(Authentication auth, String refreshToken, String origin) {
|
public LogoutResponse logout(Authentication auth, String refreshToken, String origin) {
|
||||||
BookLoreUserEntity user = resolveUser(auth, refreshToken);
|
BookLoreUserEntity user = resolveUser(auth, refreshToken);
|
||||||
|
|
||||||
@@ -65,11 +68,12 @@ public class LogoutService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void revokeRefreshToken(BookLoreUserEntity user) {
|
private void revokeRefreshToken(BookLoreUserEntity user) {
|
||||||
refreshTokenRepository.findAllByUserAndRevokedFalse(user).forEach(token -> {
|
List<RefreshTokenEntity> tokens = refreshTokenRepository.findAllByUserAndRevokedFalse(user);
|
||||||
|
tokens.forEach(token -> {
|
||||||
token.setRevoked(true);
|
token.setRevoked(true);
|
||||||
token.setRevocationDate(Instant.now());
|
token.setRevocationDate(Instant.now());
|
||||||
refreshTokenRepository.save(token);
|
|
||||||
});
|
});
|
||||||
|
refreshTokenRepository.saveAll(tokens);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String buildOidcLogoutUrl(BookLoreUserEntity user, String origin) {
|
private String buildOidcLogoutUrl(BookLoreUserEntity user, String origin) {
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ import jakarta.validation.constraints.Min;
|
|||||||
import jakarta.validation.constraints.Size;
|
import jakarta.validation.constraints.Size;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
import org.springframework.validation.annotation.Validated;
|
import org.springframework.validation.annotation.Validated;
|
||||||
@@ -74,6 +76,14 @@ public class BookController {
|
|||||||
return ResponseEntity.ok(bookService.getBookDTOs(withDescription, stripForListView));
|
return ResponseEntity.ok(bookService.getBookDTOs(withDescription, stripForListView));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "Get books (paginated)", description = "Retrieve a paginated list of books. Supports sorting via 'sort' parameter (e.g. sort=metadata.title,asc).")
|
||||||
|
@ApiResponse(responseCode = "200", description = "Page of books returned successfully")
|
||||||
|
@GetMapping("/page")
|
||||||
|
public ResponseEntity<Page<Book>> getBooksPaged(
|
||||||
|
@Parameter(hidden = true) Pageable pageable) {
|
||||||
|
return ResponseEntity.ok(bookService.getBookDTOsPaged(pageable));
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.")
|
@Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.")
|
||||||
@ApiResponses({
|
@ApiResponses({
|
||||||
@ApiResponse(responseCode = "200", description = "Book details returned successfully"),
|
@ApiResponse(responseCode = "200", description = "Book details returned successfully"),
|
||||||
|
|||||||
@@ -82,7 +82,6 @@ public class MetadataController {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
bookMetadataUpdater.setBookMetadata(context);
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
bookRepository.save(bookEntity);
|
|
||||||
auditService.log(AuditAction.METADATA_UPDATED, "Book", bookId, "Updated metadata for book: " + bookEntity.getMetadata().getTitle());
|
auditService.log(AuditAction.METADATA_UPDATED, "Book", bookId, "Updated metadata for book: " + bookEntity.getMetadata().getTitle());
|
||||||
BookMetadata bookMetadata = bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
|
BookMetadata bookMetadata = bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
|
||||||
return ResponseEntity.ok(bookMetadata);
|
return ResponseEntity.ok(bookMetadata);
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ public interface BookMapperV2 {
|
|||||||
Book toDTO(BookEntity bookEntity);
|
Book toDTO(BookEntity bookEntity);
|
||||||
|
|
||||||
@Named("mapMetadata")
|
@Named("mapMetadata")
|
||||||
|
@Mapping(target = "description", ignore = true)
|
||||||
@Mapping(target = "authors", source = "authors", qualifiedByName = "mapAuthors")
|
@Mapping(target = "authors", source = "authors", qualifiedByName = "mapAuthors")
|
||||||
@Mapping(target = "categories", source = "categories", qualifiedByName = "mapCategories")
|
@Mapping(target = "categories", source = "categories", qualifiedByName = "mapCategories")
|
||||||
@Mapping(target = "moods", source = "moods", qualifiedByName = "mapMoods")
|
@Mapping(target = "moods", source = "moods", qualifiedByName = "mapMoods")
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
package org.booklore.model.entity;
|
package org.booklore.model.entity;
|
||||||
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Data;
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "app_settings")
|
@Table(name = "app_settings")
|
||||||
@Data
|
@Getter
|
||||||
|
@Setter
|
||||||
public class AppSettingEntity {
|
public class AppSettingEntity {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ package org.booklore.model.entity;
|
|||||||
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.BatchSize;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.HashSet;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Getter
|
@Getter
|
||||||
@@ -41,7 +43,9 @@ public class AuthorEntity {
|
|||||||
private boolean photoLocked;
|
private boolean photoLocked;
|
||||||
|
|
||||||
@ManyToMany(mappedBy = "authors", fetch = FetchType.LAZY)
|
@ManyToMany(mappedBy = "authors", fetch = FetchType.LAZY)
|
||||||
private List<BookMetadataEntity> bookMetadataEntityList;
|
@BatchSize(size = 20)
|
||||||
|
@Builder.Default
|
||||||
|
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object o) {
|
public boolean equals(Object o) {
|
||||||
|
|||||||
@@ -6,11 +6,13 @@ import org.booklore.convertor.BookRecommendationIdsListConverter;
|
|||||||
import org.booklore.model.dto.BookRecommendationLite;
|
import org.booklore.model.dto.BookRecommendationLite;
|
||||||
import org.booklore.model.enums.BookFileType;
|
import org.booklore.model.enums.BookFileType;
|
||||||
import org.hibernate.annotations.BatchSize;
|
import org.hibernate.annotations.BatchSize;
|
||||||
|
import org.hibernate.annotations.LazyGroup;
|
||||||
|
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
@@ -77,8 +79,11 @@ public class BookEntity {
|
|||||||
joinColumns = @JoinColumn(name = "book_id"),
|
joinColumns = @JoinColumn(name = "book_id"),
|
||||||
inverseJoinColumns = @JoinColumn(name = "shelf_id")
|
inverseJoinColumns = @JoinColumn(name = "shelf_id")
|
||||||
)
|
)
|
||||||
private Set<ShelfEntity> shelves;
|
@Builder.Default
|
||||||
|
private Set<ShelfEntity> shelves = new HashSet<>();
|
||||||
|
|
||||||
|
@Basic(fetch = FetchType.LAZY)
|
||||||
|
@LazyGroup("recommendations")
|
||||||
@Convert(converter = BookRecommendationIdsListConverter.class)
|
@Convert(converter = BookRecommendationIdsListConverter.class)
|
||||||
@Column(name = "similar_books_json", columnDefinition = "TEXT")
|
@Column(name = "similar_books_json", columnDefinition = "TEXT")
|
||||||
private Set<BookRecommendationLite> similarBooksJson;
|
private Set<BookRecommendationLite> similarBooksJson;
|
||||||
@@ -91,7 +96,8 @@ public class BookEntity {
|
|||||||
|
|
||||||
@BatchSize(size = 20)
|
@BatchSize(size = 20)
|
||||||
@OneToMany(mappedBy = "book", fetch = FetchType.LAZY)
|
@OneToMany(mappedBy = "book", fetch = FetchType.LAZY)
|
||||||
private List<UserBookProgressEntity> userBookProgress;
|
@Builder.Default
|
||||||
|
private List<UserBookProgressEntity> userBookProgress = new ArrayList<>();
|
||||||
|
|
||||||
public Path getFullFilePath() {
|
public Path getFullFilePath() {
|
||||||
BookFileEntity primaryBookFile = getPrimaryBookFile();
|
BookFileEntity primaryBookFile = getPrimaryBookFile();
|
||||||
|
|||||||
@@ -3,10 +3,12 @@ package org.booklore.model.entity;
|
|||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
import org.booklore.model.enums.ProvisioningMethod;
|
import org.booklore.model.enums.ProvisioningMethod;
|
||||||
|
import org.hibernate.Hibernate;
|
||||||
import org.hibernate.annotations.BatchSize;
|
import org.hibernate.annotations.BatchSize;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@@ -93,4 +95,17 @@ public class BookLoreUserEntity {
|
|||||||
public void prePersist() {
|
public void prePersist() {
|
||||||
this.createdAt = LocalDateTime.now();
|
this.createdAt = LocalDateTime.now();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
|
||||||
|
BookLoreUserEntity that = (BookLoreUserEntity) o;
|
||||||
|
return id != null && Objects.equals(id, that.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Hibernate.getClass(this).hashCode();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,9 +4,9 @@ import org.booklore.util.BookUtils;
|
|||||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.BatchSize;
|
||||||
import org.hibernate.annotations.DynamicUpdate;
|
import org.hibernate.annotations.DynamicUpdate;
|
||||||
import org.hibernate.annotations.Fetch;
|
import org.hibernate.annotations.LazyGroup;
|
||||||
import org.hibernate.annotations.FetchMode;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
@@ -21,7 +21,7 @@ import java.util.Set;
|
|||||||
@Builder
|
@Builder
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@DynamicUpdate // 93+ columns; only include changed columns in UPDATE SQL
|
@DynamicUpdate
|
||||||
@Table(name = "book_metadata")
|
@Table(name = "book_metadata")
|
||||||
public class BookMetadataEntity {
|
public class BookMetadataEntity {
|
||||||
|
|
||||||
@@ -300,12 +300,16 @@ public class BookMetadataEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private Boolean abridgedLocked = Boolean.FALSE;
|
private Boolean abridgedLocked = Boolean.FALSE;
|
||||||
|
|
||||||
|
@Basic(fetch = FetchType.LAZY)
|
||||||
|
@LazyGroup("embedding")
|
||||||
@Column(name = "embedding_vector", columnDefinition = "TEXT")
|
@Column(name = "embedding_vector", columnDefinition = "TEXT")
|
||||||
private String embeddingVector;
|
private String embeddingVector;
|
||||||
|
|
||||||
@Column(name = "embedding_updated_at")
|
@Column(name = "embedding_updated_at")
|
||||||
private Instant embeddingUpdatedAt;
|
private Instant embeddingUpdatedAt;
|
||||||
|
|
||||||
|
@Basic(fetch = FetchType.LAZY)
|
||||||
|
@LazyGroup("heavyText")
|
||||||
@Column(name = "search_text", columnDefinition = "TEXT")
|
@Column(name = "search_text", columnDefinition = "TEXT")
|
||||||
private String searchText;
|
private String searchText;
|
||||||
|
|
||||||
@@ -372,9 +376,10 @@ public class BookMetadataEntity {
|
|||||||
name = "book_metadata_author_mapping",
|
name = "book_metadata_author_mapping",
|
||||||
joinColumns = @JoinColumn(name = "book_id"),
|
joinColumns = @JoinColumn(name = "book_id"),
|
||||||
inverseJoinColumns = @JoinColumn(name = "author_id"))
|
inverseJoinColumns = @JoinColumn(name = "author_id"))
|
||||||
@Fetch(FetchMode.SUBSELECT)
|
@BatchSize(size = 20)
|
||||||
@OrderColumn(name = "sort_order")
|
@OrderColumn(name = "sort_order")
|
||||||
private List<AuthorEntity> authors;
|
@Builder.Default
|
||||||
|
private List<AuthorEntity> authors = new ArrayList<>();
|
||||||
|
|
||||||
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
||||||
@JoinTable(
|
@JoinTable(
|
||||||
@@ -382,8 +387,9 @@ public class BookMetadataEntity {
|
|||||||
joinColumns = @JoinColumn(name = "book_id"),
|
joinColumns = @JoinColumn(name = "book_id"),
|
||||||
inverseJoinColumns = @JoinColumn(name = "category_id")
|
inverseJoinColumns = @JoinColumn(name = "category_id")
|
||||||
)
|
)
|
||||||
@Fetch(FetchMode.SUBSELECT)
|
@BatchSize(size = 20)
|
||||||
private Set<CategoryEntity> categories;
|
@Builder.Default
|
||||||
|
private Set<CategoryEntity> categories = new HashSet<>();
|
||||||
|
|
||||||
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
||||||
@JoinTable(
|
@JoinTable(
|
||||||
@@ -391,8 +397,9 @@ public class BookMetadataEntity {
|
|||||||
joinColumns = @JoinColumn(name = "book_id"),
|
joinColumns = @JoinColumn(name = "book_id"),
|
||||||
inverseJoinColumns = @JoinColumn(name = "mood_id")
|
inverseJoinColumns = @JoinColumn(name = "mood_id")
|
||||||
)
|
)
|
||||||
@Fetch(FetchMode.SUBSELECT)
|
@BatchSize(size = 20)
|
||||||
private Set<MoodEntity> moods;
|
@Builder.Default
|
||||||
|
private Set<MoodEntity> moods = new HashSet<>();
|
||||||
|
|
||||||
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
||||||
@JoinTable(
|
@JoinTable(
|
||||||
@@ -400,11 +407,12 @@ public class BookMetadataEntity {
|
|||||||
joinColumns = @JoinColumn(name = "book_id"),
|
joinColumns = @JoinColumn(name = "book_id"),
|
||||||
inverseJoinColumns = @JoinColumn(name = "tag_id")
|
inverseJoinColumns = @JoinColumn(name = "tag_id")
|
||||||
)
|
)
|
||||||
@Fetch(FetchMode.SUBSELECT)
|
@BatchSize(size = 20)
|
||||||
private Set<TagEntity> tags;
|
@Builder.Default
|
||||||
|
private Set<TagEntity> tags = new HashSet<>();
|
||||||
|
|
||||||
@OneToMany(mappedBy = "bookMetadata", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
@OneToMany(mappedBy = "bookMetadata", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||||
@Fetch(FetchMode.SUBSELECT)
|
@BatchSize(size = 20)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
private Set<BookReviewEntity> reviews = new HashSet<>();
|
private Set<BookReviewEntity> reviews = new HashSet<>();
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package org.booklore.model.entity;
|
|||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
import org.hibernate.annotations.CreationTimestamp;
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
import org.hibernate.annotations.LazyGroup;
|
||||||
import org.hibernate.annotations.UpdateTimestamp;
|
import org.hibernate.annotations.UpdateTimestamp;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
@@ -35,10 +36,14 @@ public class BookdropFileEntity {
|
|||||||
private Status status = Status.PENDING_REVIEW;
|
private Status status = Status.PENDING_REVIEW;
|
||||||
|
|
||||||
@Lob
|
@Lob
|
||||||
|
@Basic(fetch = FetchType.LAZY)
|
||||||
|
@LazyGroup("metadata")
|
||||||
@Column(name = "original_metadata", columnDefinition = "JSON")
|
@Column(name = "original_metadata", columnDefinition = "JSON")
|
||||||
private String originalMetadata;
|
private String originalMetadata;
|
||||||
|
|
||||||
@Lob
|
@Lob
|
||||||
|
@Basic(fetch = FetchType.LAZY)
|
||||||
|
@LazyGroup("metadata")
|
||||||
@Column(name = "fetched_metadata", columnDefinition = "JSON")
|
@Column(name = "fetched_metadata", columnDefinition = "JSON")
|
||||||
private String fetchedMetadata;
|
private String fetchedMetadata;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package org.booklore.model.entity;
|
|||||||
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.BatchSize;
|
||||||
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
@@ -24,6 +25,7 @@ public class CategoryEntity {
|
|||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
@ManyToMany(mappedBy = "categories", fetch = FetchType.LAZY)
|
@ManyToMany(mappedBy = "categories", fetch = FetchType.LAZY)
|
||||||
|
@BatchSize(size = 20)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
|
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
|
||||||
|
|
||||||
|
|||||||
@@ -3,9 +3,8 @@ package org.booklore.model.entity;
|
|||||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.BatchSize;
|
||||||
import org.hibernate.annotations.DynamicUpdate;
|
import org.hibernate.annotations.DynamicUpdate;
|
||||||
import org.hibernate.annotations.Fetch;
|
|
||||||
import org.hibernate.annotations.FetchMode;
|
|
||||||
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
@@ -80,7 +79,7 @@ public class ComicMetadataEntity {
|
|||||||
name = "comic_metadata_character_mapping",
|
name = "comic_metadata_character_mapping",
|
||||||
joinColumns = @JoinColumn(name = "book_id"),
|
joinColumns = @JoinColumn(name = "book_id"),
|
||||||
inverseJoinColumns = @JoinColumn(name = "character_id"))
|
inverseJoinColumns = @JoinColumn(name = "character_id"))
|
||||||
@Fetch(FetchMode.SUBSELECT)
|
@BatchSize(size = 20)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
private Set<ComicCharacterEntity> characters = new HashSet<>();
|
private Set<ComicCharacterEntity> characters = new HashSet<>();
|
||||||
|
|
||||||
@@ -89,7 +88,7 @@ public class ComicMetadataEntity {
|
|||||||
name = "comic_metadata_team_mapping",
|
name = "comic_metadata_team_mapping",
|
||||||
joinColumns = @JoinColumn(name = "book_id"),
|
joinColumns = @JoinColumn(name = "book_id"),
|
||||||
inverseJoinColumns = @JoinColumn(name = "team_id"))
|
inverseJoinColumns = @JoinColumn(name = "team_id"))
|
||||||
@Fetch(FetchMode.SUBSELECT)
|
@BatchSize(size = 20)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
private Set<ComicTeamEntity> teams = new HashSet<>();
|
private Set<ComicTeamEntity> teams = new HashSet<>();
|
||||||
|
|
||||||
@@ -98,12 +97,12 @@ public class ComicMetadataEntity {
|
|||||||
name = "comic_metadata_location_mapping",
|
name = "comic_metadata_location_mapping",
|
||||||
joinColumns = @JoinColumn(name = "book_id"),
|
joinColumns = @JoinColumn(name = "book_id"),
|
||||||
inverseJoinColumns = @JoinColumn(name = "location_id"))
|
inverseJoinColumns = @JoinColumn(name = "location_id"))
|
||||||
@Fetch(FetchMode.SUBSELECT)
|
@BatchSize(size = 20)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
private Set<ComicLocationEntity> locations = new HashSet<>();
|
private Set<ComicLocationEntity> locations = new HashSet<>();
|
||||||
|
|
||||||
@OneToMany(mappedBy = "comicMetadata", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
|
@OneToMany(mappedBy = "comicMetadata", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
|
||||||
@Fetch(FetchMode.SUBSELECT)
|
@BatchSize(size = 20)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
private Set<ComicCreatorMappingEntity> creatorMappings = new HashSet<>();
|
private Set<ComicCreatorMappingEntity> creatorMappings = new HashSet<>();
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import jakarta.persistence.*;
|
|||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@@ -24,6 +25,7 @@ public class KoboLibrarySnapshotEntity {
|
|||||||
@Column(name = "created_date", nullable = false)
|
@Column(name = "created_date", nullable = false)
|
||||||
private LocalDateTime createdDate;
|
private LocalDateTime createdDate;
|
||||||
|
|
||||||
@OneToMany(mappedBy = "snapshot", cascade = CascadeType.ALL, orphanRemoval = true)
|
@OneToMany(mappedBy = "snapshot", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||||
private List<KoboSnapshotBookEntity> books;
|
@Builder.Default
|
||||||
|
private List<KoboSnapshotBookEntity> books = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,8 +10,7 @@ import org.booklore.model.enums.MetadataSource;
|
|||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Getter
|
@Getter
|
||||||
@@ -31,14 +30,17 @@ public class LibraryEntity {
|
|||||||
@Convert(converter = SortConverter.class)
|
@Convert(converter = SortConverter.class)
|
||||||
private Sort sort;
|
private Sort sort;
|
||||||
|
|
||||||
@OneToMany(mappedBy = "library", orphanRemoval = true)
|
@OneToMany(mappedBy = "library", orphanRemoval = true, fetch = FetchType.LAZY)
|
||||||
private List<BookEntity> bookEntities;
|
@Builder.Default
|
||||||
|
private List<BookEntity> bookEntities = new ArrayList<>();
|
||||||
|
|
||||||
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||||
private List<LibraryPathEntity> libraryPaths;
|
@Builder.Default
|
||||||
|
private List<LibraryPathEntity> libraryPaths = new ArrayList<>();
|
||||||
|
|
||||||
@ManyToMany(mappedBy = "libraries")
|
@ManyToMany(mappedBy = "libraries", fetch = FetchType.LAZY)
|
||||||
private List<BookLoreUserEntity> users;
|
@Builder.Default
|
||||||
|
private Set<BookLoreUserEntity> users = new HashSet<>();
|
||||||
|
|
||||||
private boolean watch;
|
private boolean watch;
|
||||||
|
|
||||||
@@ -70,4 +72,16 @@ public class LibraryEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private MetadataSource metadataSource = MetadataSource.EMBEDDED;
|
private MetadataSource metadataSource = MetadataSource.EMBEDDED;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (!(o instanceof LibraryEntity that)) return false;
|
||||||
|
return id != null && Objects.equals(id, that.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return getClass().hashCode();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-3
@@ -4,14 +4,17 @@ import org.booklore.model.enums.FetchedMetadataProposalStatus;
|
|||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
import lombok.Data;
|
import lombok.Getter;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.hibernate.annotations.LazyGroup;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "metadata_fetch_proposals")
|
@Table(name = "metadata_fetch_proposals")
|
||||||
@Data
|
@Getter
|
||||||
|
@Setter
|
||||||
@Builder
|
@Builder
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@@ -43,6 +46,8 @@ public class MetadataFetchProposalEntity {
|
|||||||
private FetchedMetadataProposalStatus status;
|
private FetchedMetadataProposalStatus status;
|
||||||
|
|
||||||
@Lob
|
@Lob
|
||||||
|
@Basic(fetch = FetchType.LAZY)
|
||||||
|
@LazyGroup("lob")
|
||||||
@Column(name = "metadata_json", columnDefinition = "JSON")
|
@Column(name = "metadata_json", columnDefinition = "JSON")
|
||||||
private String metadataJson;
|
private String metadataJson;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package org.booklore.model.entity;
|
|||||||
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.BatchSize;
|
||||||
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
@@ -24,6 +25,7 @@ public class MoodEntity {
|
|||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
@ManyToMany(mappedBy = "moods", fetch = FetchType.LAZY)
|
@ManyToMany(mappedBy = "moods", fetch = FetchType.LAZY)
|
||||||
|
@BatchSize(size = 20)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
|
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package org.booklore.model.entity;
|
|||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
import org.hibernate.annotations.CreationTimestamp;
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
import org.hibernate.annotations.LazyGroup;
|
||||||
import org.hibernate.annotations.UpdateTimestamp;
|
import org.hibernate.annotations.UpdateTimestamp;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
@@ -35,6 +36,8 @@ public class PdfAnnotationEntity {
|
|||||||
private Long bookId;
|
private Long bookId;
|
||||||
|
|
||||||
@Lob
|
@Lob
|
||||||
|
@Basic(fetch = FetchType.LAZY)
|
||||||
|
@LazyGroup("lob")
|
||||||
@Column(name = "data", nullable = false, columnDefinition = "LONGTEXT")
|
@Column(name = "data", nullable = false, columnDefinition = "LONGTEXT")
|
||||||
private String data;
|
private String data;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package org.booklore.model.entity;
|
|||||||
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.BatchSize;
|
||||||
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
@@ -24,6 +25,7 @@ public class TagEntity {
|
|||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
@ManyToMany(mappedBy = "tags", fetch = FetchType.LAZY)
|
@ManyToMany(mappedBy = "tags", fetch = FetchType.LAZY)
|
||||||
|
@BatchSize(size = 20)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
|
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import org.booklore.task.TaskStatus;
|
|||||||
import org.booklore.model.enums.TaskType;
|
import org.booklore.model.enums.TaskType;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.LazyGroup;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -49,9 +50,11 @@ public class TaskHistoryEntity {
|
|||||||
private String message;
|
private String message;
|
||||||
|
|
||||||
@Lob
|
@Lob
|
||||||
|
@Basic(fetch = FetchType.LAZY)
|
||||||
|
@LazyGroup("lob")
|
||||||
private String errorDetails;
|
private String errorDetails;
|
||||||
|
|
||||||
@Convert(converter = JpaJsonConverter.class)
|
@Convert(converter = JpaJsonConverter.class)
|
||||||
@Column(name = "task_options", columnDefinition = "TEXT")
|
@Column(name = "task_options", columnDefinition = "TEXT")
|
||||||
private Map<String, Object> taskOptions;
|
private Map<String, Object> taskOptions;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package org.booklore.repository;
|
package org.booklore.repository;
|
||||||
|
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
import org.booklore.model.entity.LibraryPathEntity;
|
import org.booklore.model.entity.LibraryPathEntity;
|
||||||
@@ -33,8 +34,8 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
|||||||
Optional<BookEntity> findByIdFull(@Param("id") Long id);
|
Optional<BookEntity> findByIdFull(@Param("id") Long id);
|
||||||
|
|
||||||
// Minimal graph for summary mapping: metadata (OneToOne), library (ManyToOne), bookFiles (OneToMany).
|
// Minimal graph for summary mapping: metadata (OneToOne), library (ManyToOne), bookFiles (OneToMany).
|
||||||
// metadata.authors is intentionally excluded — @Fetch(SUBSELECT) on BookMetadataEntity.authors
|
// metadata.authors is intentionally excluded — @BatchSize on BookMetadataEntity.authors
|
||||||
// triggers a single batch query when first accessed, so no N+1 occurs.
|
// triggers a batched query when first accessed, so no N+1 occurs.
|
||||||
@EntityGraph(attributePaths = { "metadata", "library", "bookFiles" })
|
@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)")
|
@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);
|
List<BookEntity> findAllForSummaryByIds(@Param("bookIds") Collection<Long> bookIds);
|
||||||
@@ -65,12 +66,8 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
|||||||
@Query("SELECT b.id FROM BookEntity b WHERE b.libraryPath.id IN :libraryPathIds AND (b.deleted IS NULL OR b.deleted = false)")
|
@Query("SELECT b.id FROM BookEntity b WHERE b.libraryPath.id IN :libraryPathIds AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
List<Long> findAllBookIdsByLibraryPathIdIn(@Param("libraryPathIds") Collection<Long> libraryPathIds);
|
List<Long> findAllBookIdsByLibraryPathIdIn(@Param("libraryPathIds") Collection<Long> libraryPathIds);
|
||||||
|
|
||||||
@EntityGraph(attributePaths = {
|
// Only ToOne paths in EntityGraph; collections (authors, categories, moods, tags, shelves, bookFiles) loaded via @BatchSize.
|
||||||
"metadata", "metadata.comicMetadata",
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "library"})
|
||||||
"metadata.comicMetadata.characters", "metadata.comicMetadata.teams", "metadata.comicMetadata.locations", "metadata.comicMetadata.creatorMappings",
|
|
||||||
"metadata.authors", "metadata.categories", "metadata.moods", "metadata.tags",
|
|
||||||
"shelves", "libraryPath", "library", "bookFiles"
|
|
||||||
})
|
|
||||||
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||||
List<BookEntity> findAllWithMetadata();
|
List<BookEntity> findAllWithMetadata();
|
||||||
|
|
||||||
@@ -83,15 +80,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
|||||||
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
|
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds);
|
List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds);
|
||||||
|
|
||||||
@EntityGraph(attributePaths = {
|
|
||||||
"metadata", "metadata.comicMetadata",
|
|
||||||
"metadata.comicMetadata.characters", "metadata.comicMetadata.teams", "metadata.comicMetadata.locations", "metadata.comicMetadata.creatorMappings",
|
|
||||||
"metadata.authors", "metadata.categories", "metadata.moods", "metadata.tags",
|
|
||||||
"shelves", "libraryPath", "library", "bookFiles"
|
|
||||||
})
|
|
||||||
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
|
|
||||||
List<BookEntity> findWithMetadataByIdsWithPagination(@Param("bookIds") Set<Long> bookIds, Pageable pageable);
|
|
||||||
|
|
||||||
@EntityGraph(attributePaths = {
|
@EntityGraph(attributePaths = {
|
||||||
"metadata", "metadata.comicMetadata",
|
"metadata", "metadata.comicMetadata",
|
||||||
"metadata.comicMetadata.characters", "metadata.comicMetadata.teams", "metadata.comicMetadata.locations", "metadata.comicMetadata.creatorMappings",
|
"metadata.comicMetadata.characters", "metadata.comicMetadata.teams", "metadata.comicMetadata.locations", "metadata.comicMetadata.creatorMappings",
|
||||||
@@ -105,23 +93,21 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
|||||||
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
|
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
List<BookEntity> findAllByLibraryIdWithFiles(@Param("libraryId") Long libraryId);
|
List<BookEntity> findAllByLibraryIdWithFiles(@Param("libraryId") Long libraryId);
|
||||||
|
|
||||||
@Query("""
|
@EntityGraph(attributePaths = {"bookFiles", "libraryPath"})
|
||||||
SELECT DISTINCT b FROM BookEntity b
|
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId")
|
||||||
LEFT JOIN FETCH b.metadata m
|
List<BookEntity> findAllByLibraryIdForRescan(@Param("libraryId") Long libraryId);
|
||||||
LEFT JOIN FETCH m.authors
|
|
||||||
LEFT JOIN FETCH b.bookFiles
|
@EntityGraph(attributePaths = {"bookFiles", "libraryPath"})
|
||||||
LEFT JOIN FETCH b.libraryPath
|
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND b.deleted = true")
|
||||||
WHERE b.library.id = :libraryId
|
List<BookEntity> findDeletedByLibraryIdWithFiles(@Param("libraryId") Long libraryId);
|
||||||
AND (b.deleted IS NULL OR b.deleted = false)
|
|
||||||
""")
|
// Only ToOne paths in EntityGraph; collections (authors, bookFiles) loaded via @BatchSize.
|
||||||
|
@EntityGraph(attributePaths = {"metadata", "libraryPath"})
|
||||||
|
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
List<BookEntity> findAllForDuplicateDetection(@Param("libraryId") Long libraryId);
|
List<BookEntity> findAllForDuplicateDetection(@Param("libraryId") Long libraryId);
|
||||||
|
|
||||||
@EntityGraph(attributePaths = {
|
// Only ToOne paths in EntityGraph; collections (authors, categories, moods, tags, shelves, bookFiles) loaded via @BatchSize.
|
||||||
"metadata", "metadata.comicMetadata",
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "library"})
|
||||||
"metadata.comicMetadata.characters", "metadata.comicMetadata.teams", "metadata.comicMetadata.locations", "metadata.comicMetadata.creatorMappings",
|
|
||||||
"metadata.authors", "metadata.categories", "metadata.moods", "metadata.tags",
|
|
||||||
"shelves", "libraryPath", "library", "bookFiles"
|
|
||||||
})
|
|
||||||
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
|
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
List<BookEntity> findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
|
List<BookEntity> findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
|
||||||
|
|
||||||
@@ -138,15 +124,9 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
|||||||
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE bf.isBookFormat = true AND bf.fileSizeKb IS NULL AND (b.deleted IS NULL OR b.deleted = false)")
|
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE bf.isBookFormat = true AND bf.fileSizeKb IS NULL AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
List<BookEntity> findAllWithMetadataByFileSizeKbIsNull();
|
List<BookEntity> findAllWithMetadataByFileSizeKbIsNull();
|
||||||
|
|
||||||
@Query("""
|
// Only ToOne paths in EntityGraph; collections (authors, categories, shelves) loaded via @BatchSize.
|
||||||
SELECT DISTINCT b FROM BookEntity b
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata"})
|
||||||
LEFT JOIN FETCH b.metadata m
|
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||||
LEFT JOIN FETCH m.authors
|
|
||||||
LEFT JOIN FETCH m.categories
|
|
||||||
LEFT JOIN FETCH m.comicMetadata
|
|
||||||
LEFT JOIN FETCH b.shelves
|
|
||||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
|
||||||
""")
|
|
||||||
List<BookEntity> findAllFullBooks();
|
List<BookEntity> findAllFullBooks();
|
||||||
|
|
||||||
@Query(value = """
|
@Query(value = """
|
||||||
@@ -357,19 +337,10 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
|||||||
@Query("""
|
@Query("""
|
||||||
SELECT DISTINCT b FROM BookEntity b
|
SELECT DISTINCT b FROM BookEntity b
|
||||||
LEFT JOIN b.metadata m
|
LEFT JOIN b.metadata m
|
||||||
LEFT JOIN b.bookFiles bf
|
|
||||||
WHERE b.library.id = :libraryId
|
WHERE b.library.id = :libraryId
|
||||||
AND (
|
AND (
|
||||||
(m.seriesName = :seriesName)
|
(m.seriesName = :seriesName)
|
||||||
OR (
|
OR (m.seriesName IS NULL AND :seriesName = :unknownSeriesName)
|
||||||
m.seriesName IS NULL
|
|
||||||
AND bf.isBookFormat = true
|
|
||||||
AND bf.id = (
|
|
||||||
SELECT MIN(bf2.id) FROM BookFileEntity bf2
|
|
||||||
WHERE bf2.book = b AND bf2.isBookFormat = true
|
|
||||||
)
|
|
||||||
AND bf.fileName = :seriesName
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
AND (b.deleted IS NULL OR b.deleted = false)
|
AND (b.deleted IS NULL OR b.deleted = false)
|
||||||
ORDER BY COALESCE(m.seriesNumber, 0)
|
ORDER BY COALESCE(m.seriesNumber, 0)
|
||||||
@@ -408,4 +379,129 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
|||||||
List<BookEntity> findBooksBySeriesNameUngroupedByLibraryId(
|
List<BookEntity> findBooksBySeriesNameUngroupedByLibraryId(
|
||||||
@Param("seriesName") String seriesName,
|
@Param("seriesName") String seriesName,
|
||||||
@Param("libraryId") Long libraryId);
|
@Param("libraryId") Long libraryId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find books by series name across all libraries when groupUnknown=true.
|
||||||
|
*/
|
||||||
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "shelves", "libraryPath", "bookFiles"})
|
||||||
|
@Query("""
|
||||||
|
SELECT DISTINCT b FROM BookEntity b
|
||||||
|
LEFT JOIN b.metadata m
|
||||||
|
WHERE (
|
||||||
|
(m.seriesName = :seriesName)
|
||||||
|
OR (
|
||||||
|
m.seriesName IS NULL
|
||||||
|
AND :seriesName = :unknownSeriesName
|
||||||
|
)
|
||||||
|
)
|
||||||
|
AND (b.deleted IS NULL OR b.deleted = false)
|
||||||
|
ORDER BY COALESCE(m.seriesNumber, 0)
|
||||||
|
""")
|
||||||
|
List<BookEntity> findBooksBySeriesNameGrouped(
|
||||||
|
@Param("seriesName") String seriesName,
|
||||||
|
@Param("unknownSeriesName") String unknownSeriesName);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find books by series name across all libraries when groupUnknown=false.
|
||||||
|
*/
|
||||||
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "shelves", "libraryPath", "bookFiles"})
|
||||||
|
@Query("""
|
||||||
|
SELECT b FROM BookEntity b
|
||||||
|
LEFT JOIN b.metadata m
|
||||||
|
LEFT JOIN b.bookFiles bf
|
||||||
|
WHERE (
|
||||||
|
(m.seriesName = :seriesName)
|
||||||
|
OR (m.seriesName IS NULL AND m.title = :seriesName)
|
||||||
|
OR (
|
||||||
|
m.seriesName IS NULL AND m.title IS NULL
|
||||||
|
AND bf.isBookFormat = true
|
||||||
|
AND bf.id = (
|
||||||
|
SELECT MIN(bf2.id) FROM BookFileEntity bf2
|
||||||
|
WHERE bf2.book = b AND bf2.isBookFormat = true
|
||||||
|
)
|
||||||
|
AND bf.fileName = :seriesName
|
||||||
|
)
|
||||||
|
)
|
||||||
|
AND (b.deleted IS NULL OR b.deleted = false)
|
||||||
|
ORDER BY COALESCE(m.seriesNumber, 0)
|
||||||
|
""")
|
||||||
|
List<BookEntity> findBooksBySeriesNameUngrouped(
|
||||||
|
@Param("seriesName") String seriesName);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paginated query for all non-deleted books with Komga-relevant metadata.
|
||||||
|
* Only ToOne paths in EntityGraph to avoid Cartesian product; collections loaded via @BatchSize.
|
||||||
|
*/
|
||||||
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "libraryPath", "library"})
|
||||||
|
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||||
|
Page<BookEntity> findAllWithMetadataPaged(Pageable pageable);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paginated query for non-deleted books by library with Komga-relevant metadata.
|
||||||
|
* Only ToOne paths in EntityGraph to avoid Cartesian product; collections loaded via @BatchSize.
|
||||||
|
*/
|
||||||
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "libraryPath", "library"})
|
||||||
|
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
|
Page<BookEntity> findAllWithMetadataByLibraryIdPaged(@Param("libraryId") Long libraryId, Pageable pageable);
|
||||||
|
|
||||||
|
@Query("SELECT COUNT(b) FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||||
|
long countNonDeleted();
|
||||||
|
|
||||||
|
@Query("SELECT COUNT(b) FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
|
long countByLibraryIdNonDeleted(@Param("libraryId") Long libraryId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lightweight query for recommendation: loads only metadata with authors and categories (no bookFiles, shelves, etc.)
|
||||||
|
*/
|
||||||
|
@Query("""
|
||||||
|
SELECT DISTINCT b FROM BookEntity b
|
||||||
|
LEFT JOIN FETCH b.metadata m
|
||||||
|
LEFT JOIN FETCH m.authors
|
||||||
|
LEFT JOIN FETCH m.categories
|
||||||
|
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||||
|
AND b.id <> :excludeBookId
|
||||||
|
""")
|
||||||
|
List<BookEntity> findAllForRecommendation(@Param("excludeBookId") Long excludeBookId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paginated query for all non-deleted books (main UI listing).
|
||||||
|
* Only ToOne paths in EntityGraph to avoid Cartesian product with LIMIT;
|
||||||
|
* collections (authors, categories, tags, moods, shelves, bookFiles) loaded via @BatchSize.
|
||||||
|
*/
|
||||||
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "libraryPath", "library"})
|
||||||
|
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||||
|
Page<BookEntity> findAllWithMetadataPage(Pageable pageable);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paginated query for non-deleted books filtered by library IDs.
|
||||||
|
* Only ToOne paths in EntityGraph to avoid Cartesian product with LIMIT;
|
||||||
|
* collections (authors, categories, tags, moods, shelves, bookFiles) loaded via @BatchSize.
|
||||||
|
*/
|
||||||
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "libraryPath", "library"})
|
||||||
|
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
|
Page<BookEntity> findAllWithMetadataByLibraryIdsPage(@Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Batched query for embedding/recommendation computation.
|
||||||
|
* Only ToOne paths in EntityGraph to avoid Cartesian product with LIMIT/OFFSET;
|
||||||
|
* collections (authors, categories, shelves) loaded via @BatchSize when accessed.
|
||||||
|
*/
|
||||||
|
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata"})
|
||||||
|
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) ORDER BY b.id")
|
||||||
|
List<BookEntity> findAllFullBooksBatch(Pageable pageable);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lightweight projection for on-demand recommendation: returns only bookId, embedding vector,
|
||||||
|
* and series name. Avoids loading full entities when pre-computed embeddings are available.
|
||||||
|
*/
|
||||||
|
@Query("""
|
||||||
|
SELECT b.id as bookId, m.embeddingVector as embeddingVector, m.seriesName as seriesName
|
||||||
|
FROM BookEntity b
|
||||||
|
LEFT JOIN b.metadata m
|
||||||
|
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||||
|
AND b.id <> :excludeBookId
|
||||||
|
AND m.embeddingVector IS NOT NULL
|
||||||
|
""")
|
||||||
|
List<org.booklore.repository.projection.BookEmbeddingProjection> findAllEmbeddingsForRecommendation(@Param("excludeBookId") Long excludeBookId);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import org.booklore.model.dto.ProgressPercentDto;
|
|||||||
import org.booklore.model.dto.RatingDistributionDto;
|
import org.booklore.model.dto.RatingDistributionDto;
|
||||||
import org.booklore.model.dto.StatusDistributionDto;
|
import org.booklore.model.dto.StatusDistributionDto;
|
||||||
import org.booklore.model.entity.UserBookProgressEntity;
|
import org.booklore.model.entity.UserBookProgressEntity;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Modifying;
|
import org.springframework.data.jpa.repository.Modifying;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
@@ -14,6 +15,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
@@ -202,4 +204,46 @@ public interface UserBookProgressRepository extends JpaRepository<UserBookProgre
|
|||||||
WHERE ubp.user.id = :userId
|
WHERE ubp.user.id = :userId
|
||||||
""")
|
""")
|
||||||
List<ProgressPercentDto> findAllProgressPercentsByUser(@Param("userId") Long userId);
|
List<ProgressPercentDto> findAllProgressPercentsByUser(@Param("userId") Long userId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns book IDs for in-progress reading (non-audiobook), ordered by most recently read.
|
||||||
|
*/
|
||||||
|
@Query("""
|
||||||
|
SELECT DISTINCT ubp.book.id FROM UserBookProgressEntity ubp
|
||||||
|
JOIN ubp.book b
|
||||||
|
JOIN b.bookFiles bf
|
||||||
|
WHERE ubp.user.id = :userId
|
||||||
|
AND ubp.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING)
|
||||||
|
AND (b.deleted IS NULL OR b.deleted = false)
|
||||||
|
AND bf.isBookFormat = true
|
||||||
|
AND bf.bookType <> org.booklore.model.enums.BookFileType.AUDIOBOOK
|
||||||
|
AND b.library.id IN :libraryIds
|
||||||
|
AND ubp.lastReadTime IS NOT NULL
|
||||||
|
ORDER BY ubp.lastReadTime DESC
|
||||||
|
""")
|
||||||
|
List<Long> findTopContinueReadingBookIds(
|
||||||
|
@Param("userId") Long userId,
|
||||||
|
@Param("libraryIds") Collection<Long> libraryIds,
|
||||||
|
Pageable pageable);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns book IDs for in-progress listening (audiobook), ordered by most recently read.
|
||||||
|
*/
|
||||||
|
@Query("""
|
||||||
|
SELECT DISTINCT ubp.book.id FROM UserBookProgressEntity ubp
|
||||||
|
JOIN ubp.book b
|
||||||
|
JOIN b.bookFiles bf
|
||||||
|
WHERE ubp.user.id = :userId
|
||||||
|
AND ubp.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING)
|
||||||
|
AND (b.deleted IS NULL OR b.deleted = false)
|
||||||
|
AND bf.isBookFormat = true
|
||||||
|
AND bf.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
|
||||||
|
AND b.library.id IN :libraryIds
|
||||||
|
AND ubp.lastReadTime IS NOT NULL
|
||||||
|
ORDER BY ubp.lastReadTime DESC
|
||||||
|
""")
|
||||||
|
List<Long> findTopContinueListeningBookIds(
|
||||||
|
@Param("userId") Long userId,
|
||||||
|
@Param("libraryIds") Collection<Long> libraryIds,
|
||||||
|
Pageable pageable);
|
||||||
}
|
}
|
||||||
|
|||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
package org.booklore.repository.projection;
|
||||||
|
|
||||||
|
public interface BookEmbeddingProjection {
|
||||||
|
Long getBookId();
|
||||||
|
String getEmbeddingVector();
|
||||||
|
String getSeriesName();
|
||||||
|
}
|
||||||
@@ -38,7 +38,7 @@ public class IconService {
|
|||||||
private static final String ICONS_DIR = "icons";
|
private static final String ICONS_DIR = "icons";
|
||||||
private static final String SVG_DIR = "svg";
|
private static final String SVG_DIR = "svg";
|
||||||
private static final String SVG_EXTENSION = ".svg";
|
private static final String SVG_EXTENSION = ".svg";
|
||||||
private static final int MAX_CACHE_SIZE = 1000;
|
private static final int MAX_CACHE_SIZE = 200;
|
||||||
private static final String SVG_START_TAG = "<svg";
|
private static final String SVG_START_TAG = "<svg";
|
||||||
private static final String XML_DECLARATION = "<?xml";
|
private static final String XML_DECLARATION = "<?xml";
|
||||||
private static final String SVG_END_TAG = "</svg>";
|
private static final String SVG_END_TAG = "</svg>";
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import java.util.stream.Collectors;
|
|||||||
|
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@Service
|
@Service
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public class MagicShelfService {
|
public class MagicShelfService {
|
||||||
|
|
||||||
private final MagicShelfRepository magicShelfRepository;
|
private final MagicShelfRepository magicShelfRepository;
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ import java.util.stream.Collectors;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public class ReadingSessionService {
|
public class ReadingSessionService {
|
||||||
|
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
@@ -84,7 +85,6 @@ public class ReadingSessionService {
|
|||||||
log.info("Reading session persisted successfully: sessionId={}, userId={}, bookId={}, duration={}s", session.getId(), userId, request.getBookId(), request.getDurationSeconds());
|
log.info("Reading session persisted successfully: sessionId={}, userId={}, bookId={}, duration={}s", session.getId(), userId, request.getBookId(), request.getDurationSeconds());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForYear(int year) {
|
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForYear(int year) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -98,7 +98,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForMonth(int year, int month) {
|
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForMonth(int year, int month) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -112,7 +111,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
|
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -136,7 +134,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<ReadingSpeedResponse> getReadingSpeedForYear(int year) {
|
public List<ReadingSpeedResponse> getReadingSpeedForYear(int year) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -151,7 +148,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<PeakHoursResponse> getPeakReadingHours(Integer year, Integer month) {
|
public List<PeakHoursResponse> getPeakReadingHours(Integer year, Integer month) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -166,7 +162,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
|
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -184,7 +179,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<GenreStatisticsResponse> getGenreStatistics() {
|
public List<GenreStatisticsResponse> getGenreStatistics() {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -207,7 +201,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<CompletionTimelineResponse> getCompletionTimeline(int year) {
|
public List<CompletionTimelineResponse> getCompletionTimeline(int year) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -246,7 +239,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public Page<ReadingSessionResponse> getReadingSessionsForBook(Long bookId, int page, int size) {
|
public Page<ReadingSessionResponse> getReadingSessionsForBook(Long bookId, int page, int size) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -275,7 +267,6 @@ public class ReadingSessionService {
|
|||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<BookCompletionHeatmapResponse> getBookCompletionHeatmap() {
|
public List<BookCompletionHeatmapResponse> getBookCompletionHeatmap() {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -293,7 +284,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<PageTurnerScoreResponse> getPageTurnerScores() {
|
public List<PageTurnerScoreResponse> getPageTurnerScores() {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -377,7 +367,6 @@ public class ReadingSessionService {
|
|||||||
|
|
||||||
private static final int COMPLETION_RACE_BOOK_LIMIT = 10;
|
private static final int COMPLETION_RACE_BOOK_LIMIT = 10;
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<CompletionRaceResponse> getCompletionRace(int year) {
|
public List<CompletionRaceResponse> getCompletionRace(int year) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -409,7 +398,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<ReadingSessionHeatmapResponse> getReadingDates() {
|
public List<ReadingSessionHeatmapResponse> getReadingDates() {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -423,7 +411,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public BookDistributionsResponse getBookDistributions() {
|
public BookDistributionsResponse getBookDistributions() {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -497,7 +484,6 @@ public class ReadingSessionService {
|
|||||||
return max;
|
return max;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<SessionScatterResponse> getSessionScatter(int year) {
|
public List<SessionScatterResponse> getSessionScatter(int year) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -512,7 +498,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public ReadingStreakResponse getReadingStreak() {
|
public ReadingStreakResponse getReadingStreak() {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -570,7 +555,6 @@ public class ReadingSessionService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<BookTimelineResponse> getBookTimeline(int year) {
|
public List<BookTimelineResponse> getBookTimeline(int year) {
|
||||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||||
Long userId = authenticatedUser.getId();
|
Long userId = authenticatedUser.getId();
|
||||||
@@ -620,7 +604,6 @@ public class ReadingSessionService {
|
|||||||
// Listening (audiobook) stats
|
// Listening (audiobook) stats
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<ListeningHeatmapResponse> getListeningHeatmapForMonth(int year, int month) {
|
public List<ListeningHeatmapResponse> getListeningHeatmapForMonth(int year, int month) {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
return readingSessionRepository.findListeningSessionsByUserAndMonth(userId, year, month, getTimezoneOffset())
|
return readingSessionRepository.findListeningSessionsByUserAndMonth(userId, year, month, getTimezoneOffset())
|
||||||
@@ -633,7 +616,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<WeeklyListeningTrendResponse> getWeeklyListeningTrend(int weeks) {
|
public List<WeeklyListeningTrendResponse> getWeeklyListeningTrend(int weeks) {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
return readingSessionRepository.findWeeklyListeningTrend(userId, weeks, getTimezoneOffset())
|
return readingSessionRepository.findWeeklyListeningTrend(userId, weeks, getTimezoneOffset())
|
||||||
@@ -647,7 +629,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public ListeningCompletionResponse getListeningCompletion() {
|
public ListeningCompletionResponse getListeningCompletion() {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
var progressList = readingSessionRepository.findAudiobookProgressByUser(userId);
|
var progressList = readingSessionRepository.findAudiobookProgressByUser(userId);
|
||||||
@@ -684,7 +665,6 @@ public class ReadingSessionService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<MonthlyPaceResponse> getMonthlyListeningPace(int months) {
|
public List<MonthlyPaceResponse> getMonthlyListeningPace(int months) {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
|
|
||||||
@@ -714,7 +694,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public ListeningFinishFunnelResponse getListeningFinishFunnel() {
|
public ListeningFinishFunnelResponse getListeningFinishFunnel() {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
var progressList = readingSessionRepository.findAudiobookProgressByUser(userId);
|
var progressList = readingSessionRepository.findAudiobookProgressByUser(userId);
|
||||||
@@ -745,7 +724,6 @@ public class ReadingSessionService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<PeakHoursResponse> getListeningPeakHours(Integer year, Integer month) {
|
public List<PeakHoursResponse> getListeningPeakHours(Integer year, Integer month) {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
return readingSessionRepository.findListeningPeakHoursByUser(userId, year, month, getTimezoneOffset())
|
return readingSessionRepository.findListeningPeakHoursByUser(userId, year, month, getTimezoneOffset())
|
||||||
@@ -758,7 +736,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<GenreStatisticsResponse> getListeningGenreStatistics() {
|
public List<GenreStatisticsResponse> getListeningGenreStatistics() {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
return readingSessionRepository.findListeningGenreStatisticsByUser(userId)
|
return readingSessionRepository.findListeningGenreStatisticsByUser(userId)
|
||||||
@@ -779,7 +756,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<ListeningAuthorResponse> getListeningAuthorStats() {
|
public List<ListeningAuthorResponse> getListeningAuthorStats() {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
return readingSessionRepository.findListeningAuthorStatsByUser(userId)
|
return readingSessionRepository.findListeningAuthorStatsByUser(userId)
|
||||||
@@ -793,7 +769,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<SessionScatterResponse> getListeningSessionScatter() {
|
public List<SessionScatterResponse> getListeningSessionScatter() {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
return readingSessionRepository.findListeningSessionScatterByUser(userId, getTimezoneOffset())
|
return readingSessionRepository.findListeningSessionScatterByUser(userId, getTimezoneOffset())
|
||||||
@@ -806,7 +781,6 @@ public class ReadingSessionService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<LongestAudiobookResponse> getListeningLongestBooks() {
|
public List<LongestAudiobookResponse> getListeningLongestBooks() {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
return readingSessionRepository.findAudiobookProgressByUser(userId)
|
return readingSessionRepository.findAudiobookProgressByUser(userId)
|
||||||
|
|||||||
@@ -4,15 +4,19 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import org.booklore.mapper.v2.BookMapperV2;
|
import org.booklore.mapper.v2.BookMapperV2;
|
||||||
import org.booklore.model.dto.Book;
|
import org.booklore.model.dto.Book;
|
||||||
import org.booklore.model.dto.BookMetadata;
|
import org.booklore.model.dto.BookMetadata;
|
||||||
|
import org.booklore.model.dto.BookRecommendationLite;
|
||||||
import org.booklore.model.dto.ComicMetadata;
|
import org.booklore.model.dto.ComicMetadata;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.service.restriction.ContentRestrictionService;
|
import org.booklore.service.restriction.ContentRestrictionService;
|
||||||
|
import org.hibernate.Hibernate;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.*;
|
||||||
import java.util.Set;
|
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@@ -35,6 +39,35 @@ public class BookQueryService {
|
|||||||
return mapBooksToDto(books, includeDescription, userId, StripForListView);
|
return mapBooksToDto(books, includeDescription, userId, StripForListView);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Page<Book> getAllBooksPaged(Pageable pageable) {
|
||||||
|
Page<BookEntity> page = bookRepository.findAllWithMetadataPage(pageable);
|
||||||
|
return page.map(book -> mapBookToDto(book, false, null, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Page<Book> getAllBooksByLibraryIdsPaged(Collection<Long> libraryIds, Long userId, Pageable pageable) {
|
||||||
|
Page<BookEntity> page = bookRepository.findAllWithMetadataByLibraryIdsPage(libraryIds, pageable);
|
||||||
|
List<BookEntity> filtered = contentRestrictionService.applyRestrictions(page.getContent(), userId);
|
||||||
|
List<Book> dtos = filtered.stream()
|
||||||
|
.map(book -> mapBookToDto(book, false, userId, true))
|
||||||
|
.toList();
|
||||||
|
return new PageImpl<>(dtos, pageable, page.getTotalElements());
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<BookEntity> getAllFullBookEntitiesBatch(Pageable pageable) {
|
||||||
|
List<BookEntity> books = bookRepository.findAllFullBooksBatch(pageable);
|
||||||
|
for (BookEntity book : books) {
|
||||||
|
if (book.getMetadata() != null) {
|
||||||
|
Hibernate.initialize(book.getMetadata().getAuthors());
|
||||||
|
Hibernate.initialize(book.getMetadata().getCategories());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return books;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long countAllNonDeleted() {
|
||||||
|
return bookRepository.countNonDeleted();
|
||||||
|
}
|
||||||
|
|
||||||
public List<BookEntity> findAllWithMetadataByIds(Set<Long> bookIds) {
|
public List<BookEntity> findAllWithMetadataByIds(Set<Long> bookIds) {
|
||||||
return bookRepository.findAllWithMetadataByIds(bookIds);
|
return bookRepository.findAllWithMetadataByIds(bookIds);
|
||||||
}
|
}
|
||||||
@@ -52,6 +85,36 @@ public class BookQueryService {
|
|||||||
bookRepository.saveAll(books);
|
bookRepository.saveAll(books);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void compareAndSaveEmbeddings(Map<Long, String> embeddingJsonByBookId) {
|
||||||
|
List<BookEntity> books = bookRepository.findAllWithMetadataByIds(new HashSet<>(embeddingJsonByBookId.keySet()));
|
||||||
|
for (BookEntity book : books) {
|
||||||
|
String embeddingJson = embeddingJsonByBookId.get(book.getId());
|
||||||
|
if (embeddingJson != null && book.getMetadata() != null) {
|
||||||
|
if (!Objects.equals(book.getMetadata().getEmbeddingVector(), embeddingJson)) {
|
||||||
|
book.getMetadata().setEmbeddingVector(embeddingJson);
|
||||||
|
book.getMetadata().setEmbeddingUpdatedAt(java.time.Instant.now());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void saveRecommendationsInBatches(Map<Long, Set<BookRecommendationLite>> recommendations, int batchSize) {
|
||||||
|
List<Long> bookIds = new ArrayList<>(recommendations.keySet());
|
||||||
|
for (int i = 0; i < bookIds.size(); i += batchSize) {
|
||||||
|
List<Long> batchIds = bookIds.subList(i, Math.min(i + batchSize, bookIds.size()));
|
||||||
|
List<BookEntity> batch = bookRepository.findAllById(batchIds);
|
||||||
|
for (BookEntity book : batch) {
|
||||||
|
Set<BookRecommendationLite> recs = recommendations.get(book.getId());
|
||||||
|
if (recs != null) {
|
||||||
|
book.setSimilarBooksJson(recs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bookRepository.saveAll(batch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private List<Book> mapBooksToDto(List<BookEntity> books, boolean includeDescription, Long userId, boolean stripForListView) {
|
private List<Book> mapBooksToDto(List<BookEntity> books, boolean includeDescription, Long userId, boolean stripForListView) {
|
||||||
return books.stream()
|
return books.stream()
|
||||||
.map(book -> mapBookToDto(book, includeDescription, userId, stripForListView))
|
.map(book -> mapBookToDto(book, includeDescription, userId, stripForListView))
|
||||||
@@ -61,8 +124,8 @@ public class BookQueryService {
|
|||||||
private Book mapBookToDto(BookEntity bookEntity, boolean includeDescription, Long userId, boolean stripForListView) {
|
private Book mapBookToDto(BookEntity bookEntity, boolean includeDescription, Long userId, boolean stripForListView) {
|
||||||
Book dto = bookMapperV2.toDTO(bookEntity);
|
Book dto = bookMapperV2.toDTO(bookEntity);
|
||||||
|
|
||||||
if (!includeDescription && dto.getMetadata() != null) {
|
if (includeDescription && dto.getMetadata() != null && bookEntity.getMetadata() != null) {
|
||||||
dto.getMetadata().setDescription(null);
|
dto.getMetadata().setDescription(bookEntity.getMetadata().getDescription());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dto.getShelves() != null && userId != null) {
|
if (dto.getShelves() != null && userId != null) {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package org.booklore.service.book;
|
package org.booklore.service.book;
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -22,14 +21,13 @@ import org.booklore.service.monitoring.MonitoringRegistrationService;
|
|||||||
import org.booklore.service.progress.ReadingProgressService;
|
import org.booklore.service.progress.ReadingProgressService;
|
||||||
import org.booklore.util.FileService;
|
import org.booklore.util.FileService;
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.core.io.ByteArrayResource;
|
import org.springframework.core.io.ByteArrayResource;
|
||||||
import org.springframework.core.io.ClassPathResource;
|
import org.springframework.core.io.ClassPathResource;
|
||||||
import org.springframework.core.io.FileSystemResource;
|
import org.springframework.core.io.FileSystemResource;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.core.io.UrlResource;
|
import org.springframework.core.io.UrlResource;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.http.*;
|
import org.springframework.http.*;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
@@ -47,6 +45,7 @@ import java.util.stream.Collectors;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@Service
|
@Service
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public class BookService {
|
public class BookService {
|
||||||
|
|
||||||
private final BookRepository bookRepository;
|
private final BookRepository bookRepository;
|
||||||
@@ -69,7 +68,6 @@ public class BookService {
|
|||||||
private final AuditService auditService;
|
private final AuditService auditService;
|
||||||
|
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<Book> getBookDTOs(boolean includeDescription, boolean stripForListView) {
|
public List<Book> getBookDTOs(boolean includeDescription, boolean stripForListView) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
boolean isAdmin = user.getPermissions().isAdmin();
|
boolean isAdmin = user.getPermissions().isAdmin();
|
||||||
@@ -102,12 +100,42 @@ public class BookService {
|
|||||||
return books;
|
return books;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Page<Book> getBookDTOsPaged(Pageable pageable) {
|
||||||
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
|
boolean isAdmin = user.getPermissions().isAdmin();
|
||||||
|
|
||||||
|
Page<Book> bookPage = isAdmin
|
||||||
|
? bookQueryService.getAllBooksPaged(pageable)
|
||||||
|
: bookQueryService.getAllBooksByLibraryIdsPaged(
|
||||||
|
getUserLibraryIds(user),
|
||||||
|
user.getId(),
|
||||||
|
pageable
|
||||||
|
);
|
||||||
|
|
||||||
|
Set<Long> bookIds = bookPage.getContent().stream().map(Book::getId).collect(Collectors.toSet());
|
||||||
|
Map<Long, UserBookProgressEntity> progressMap =
|
||||||
|
readingProgressService.fetchUserProgress(user.getId(), bookIds);
|
||||||
|
Map<Long, UserBookFileProgressEntity> fileProgressMap =
|
||||||
|
readingProgressService.fetchUserFileProgress(user.getId(), bookIds);
|
||||||
|
|
||||||
|
bookPage.getContent().forEach(book -> {
|
||||||
|
readingProgressService.enrichBookWithProgress(
|
||||||
|
book,
|
||||||
|
progressMap.get(book.getId()),
|
||||||
|
fileProgressMap.get(book.getId())
|
||||||
|
);
|
||||||
|
Set<Shelf> filtered = filterShelvesByUserId(book.getShelves(), user.getId());
|
||||||
|
book.setShelves(filtered != null && filtered.isEmpty() ? null : filtered);
|
||||||
|
});
|
||||||
|
|
||||||
|
return bookPage;
|
||||||
|
}
|
||||||
|
|
||||||
private Set<Long> getUserLibraryIds(BookLoreUser user) {
|
private Set<Long> getUserLibraryIds(BookLoreUser user) {
|
||||||
return user.getAssignedLibraries().stream()
|
return user.getAssignedLibraries().stream()
|
||||||
.map(Library::getId)
|
.map(Library::getId)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
}
|
}
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<Book> getBooksByIds(Set<Long> bookIds, boolean withDescription) {
|
public List<Book> getBooksByIds(Set<Long> bookIds, boolean withDescription) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
boolean isAdmin = user.getPermissions().isAdmin();
|
boolean isAdmin = user.getPermissions().isAdmin();
|
||||||
@@ -140,7 +168,6 @@ public class BookService {
|
|||||||
}).collect(Collectors.toList());
|
}).collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public Book getBook(long bookId, boolean withDescription) {
|
public Book getBook(long bookId, boolean withDescription) {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
@@ -165,7 +192,6 @@ public class BookService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public BookViewerSettings getBookViewerSetting(long bookId, long bookFileId) {
|
public BookViewerSettings getBookViewerSetting(long bookId, long bookFileId) {
|
||||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
@@ -230,6 +256,7 @@ public class BookService {
|
|||||||
return settingsBuilder.build();
|
return settingsBuilder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
|
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
|
||||||
bookUpdateService.updateBookViewerSetting(bookId, bookViewerSettings);
|
bookUpdateService.updateBookViewerSetting(bookId, bookViewerSettings);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ public class BookUpdateService {
|
|||||||
private final ReadingProgressService readingProgressService;
|
private final ReadingProgressService readingProgressService;
|
||||||
private final EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
|
private final EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
|
||||||
|
|
||||||
|
@Transactional
|
||||||
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
|
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
|
||||||
BookEntity book = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
BookEntity book = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import java.util.Set;
|
|||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public class NotebookService {
|
public class NotebookService {
|
||||||
|
|
||||||
private static final int EXPORT_LIMIT = 50_000;
|
private static final int EXPORT_LIMIT = 50_000;
|
||||||
@@ -25,7 +26,6 @@ public class NotebookService {
|
|||||||
private final NotebookEntryRepository repository;
|
private final NotebookEntryRepository repository;
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public Page<NotebookEntry> getNotebookEntries(int page, int size, Set<String> types, Long bookId,
|
public Page<NotebookEntry> getNotebookEntries(int page, int size, Set<String> types, Long bookId,
|
||||||
String search, String sort) {
|
String search, String sort) {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
@@ -34,7 +34,6 @@ public class NotebookService {
|
|||||||
.map(NotebookService::toDto);
|
.map(NotebookService::toDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<NotebookEntry> getAllNotebookEntries(Set<String> types, Long bookId, String search, String sort) {
|
public List<NotebookEntry> getAllNotebookEntries(Set<String> types, Long bookId, String search, String sort) {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
Pageable pageable = PageRequest.of(0, EXPORT_LIMIT, toSort(sort));
|
Pageable pageable = PageRequest.of(0, EXPORT_LIMIT, toSort(sort));
|
||||||
@@ -43,7 +42,6 @@ public class NotebookService {
|
|||||||
.getContent();
|
.getContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<NotebookBookOption> getBooksWithAnnotations(String search) {
|
public List<NotebookBookOption> getBooksWithAnnotations(String search) {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
return repository.findBooksWithAnnotations(userId, wrapSearch(search), Pageable.ofSize(BOOK_OPTIONS_LIMIT))
|
return repository.findBooksWithAnnotations(userId, wrapSearch(search), Pageable.ofSize(BOOK_OPTIONS_LIMIT))
|
||||||
|
|||||||
@@ -40,6 +40,9 @@ import org.springframework.data.domain.Page;
|
|||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.transaction.PlatformTransactionManager;
|
||||||
|
import org.springframework.transaction.TransactionDefinition;
|
||||||
|
import org.springframework.transaction.support.TransactionTemplate;
|
||||||
import tools.jackson.databind.ObjectMapper;
|
import tools.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
@@ -75,6 +78,7 @@ public class BookDropService {
|
|||||||
private final FileMovingHelper fileMovingHelper;
|
private final FileMovingHelper fileMovingHelper;
|
||||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||||
private final KoboAutoShelfService koboAutoShelfService;
|
private final KoboAutoShelfService koboAutoShelfService;
|
||||||
|
private final PlatformTransactionManager transactionManager;
|
||||||
|
|
||||||
private static final int CHUNK_SIZE = 100;
|
private static final int CHUNK_SIZE = 100;
|
||||||
|
|
||||||
@@ -467,24 +471,32 @@ public class BookDropService {
|
|||||||
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
|
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
|
||||||
.getType());
|
.getType());
|
||||||
|
|
||||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(fileProcessResult.getBook().getId())
|
// Post-processing runs in REQUIRES_NEW so it gets a fresh REPEATABLE_READ snapshot
|
||||||
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
|
// that can see the book committed by processFile()'s own REQUIRES_NEW transaction
|
||||||
|
TransactionTemplate newTx = new TransactionTemplate(transactionManager);
|
||||||
|
newTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||||
|
Long bookId = fileProcessResult.getBook().getId();
|
||||||
|
newTx.executeWithoutResult(status -> {
|
||||||
|
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
|
||||||
|
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
|
||||||
|
|
||||||
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook());
|
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
||||||
MetadataUpdateContext context = MetadataUpdateContext.builder()
|
.bookEntity(bookEntity)
|
||||||
.bookEntity(bookEntity)
|
.metadataUpdateWrapper(MetadataUpdateWrapper.builder()
|
||||||
.metadataUpdateWrapper(MetadataUpdateWrapper.builder()
|
.metadata(metadata)
|
||||||
.metadata(metadata)
|
.build())
|
||||||
.build())
|
.updateThumbnail(metadata.getThumbnailUrl() != null)
|
||||||
.updateThumbnail(metadata.getThumbnailUrl() != null)
|
.mergeCategories(false)
|
||||||
.mergeCategories(false)
|
.replaceMode(MetadataReplaceMode.REPLACE_WHEN_PROVIDED)
|
||||||
.replaceMode(MetadataReplaceMode.REPLACE_WHEN_PROVIDED)
|
.mergeMoods(true)
|
||||||
.mergeMoods(true)
|
.mergeTags(true)
|
||||||
.mergeTags(true)
|
.build();
|
||||||
.build();
|
|
||||||
|
|
||||||
metadataRefreshService.updateBookMetadata(context);
|
metadataRefreshService.updateBookMetadata(context);
|
||||||
koboAutoShelfService.autoAddBookToKoboShelves(bookEntity.getId());
|
koboAutoShelfService.autoAddBookToKoboShelves(bookEntity.getId());
|
||||||
|
|
||||||
|
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook());
|
||||||
|
});
|
||||||
|
|
||||||
cleanupBookdropData(bookdropFile);
|
cleanupBookdropData(bookdropFile);
|
||||||
|
|
||||||
@@ -639,4 +651,3 @@ public class BookDropService {
|
|||||||
private record FileProcessingContext(Long libraryId, Long pathId, BookMetadata metadata) {
|
private record FileProcessingContext(Long libraryId, Long pathId, BookMetadata metadata) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ import org.booklore.service.reader.CbxReaderService;
|
|||||||
import org.booklore.service.reader.PdfReaderService;
|
import org.booklore.service.reader.PdfReaderService;
|
||||||
import org.springframework.core.io.ByteArrayResource;
|
import org.springframework.core.io.ByteArrayResource;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -121,11 +124,13 @@ public class KomgaService {
|
|||||||
seriesName, libraryId);
|
seriesName, libraryId);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// For all libraries, need to load all books and filter (less common case)
|
// For all libraries without library filter
|
||||||
List<BookEntity> allBooks = bookRepository.findAllWithMetadata();
|
if (groupUnknown) {
|
||||||
seriesBooks = allBooks.stream()
|
seriesBooks = bookRepository.findBooksBySeriesNameGrouped(
|
||||||
.filter(book -> komgaMapper.getBookSeriesName(book).equals(seriesName))
|
seriesName, komgaMapper.getUnknownSeriesName());
|
||||||
.collect(Collectors.toList());
|
} else {
|
||||||
|
seriesBooks = bookRepository.findBooksBySeriesNameUngrouped(seriesName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!seriesBooks.isEmpty()) {
|
if (!seriesBooks.isEmpty()) {
|
||||||
@@ -165,25 +170,40 @@ public class KomgaService {
|
|||||||
Long libraryId = Long.parseLong(parts[0]);
|
Long libraryId = Long.parseLong(parts[0]);
|
||||||
String seriesSlug = parts[1];
|
String seriesSlug = parts[1];
|
||||||
|
|
||||||
// Get books matching the series - optimized to query by series name
|
boolean groupUnknown = appSettingService.getAppSettings().isKomgaGroupUnknown();
|
||||||
List<BookEntity> allSeriesBooks = bookRepository.findAllWithMetadataByLibraryId(libraryId);
|
|
||||||
|
// Get distinct series names for this library to find the matching name by slug
|
||||||
|
List<String> seriesNames;
|
||||||
|
if (groupUnknown) {
|
||||||
|
seriesNames = bookRepository.findDistinctSeriesNamesGroupedByLibraryId(libraryId, komgaMapper.getUnknownSeriesName());
|
||||||
|
} else {
|
||||||
|
seriesNames = bookRepository.findDistinctSeriesNamesUngroupedByLibraryId(libraryId);
|
||||||
|
}
|
||||||
|
|
||||||
// Find the series name that matches this slug
|
// Find the series name that matches this slug
|
||||||
List<BookEntity> seriesBooks = allSeriesBooks.stream()
|
String matchedSeriesName = seriesNames.stream()
|
||||||
.filter(book -> {
|
.filter(name -> {
|
||||||
String bookSeriesName = komgaMapper.getBookSeriesName(book);
|
String slug = NON_ALPHANUMERIC_PATTERN.matcher(name.toLowerCase()).replaceAll("-");
|
||||||
String bookSeriesSlug = NON_ALPHANUMERIC_PATTERN.matcher(bookSeriesName.toLowerCase()).replaceAll("-");
|
return slug.equals(seriesSlug);
|
||||||
return bookSeriesSlug.equals(seriesSlug);
|
|
||||||
})
|
})
|
||||||
.collect(Collectors.toList());
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new RuntimeException("Series not found"));
|
||||||
|
|
||||||
|
// Load only the books for this specific series
|
||||||
|
List<BookEntity> seriesBooks;
|
||||||
|
if (groupUnknown) {
|
||||||
|
seriesBooks = bookRepository.findBooksBySeriesNameGroupedByLibraryId(
|
||||||
|
matchedSeriesName, libraryId, komgaMapper.getUnknownSeriesName());
|
||||||
|
} else {
|
||||||
|
seriesBooks = bookRepository.findBooksBySeriesNameUngroupedByLibraryId(
|
||||||
|
matchedSeriesName, libraryId);
|
||||||
|
}
|
||||||
|
|
||||||
if (seriesBooks.isEmpty()) {
|
if (seriesBooks.isEmpty()) {
|
||||||
throw new RuntimeException("Series not found");
|
throw new RuntimeException("Series not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
String seriesName = komgaMapper.getBookSeriesName(seriesBooks.get(0));
|
return komgaMapper.toKomgaSeriesDto(matchedSeriesName, libraryId, seriesBooks);
|
||||||
|
|
||||||
return komgaMapper.toKomgaSeriesDto(seriesName, libraryId, seriesBooks);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public KomgaPageableDto<KomgaBookDto> getBooksBySeries(String seriesId, int page, int size, boolean unpaged) {
|
public KomgaPageableDto<KomgaBookDto> getBooksBySeries(String seriesId, int page, int size, boolean unpaged) {
|
||||||
@@ -196,23 +216,36 @@ public class KomgaService {
|
|||||||
Long libraryId = Long.parseLong(parts[0]);
|
Long libraryId = Long.parseLong(parts[0]);
|
||||||
String seriesSlug = parts[1];
|
String seriesSlug = parts[1];
|
||||||
|
|
||||||
// Get all books for the library once
|
boolean groupUnknown = appSettingService.getAppSettings().isKomgaGroupUnknown();
|
||||||
List<BookEntity> allBooks = bookRepository.findAllWithMetadataByLibraryId(libraryId);
|
|
||||||
|
|
||||||
// Filter and sort books for this series
|
// Get distinct series names for this library to find the matching name by slug
|
||||||
List<BookEntity> seriesBooks = allBooks.stream()
|
List<String> seriesNames;
|
||||||
.filter(book -> {
|
if (groupUnknown) {
|
||||||
String bookSeriesName = komgaMapper.getBookSeriesName(book);
|
seriesNames = bookRepository.findDistinctSeriesNamesGroupedByLibraryId(libraryId, komgaMapper.getUnknownSeriesName());
|
||||||
String bookSeriesSlug = NON_ALPHANUMERIC_PATTERN.matcher(bookSeriesName.toLowerCase()).replaceAll("-");
|
} else {
|
||||||
return bookSeriesSlug.equals(seriesSlug);
|
seriesNames = bookRepository.findDistinctSeriesNamesUngroupedByLibraryId(libraryId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the series name that matches this slug
|
||||||
|
String matchedSeriesName = seriesNames.stream()
|
||||||
|
.filter(name -> {
|
||||||
|
String slug = NON_ALPHANUMERIC_PATTERN.matcher(name.toLowerCase()).replaceAll("-");
|
||||||
|
return slug.equals(seriesSlug);
|
||||||
})
|
})
|
||||||
.sorted(Comparator.comparing(book -> {
|
.findFirst()
|
||||||
BookMetadataEntity metadata = book.getMetadata();
|
.orElse(null);
|
||||||
return metadata != null && metadata.getSeriesNumber() != null
|
|
||||||
? metadata.getSeriesNumber()
|
// Load only the books for this specific series (already sorted by seriesNumber via query ORDER BY)
|
||||||
: 0f;
|
List<BookEntity> seriesBooks;
|
||||||
}))
|
if (matchedSeriesName == null) {
|
||||||
.collect(Collectors.toList());
|
seriesBooks = List.of();
|
||||||
|
} else if (groupUnknown) {
|
||||||
|
seriesBooks = bookRepository.findBooksBySeriesNameGroupedByLibraryId(
|
||||||
|
matchedSeriesName, libraryId, komgaMapper.getUnknownSeriesName());
|
||||||
|
} else {
|
||||||
|
seriesBooks = bookRepository.findBooksBySeriesNameUngroupedByLibraryId(
|
||||||
|
matchedSeriesName, libraryId);
|
||||||
|
}
|
||||||
|
|
||||||
// Handle unpaged mode
|
// Handle unpaged mode
|
||||||
int totalElements = seriesBooks.size();
|
int totalElements = seriesBooks.size();
|
||||||
@@ -256,21 +289,16 @@ public class KomgaService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public KomgaPageableDto<KomgaBookDto> getAllBooks(Long libraryId, int page, int size) {
|
public KomgaPageableDto<KomgaBookDto> getAllBooks(Long libraryId, int page, int size) {
|
||||||
List<BookEntity> books;
|
Pageable pageable = PageRequest.of(page, size);
|
||||||
|
Page<BookEntity> bookPage;
|
||||||
|
|
||||||
if (libraryId != null) {
|
if (libraryId != null) {
|
||||||
books = bookRepository.findAllWithMetadataByLibraryId(libraryId);
|
bookPage = bookRepository.findAllWithMetadataByLibraryIdPaged(libraryId, pageable);
|
||||||
} else {
|
} else {
|
||||||
books = bookRepository.findAllWithMetadata();
|
bookPage = bookRepository.findAllWithMetadataPaged(pageable);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Manual pagination
|
List<KomgaBookDto> content = bookPage.getContent().stream()
|
||||||
int totalElements = books.size();
|
|
||||||
int totalPages = (int) Math.ceil((double) totalElements / size);
|
|
||||||
int fromIndex = Math.min(page * size, totalElements);
|
|
||||||
int toIndex = Math.min(fromIndex + size, totalElements);
|
|
||||||
|
|
||||||
List<KomgaBookDto> content = books.subList(fromIndex, toIndex).stream()
|
|
||||||
.map(book -> komgaMapper.toKomgaBookDto(book))
|
.map(book -> komgaMapper.toKomgaBookDto(book))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
@@ -279,10 +307,10 @@ public class KomgaService {
|
|||||||
.number(page)
|
.number(page)
|
||||||
.size(size)
|
.size(size)
|
||||||
.numberOfElements(content.size())
|
.numberOfElements(content.size())
|
||||||
.totalElements(totalElements)
|
.totalElements((int) bookPage.getTotalElements())
|
||||||
.totalPages(totalPages)
|
.totalPages(bookPage.getTotalPages())
|
||||||
.first(page == 0)
|
.first(page == 0)
|
||||||
.last(page >= totalPages - 1)
|
.last(page >= bookPage.getTotalPages() - 1)
|
||||||
.empty(content.isEmpty())
|
.empty(content.isEmpty())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
@@ -419,4 +447,4 @@ public class KomgaService {
|
|||||||
return outputStream.toByteArray();
|
return outputStream.toByteArray();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,12 +33,13 @@ public class BookRestorationService {
|
|||||||
if (libraryFiles.isEmpty()) return;
|
if (libraryFiles.isEmpty()) return;
|
||||||
|
|
||||||
LibraryEntity libraryEntity = libraryFiles.getFirst().getLibraryEntity();
|
LibraryEntity libraryEntity = libraryFiles.getFirst().getLibraryEntity();
|
||||||
|
Long libraryId = libraryEntity.getId();
|
||||||
Set<Path> currentPaths = libraryFiles.stream()
|
Set<Path> currentPaths = libraryFiles.stream()
|
||||||
.map(LibraryFile::getFullPath)
|
.map(LibraryFile::getFullPath)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
List<BookEntity> toRestore = libraryEntity.getBookEntities().stream()
|
List<BookEntity> deletedBooks = bookRepository.findDeletedByLibraryIdWithFiles(libraryId);
|
||||||
.filter(book -> Boolean.TRUE.equals(book.getDeleted()))
|
List<BookEntity> toRestore = deletedBooks.stream()
|
||||||
.filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty())
|
.filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty())
|
||||||
.filter(book -> currentPaths.contains(book.getFullFilePath()))
|
.filter(book -> currentPaths.contains(book.getFullFilePath()))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|||||||
+21
-13
@@ -13,6 +13,7 @@ import org.booklore.model.entity.LibraryPathEntity;
|
|||||||
import org.booklore.model.websocket.LogNotification;
|
import org.booklore.model.websocket.LogNotification;
|
||||||
import org.booklore.model.websocket.Topic;
|
import org.booklore.model.websocket.Topic;
|
||||||
import org.booklore.repository.BookAdditionalFileRepository;
|
import org.booklore.repository.BookAdditionalFileRepository;
|
||||||
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.repository.LibraryRepository;
|
import org.booklore.repository.LibraryRepository;
|
||||||
import org.booklore.service.NotificationService;
|
import org.booklore.service.NotificationService;
|
||||||
import org.booklore.service.file.FileFingerprint;
|
import org.booklore.service.file.FileFingerprint;
|
||||||
@@ -37,6 +38,7 @@ import java.util.stream.Collectors;
|
|||||||
public class LibraryProcessingService {
|
public class LibraryProcessingService {
|
||||||
|
|
||||||
private final LibraryRepository libraryRepository;
|
private final LibraryRepository libraryRepository;
|
||||||
|
private final BookRepository bookRepository;
|
||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
private final BookAdditionalFileRepository bookAdditionalFileRepository;
|
private final BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||||
private final FileAsBookProcessor fileAsBookProcessor;
|
private final FileAsBookProcessor fileAsBookProcessor;
|
||||||
@@ -53,7 +55,8 @@ public class LibraryProcessingService {
|
|||||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started processing library: " + libraryEntity.getName()));
|
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started processing library: " + libraryEntity.getName()));
|
||||||
try {
|
try {
|
||||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity);
|
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity);
|
||||||
List<LibraryFile> newFiles = detectNewBookPaths(libraryFiles, libraryEntity);
|
List<BookEntity> existingBooks = bookRepository.findAllByLibraryIdForRescan(libraryId);
|
||||||
|
List<LibraryFile> newFiles = detectNewBookPaths(libraryFiles, existingBooks, libraryId);
|
||||||
|
|
||||||
// Use BookGroupingService for consistent grouping based on organization mode
|
// Use BookGroupingService for consistent grouping based on organization mode
|
||||||
Map<String, List<LibraryFile>> groups = bookGroupingService.groupForInitialScan(newFiles, libraryEntity);
|
Map<String, List<LibraryFile>> groups = bookGroupingService.groupForInitialScan(newFiles, libraryEntity);
|
||||||
@@ -69,16 +72,20 @@ public class LibraryProcessingService {
|
|||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public void rescanLibrary(RescanLibraryContext context) throws IOException {
|
public void rescanLibrary(RescanLibraryContext context) throws IOException {
|
||||||
LibraryEntity libraryEntity = libraryRepository.findByIdWithBooks(context.getLibraryId()).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(context.getLibraryId()));
|
long libraryId = context.getLibraryId();
|
||||||
|
LibraryEntity libraryEntity = libraryRepository.findByIdWithPaths(libraryId)
|
||||||
|
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started refreshing library: " + libraryEntity.getName()));
|
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started refreshing library: " + libraryEntity.getName()));
|
||||||
|
|
||||||
validateLibraryPathsAccessible(libraryEntity);
|
validateLibraryPathsAccessible(libraryEntity);
|
||||||
|
|
||||||
|
List<BookEntity> books = bookRepository.findAllByLibraryIdForRescan(libraryId);
|
||||||
|
|
||||||
List<LibraryFile> allLibraryFiles = libraryFileHelper.getAllLibraryFiles(libraryEntity);
|
List<LibraryFile> allLibraryFiles = libraryFileHelper.getAllLibraryFiles(libraryEntity);
|
||||||
List<LibraryFile> filteredFiles = libraryFileHelper.filterByAllowedFormats(
|
List<LibraryFile> filteredFiles = libraryFileHelper.filterByAllowedFormats(
|
||||||
allLibraryFiles, libraryEntity.getAllowedFormats());
|
allLibraryFiles, libraryEntity.getAllowedFormats());
|
||||||
|
|
||||||
int existingBookCount = libraryEntity.getBookEntities().size();
|
int existingBookCount = books.size();
|
||||||
if (existingBookCount > 0 && allLibraryFiles.isEmpty()) {
|
if (existingBookCount > 0 && allLibraryFiles.isEmpty()) {
|
||||||
String paths = libraryEntity.getLibraryPaths().stream()
|
String paths = libraryEntity.getLibraryPaths().stream()
|
||||||
.map(LibraryPathEntity::getPath)
|
.map(LibraryPathEntity::getPath)
|
||||||
@@ -93,7 +100,7 @@ public class LibraryProcessingService {
|
|||||||
log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName());
|
log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName());
|
||||||
bookDeletionService.deleteRemovedAdditionalFiles(additionalFileIds);
|
bookDeletionService.deleteRemovedAdditionalFiles(additionalFileIds);
|
||||||
}
|
}
|
||||||
List<Long> bookIds = detectDeletedBookIds(allLibraryFiles, libraryEntity);
|
List<Long> bookIds = detectDeletedBookIds(allLibraryFiles, books);
|
||||||
if (!bookIds.isEmpty()) {
|
if (!bookIds.isEmpty()) {
|
||||||
log.info("Detected {} removed books in library: {}", bookIds.size(), libraryEntity.getName());
|
log.info("Detected {} removed books in library: {}", bookIds.size(), libraryEntity.getName());
|
||||||
bookDeletionService.processDeletedLibraryFiles(bookIds, allLibraryFiles);
|
bookDeletionService.processDeletedLibraryFiles(bookIds, allLibraryFiles);
|
||||||
@@ -101,11 +108,12 @@ public class LibraryProcessingService {
|
|||||||
bookRestorationService.restoreDeletedBooks(allLibraryFiles);
|
bookRestorationService.restoreDeletedBooks(allLibraryFiles);
|
||||||
bookDeletionService.purgeDisallowedFormats(libraryEntity);
|
bookDeletionService.purgeDisallowedFormats(libraryEntity);
|
||||||
entityManager.clear();
|
entityManager.clear();
|
||||||
// Re-fetch library entity with books to get fresh state after entity manager was cleared
|
// Re-fetch fresh state after entity manager was cleared
|
||||||
libraryEntity = libraryRepository.findByIdWithBooks(context.getLibraryId())
|
libraryEntity = libraryRepository.findByIdWithPaths(libraryId)
|
||||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(context.getLibraryId()));
|
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
|
books = bookRepository.findAllByLibraryIdForRescan(libraryId);
|
||||||
|
|
||||||
List<LibraryFile> newFiles = detectNewBookPaths(filteredFiles, libraryEntity);
|
List<LibraryFile> newFiles = detectNewBookPaths(filteredFiles, books, libraryId);
|
||||||
|
|
||||||
// Use BookGroupingService to determine what to attach vs create new
|
// Use BookGroupingService to determine what to attach vs create new
|
||||||
BookGroupingService.GroupingResult groupingResult = bookGroupingService.groupForRescan(newFiles, libraryEntity);
|
BookGroupingService.GroupingResult groupingResult = bookGroupingService.groupForRescan(newFiles, libraryEntity);
|
||||||
@@ -137,12 +145,12 @@ public class LibraryProcessingService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected static List<Long> detectDeletedBookIds(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
protected static List<Long> detectDeletedBookIds(List<LibraryFile> libraryFiles, List<BookEntity> books) {
|
||||||
Set<Path> currentFullPaths = libraryFiles.stream()
|
Set<Path> currentFullPaths = libraryFiles.stream()
|
||||||
.map(LibraryFile::getFullPath)
|
.map(LibraryFile::getFullPath)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
return libraryEntity.getBookEntities().stream()
|
return books.stream()
|
||||||
.filter(book -> (book.getDeleted() == null || !book.getDeleted()))
|
.filter(book -> (book.getDeleted() == null || !book.getDeleted()))
|
||||||
.filter(book -> {
|
.filter(book -> {
|
||||||
// Don't mark fileless books as deleted - they're intentionally without files
|
// Don't mark fileless books as deleted - they're intentionally without files
|
||||||
@@ -155,13 +163,13 @@ public class LibraryProcessingService {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
protected List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
protected List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, List<BookEntity> books, Long libraryId) {
|
||||||
Set<String> existingKeys = libraryEntity.getBookEntities().stream()
|
Set<String> existingKeys = books.stream()
|
||||||
.filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty())
|
.filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty())
|
||||||
.map(this::generateUniqueKey)
|
.map(this::generateUniqueKey)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
Set<String> additionalFileKeys = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId()).stream()
|
Set<String> additionalFileKeys = bookAdditionalFileRepository.findByLibraryId(libraryId).stream()
|
||||||
.map(this::generateUniqueKey)
|
.map(this::generateUniqueKey)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ import java.util.stream.Collectors;
|
|||||||
@Service
|
@Service
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@DependsOnDatabaseInitialization
|
@DependsOnDatabaseInitialization
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public class LibraryService {
|
public class LibraryService {
|
||||||
|
|
||||||
private static final Set<Long> scanningLibraries = ConcurrentHashMap.newKeySet();
|
private static final Set<Long> scanningLibraries = ConcurrentHashMap.newKeySet();
|
||||||
@@ -161,7 +162,8 @@ public class LibraryService {
|
|||||||
@Transactional
|
@Transactional
|
||||||
public Library createLibrary(CreateLibraryRequest request) {
|
public Library createLibrary(CreateLibraryRequest request) {
|
||||||
BookLoreUser bookLoreUser = authenticationService.getAuthenticatedUser();
|
BookLoreUser bookLoreUser = authenticationService.getAuthenticatedUser();
|
||||||
Optional<BookLoreUserEntity> user = userRepository.findById(bookLoreUser.getId());
|
BookLoreUserEntity userEntity = userRepository.findById(bookLoreUser.getId())
|
||||||
|
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(bookLoreUser.getId()));
|
||||||
|
|
||||||
LibraryEntity libraryEntity = LibraryEntity.builder()
|
LibraryEntity libraryEntity = LibraryEntity.builder()
|
||||||
.name(request.getName())
|
.name(request.getName())
|
||||||
@@ -179,9 +181,13 @@ public class LibraryService {
|
|||||||
.allowedFormats(request.getAllowedFormats())
|
.allowedFormats(request.getAllowedFormats())
|
||||||
.metadataSource(request.getMetadataSource())
|
.metadataSource(request.getMetadataSource())
|
||||||
.organizationMode(request.getOrganizationMode())
|
.organizationMode(request.getOrganizationMode())
|
||||||
.users(List.of(user.get()))
|
.users(new HashSet<>(Set.of(userEntity)))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
for (LibraryPathEntity p : libraryEntity.getLibraryPaths()) {
|
||||||
|
p.setLibrary(libraryEntity);
|
||||||
|
}
|
||||||
|
|
||||||
libraryEntity = libraryRepository.save(libraryEntity);
|
libraryEntity = libraryRepository.save(libraryEntity);
|
||||||
Long libraryId = libraryEntity.getId();
|
Long libraryId = libraryEntity.getId();
|
||||||
|
|
||||||
@@ -198,6 +204,7 @@ public class LibraryService {
|
|||||||
return libraryMapper.toLibrary(libraryEntity);
|
return libraryMapper.toLibrary(libraryEntity);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
public void rescanLibrary(long libraryId) {
|
public void rescanLibrary(long libraryId) {
|
||||||
LibraryEntity lib = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
LibraryEntity lib = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
auditService.log(AuditAction.LIBRARY_SCANNED, "Library", libraryId, "Scanned library: " + lib.getName());
|
auditService.log(AuditAction.LIBRARY_SCANNED, "Library", libraryId, "Scanned library: " + lib.getName());
|
||||||
@@ -223,19 +230,16 @@ public class LibraryService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public Library getLibrary(long libraryId) {
|
public Library getLibrary(long libraryId) {
|
||||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
return libraryMapper.toLibrary(libraryEntity);
|
return libraryMapper.toLibrary(libraryEntity);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<Library> getAllLibraries() {
|
public List<Library> getAllLibraries() {
|
||||||
List<LibraryEntity> libraries = libraryRepository.findAll();
|
List<LibraryEntity> libraries = libraryRepository.findAll();
|
||||||
return libraries.stream().map(libraryMapper::toLibrary).toList();
|
return libraries.stream().map(libraryMapper::toLibrary).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<Library> getLibraries() {
|
public List<Library> getLibraries() {
|
||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
BookLoreUserEntity userEntity = userRepository.findByIdWithLibraries(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
BookLoreUserEntity userEntity = userRepository.findByIdWithLibraries(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||||
@@ -251,10 +255,10 @@ public class LibraryService {
|
|||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public void deleteLibrary(long id) {
|
public void deleteLibrary(long id) {
|
||||||
LibraryEntity library = libraryRepository.findByIdWithBooks(id)
|
LibraryEntity library = libraryRepository.findById(id)
|
||||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(id));
|
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(id));
|
||||||
libraryWatchService.unregisterLibrary(id);
|
libraryWatchService.unregisterLibrary(id);
|
||||||
Set<Long> bookIds = library.getBookEntities().stream().map(BookEntity::getId).collect(Collectors.toSet());
|
Set<Long> bookIds = bookRepository.findBookIdsByLibraryId(id);
|
||||||
fileService.deleteBookCovers(bookIds);
|
fileService.deleteBookCovers(bookIds);
|
||||||
String libraryName = library.getName();
|
String libraryName = library.getName();
|
||||||
libraryRepository.deleteById(id);
|
libraryRepository.deleteById(id);
|
||||||
@@ -262,14 +266,12 @@ public class LibraryService {
|
|||||||
log.info("Library deleted successfully: {}", id);
|
log.info("Library deleted successfully: {}", id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public Book getBook(long libraryId, long bookId) {
|
public Book getBook(long libraryId, long bookId) {
|
||||||
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).filter(b -> b.getLibrary().getId() == libraryId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).filter(b -> b.getLibrary().getId() == libraryId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
return bookMapper.toBook(bookEntity);
|
return bookMapper.toBook(bookEntity);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<Book> getBooks(long libraryId) {
|
public List<Book> getBooks(long libraryId) {
|
||||||
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
List<BookEntity> bookEntities = bookRepository.findAllWithMetadataByLibraryId(libraryId);
|
List<BookEntity> bookEntities = bookRepository.findAllWithMetadataByLibraryId(libraryId);
|
||||||
@@ -285,7 +287,6 @@ public class LibraryService {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public Map<String, Long> getBookCountsByFormat(long libraryId) {
|
public Map<String, Long> getBookCountsByFormat(long libraryId) {
|
||||||
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
Map<String, Long> counts = new HashMap<>();
|
Map<String, Long> counts = new HashMap<>();
|
||||||
|
|||||||
@@ -226,7 +226,6 @@ public class BookMetadataService {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
bookMetadataUpdater.setBookMetadata(context);
|
bookMetadataUpdater.setBookMetadata(context);
|
||||||
bookRepository.save(bookEntity);
|
|
||||||
auditService.log(AuditAction.METADATA_UPDATED, "Book", bookId, "Updated metadata for book: " + bookEntity.getMetadata().getTitle());
|
auditService.log(AuditAction.METADATA_UPDATED, "Book", bookId, "Updated metadata for book: " + bookEntity.getMetadata().getTitle());
|
||||||
return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
|
return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ public class MetadataTaskService {
|
|||||||
private final FetchedProposalMapper fetchedProposalMapper;
|
private final FetchedProposalMapper fetchedProposalMapper;
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public Optional<MetadataTaskDetailsResponse> getTaskWithProposals(String taskId) {
|
public Optional<MetadataTaskDetailsResponse> getTaskWithProposals(String taskId) {
|
||||||
return metadataFetchTaskRepository.findById(taskId)
|
return metadataFetchTaskRepository.findById(taskId)
|
||||||
.map(this::buildTaskDetailsResponse);
|
.map(this::buildTaskDetailsResponse);
|
||||||
@@ -64,6 +65,7 @@ public class MetadataTaskService {
|
|||||||
.orElse(false);
|
.orElse(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
public boolean updateProposalStatus(String taskId, Long proposalId, String statusStr) {
|
public boolean updateProposalStatus(String taskId, Long proposalId, String statusStr) {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
Optional<FetchedMetadataProposalStatus> statusOpt = parseStatus(statusStr);
|
Optional<FetchedMetadataProposalStatus> statusOpt = parseStatus(statusStr);
|
||||||
@@ -134,4 +136,4 @@ public class MetadataTaskService {
|
|||||||
.filter(n -> n.getTotal() > 0)
|
.filter(n -> n.getTotal() > 0)
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ import java.util.stream.Collectors;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@Service
|
@Service
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public class ReadingProgressService {
|
public class ReadingProgressService {
|
||||||
|
|
||||||
private static final float READING_THRESHOLD = 0.1f;
|
private static final float READING_THRESHOLD = 0.1f;
|
||||||
|
|||||||
+71
-3
@@ -10,6 +10,7 @@ import org.booklore.model.entity.AuthorEntity;
|
|||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
import org.booklore.model.entity.BookMetadataEntity;
|
import org.booklore.model.entity.BookMetadataEntity;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
|
import org.booklore.repository.projection.BookEmbeddingProjection;
|
||||||
import org.booklore.service.book.BookQueryService;
|
import org.booklore.service.book.BookQueryService;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
@@ -26,6 +27,7 @@ import java.util.stream.Collectors;
|
|||||||
public class BookRecommendationService {
|
public class BookRecommendationService {
|
||||||
|
|
||||||
private final BookSimilarityService similarityService;
|
private final BookSimilarityService similarityService;
|
||||||
|
private final BookVectorService vectorService;
|
||||||
private final BookRepository bookRepository;
|
private final BookRepository bookRepository;
|
||||||
private final BookQueryService bookQueryService;
|
private final BookQueryService bookQueryService;
|
||||||
private final BookMapper bookMapper;
|
private final BookMapper bookMapper;
|
||||||
@@ -92,7 +94,74 @@ public class BookRecommendationService {
|
|||||||
protected List<BookRecommendation> findSimilarBooks(Long bookId, int limit) {
|
protected List<BookRecommendation> findSimilarBooks(Long bookId, int limit) {
|
||||||
BookEntity target = bookRepository.findByIdWithMetadata(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
BookEntity target = bookRepository.findByIdWithMetadata(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
|
|
||||||
List<BookEntity> candidates = bookQueryService.getAllFullBookEntities();
|
String targetVectorJson = Optional.ofNullable(target.getMetadata())
|
||||||
|
.map(BookMetadataEntity::getEmbeddingVector)
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (targetVectorJson != null) {
|
||||||
|
double[] targetVector = vectorService.deserializeVector(targetVectorJson);
|
||||||
|
if (targetVector != null) {
|
||||||
|
return findSimilarBooksViaEmbeddings(bookId, target, targetVector, limit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: entity-based similarity (loads all candidates)
|
||||||
|
return findSimilarBooksViaEntities(bookId, target, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<BookRecommendation> findSimilarBooksViaEmbeddings(Long bookId, BookEntity target, double[] targetVector, int limit) {
|
||||||
|
String targetSeriesName = Optional.ofNullable(target.getMetadata())
|
||||||
|
.map(BookMetadataEntity::getSeriesName)
|
||||||
|
.map(String::toLowerCase)
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
List<BookEmbeddingProjection> projections = bookRepository.findAllEmbeddingsForRecommendation(bookId);
|
||||||
|
|
||||||
|
List<SimpleEntry<Long, Double>> scored = projections.stream()
|
||||||
|
.filter(p -> {
|
||||||
|
if (targetSeriesName == null) return true;
|
||||||
|
String candidateSeries = Optional.ofNullable(p.getSeriesName())
|
||||||
|
.map(String::toLowerCase)
|
||||||
|
.orElse(null);
|
||||||
|
return !targetSeriesName.equals(candidateSeries);
|
||||||
|
})
|
||||||
|
.map(p -> {
|
||||||
|
double[] candidateVector = vectorService.deserializeVector(p.getEmbeddingVector());
|
||||||
|
double similarity = candidateVector != null
|
||||||
|
? vectorService.cosineSimilarity(targetVector, candidateVector)
|
||||||
|
: 0.0;
|
||||||
|
return new SimpleEntry<>(p.getBookId(), similarity);
|
||||||
|
})
|
||||||
|
.filter(entry -> entry.getValue() > 0.1)
|
||||||
|
.sorted(Map.Entry.<Long, Double>comparingByValue().reversed())
|
||||||
|
.limit(limit * 3L)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
Set<Long> topBookIds = scored.stream().map(SimpleEntry::getKey).collect(Collectors.toSet());
|
||||||
|
Map<Long, BookEntity> bookMap = bookQueryService.findAllWithMetadataByIds(topBookIds).stream()
|
||||||
|
.collect(Collectors.toMap(BookEntity::getId, Function.identity()));
|
||||||
|
|
||||||
|
Map<String, Integer> authorCounts = new HashMap<>();
|
||||||
|
List<BookRecommendation> recommendations = new ArrayList<>();
|
||||||
|
|
||||||
|
for (SimpleEntry<Long, Double> entry : scored) {
|
||||||
|
if (recommendations.size() >= limit) break;
|
||||||
|
BookEntity bookEntity = bookMap.get(entry.getKey());
|
||||||
|
if (bookEntity == null) continue;
|
||||||
|
Set<String> authorNames = getAuthorNames(bookEntity);
|
||||||
|
boolean allowed = authorNames.stream()
|
||||||
|
.allMatch(name -> authorCounts.getOrDefault(name, 0) < MAX_BOOKS_PER_AUTHOR);
|
||||||
|
if (allowed) {
|
||||||
|
recommendations.add(new BookRecommendation(bookMapper.toBookWithDescription(bookEntity, false), entry.getValue()));
|
||||||
|
authorNames.forEach(name -> authorCounts.merge(name, 1, Integer::sum));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return recommendations;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<BookRecommendation> findSimilarBooksViaEntities(Long bookId, BookEntity target, int limit) {
|
||||||
|
List<BookEntity> candidates = bookRepository.findAllForRecommendation(bookId);
|
||||||
|
|
||||||
String targetSeriesName = Optional.ofNullable(target.getMetadata())
|
String targetSeriesName = Optional.ofNullable(target.getMetadata())
|
||||||
.map(BookMetadataEntity::getSeriesName)
|
.map(BookMetadataEntity::getSeriesName)
|
||||||
@@ -100,7 +169,6 @@ public class BookRecommendationService {
|
|||||||
.orElse(null);
|
.orElse(null);
|
||||||
|
|
||||||
List<SimpleEntry<BookEntity, Double>> scored = candidates.stream()
|
List<SimpleEntry<BookEntity, Double>> scored = candidates.stream()
|
||||||
.filter(candidate -> !candidate.getId().equals(bookId))
|
|
||||||
.filter(candidate -> {
|
.filter(candidate -> {
|
||||||
String candidateSeriesName = Optional.ofNullable(candidate.getMetadata())
|
String candidateSeriesName = Optional.ofNullable(candidate.getMetadata())
|
||||||
.map(BookMetadataEntity::getSeriesName)
|
.map(BookMetadataEntity::getSeriesName)
|
||||||
@@ -140,4 +208,4 @@ public class BookRecommendationService {
|
|||||||
.map(String::toLowerCase)
|
.map(String::toLowerCase)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-3
@@ -23,19 +23,18 @@ import java.util.stream.Collectors;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public class ContentRestrictionService {
|
public class ContentRestrictionService {
|
||||||
|
|
||||||
private final UserContentRestrictionRepository restrictionRepository;
|
private final UserContentRestrictionRepository restrictionRepository;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<ContentRestriction> getUserRestrictions(Long userId) {
|
public List<ContentRestriction> getUserRestrictions(Long userId) {
|
||||||
return restrictionRepository.findByUserId(userId).stream()
|
return restrictionRepository.findByUserId(userId).stream()
|
||||||
.map(this::toDto)
|
.map(this::toDto)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public ContentRestriction getRestriction(Long restrictionId) {
|
public ContentRestriction getRestriction(Long restrictionId) {
|
||||||
return restrictionRepository.findById(restrictionId)
|
return restrictionRepository.findById(restrictionId)
|
||||||
.map(this::toDto)
|
.map(this::toDto)
|
||||||
@@ -96,7 +95,6 @@ public class ContentRestrictionService {
|
|||||||
restrictionRepository.deleteByUserId(userId);
|
restrictionRepository.deleteByUserId(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public List<BookEntity> applyRestrictions(List<BookEntity> books, Long userId) {
|
public List<BookEntity> applyRestrictions(List<BookEntity> books, Long userId) {
|
||||||
List<UserContentRestrictionEntity> restrictions = restrictionRepository.findByUserId(userId);
|
List<UserContentRestrictionEntity> restrictions = restrictionRepository.findByUserId(userId);
|
||||||
|
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ public class FileUploadService {
|
|||||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||||
private final AuditService auditService;
|
private final AuditService auditService;
|
||||||
|
|
||||||
|
@Transactional
|
||||||
public void uploadFile(MultipartFile file, long libraryId, long pathId) {
|
public void uploadFile(MultipartFile file, long libraryId, long pathId) {
|
||||||
validateFile(file);
|
validateFile(file);
|
||||||
|
|
||||||
|
|||||||
+2
-4
@@ -29,6 +29,7 @@ import static org.booklore.model.enums.PermissionType.MANAGE_LIBRARY;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
|
@Transactional(readOnly = true)
|
||||||
public class BookFilePersistenceService {
|
public class BookFilePersistenceService {
|
||||||
|
|
||||||
private final EntityManager entityManager;
|
private final EntityManager entityManager;
|
||||||
@@ -103,12 +104,10 @@ public class BookFilePersistenceService {
|
|||||||
return books.size();
|
return books.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public Optional<BookEntity> findByLibraryPathSubPathAndFileName(long libraryPathId, String fileSubPath, String fileName) {
|
public Optional<BookEntity> findByLibraryPathSubPathAndFileName(long libraryPathId, String fileSubPath, String fileName) {
|
||||||
return bookRepository.findByLibraryPath_IdAndFileSubPathAndFileName(libraryPathId, fileSubPath, fileName);
|
return bookRepository.findByLibraryPath_IdAndFileSubPathAndFileName(libraryPathId, fileSubPath, fileName);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public Optional<BookFileEntity> findBookFileByLibraryPathSubPathAndFileName(long libraryPathId, String fileSubPath, String fileName) {
|
public Optional<BookFileEntity> findBookFileByLibraryPathSubPathAndFileName(long libraryPathId, String fileSubPath, String fileName) {
|
||||||
return bookFileRepository.findByLibraryPathIdAndFileSubPathAndFileName(libraryPathId, fileSubPath, fileName);
|
return bookFileRepository.findByLibraryPathIdAndFileSubPathAndFileName(libraryPathId, fileSubPath, fileName);
|
||||||
}
|
}
|
||||||
@@ -130,7 +129,6 @@ public class BookFilePersistenceService {
|
|||||||
bookRepository.save(book);
|
bookRepository.save(book);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public long countBookFilesByBookId(Long bookId) {
|
public long countBookFilesByBookId(Long bookId) {
|
||||||
return bookFileRepository.countByBookId(bookId);
|
return bookFileRepository.countByBookId(bookId);
|
||||||
}
|
}
|
||||||
@@ -165,4 +163,4 @@ public class BookFilePersistenceService {
|
|||||||
bookMapper.toBookWithDescription(book, false), Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
|
bookMapper.toBookWithDescription(book, false), Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
|
||||||
log.info("[RECOVERED] Book id={} recovered from folder move", book.getId());
|
log.info("[RECOVERED] Book id={} recovered from folder move", book.getId());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -129,7 +129,7 @@ public class LibraryFileEventProcessor {
|
|||||||
log.info("[PROCESS] '{}' event for '{}'{}", event.eventKind().name(), fileName,
|
log.info("[PROCESS] '{}' event for '{}'{}", event.eventKind().name(), fileName,
|
||||||
event.isDirectory() ? " (directory)" : "");
|
event.isDirectory() ? " (directory)" : "");
|
||||||
|
|
||||||
LibraryEntity library = libraryRepository.findById(event.libraryId())
|
LibraryEntity library = libraryRepository.findByIdWithPaths(event.libraryId())
|
||||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(event.libraryId()));
|
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(event.libraryId()));
|
||||||
|
|
||||||
if (library.getLibraryPaths().stream().noneMatch(lp -> path.startsWith(lp.getPath()))) {
|
if (library.getLibraryPaths().stream().noneMatch(lp -> path.startsWith(lp.getPath()))) {
|
||||||
@@ -561,4 +561,4 @@ public class LibraryFileEventProcessor {
|
|||||||
|
|
||||||
public record FileEvent(WatchEvent.Kind<?> eventKind, long libraryId, Path fullPath, boolean isDirectory) {
|
public record FileEvent(WatchEvent.Kind<?> eventKind, long libraryId, Path fullPath, boolean isDirectory) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+60
-44
@@ -17,9 +17,9 @@ import org.booklore.service.recommender.BookVectorService;
|
|||||||
import org.booklore.task.TaskStatus;
|
import org.booklore.task.TaskStatus;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@@ -33,6 +33,7 @@ public class BookRecommendationUpdaterTask implements Task {
|
|||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
|
|
||||||
private static final int RECOMMENDATION_LIMIT = 25;
|
private static final int RECOMMENDATION_LIMIT = 25;
|
||||||
|
private static final int BATCH_SIZE = 500;
|
||||||
private static final long MIN_NOTIFICATION_INTERVAL_MS = 250;
|
private static final long MIN_NOTIFICATION_INTERVAL_MS = 250;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -57,62 +58,77 @@ public class BookRecommendationUpdaterTask implements Task {
|
|||||||
|
|
||||||
lastNotificationTime = sendTaskProgressNotification(taskId, 0, "Starting book recommendation update", TaskStatus.IN_PROGRESS, lastNotificationTime, true);
|
lastNotificationTime = sendTaskProgressNotification(taskId, 0, "Starting book recommendation update", TaskStatus.IN_PROGRESS, lastNotificationTime, true);
|
||||||
|
|
||||||
List<BookEntity> allBooks = bookQueryService.getAllFullBookEntities();
|
// Load books in batches, generate embeddings, store lightweight data only
|
||||||
int totalBooks = allBooks.size();
|
long totalBooks = bookQueryService.countAllNonDeleted();
|
||||||
|
|
||||||
lastNotificationTime = sendTaskProgressNotification(taskId, 5, String.format("Loaded %d books, generating embeddings...", totalBooks), TaskStatus.IN_PROGRESS, lastNotificationTime, false);
|
|
||||||
|
|
||||||
Map<Long, double[]> embeddings = new HashMap<>();
|
Map<Long, double[]> embeddings = new HashMap<>();
|
||||||
List<BookEntity> booksToUpdate = new ArrayList<>();
|
Map<Long, String> seriesNames = new HashMap<>();
|
||||||
|
|
||||||
|
lastNotificationTime = sendTaskProgressNotification(taskId, 2, String.format("Found %d books, generating embeddings in batches...", totalBooks), TaskStatus.IN_PROGRESS, lastNotificationTime, false);
|
||||||
|
|
||||||
int embeddingProgress = 0;
|
int embeddingProgress = 0;
|
||||||
for (BookEntity book : allBooks) {
|
int batchPage = 0;
|
||||||
double[] embedding = vectorService.generateEmbedding(book);
|
while (true) {
|
||||||
embeddings.put(book.getId(), embedding);
|
List<BookEntity> batch = bookQueryService.getAllFullBookEntitiesBatch(
|
||||||
|
PageRequest.of(batchPage, BATCH_SIZE));
|
||||||
|
if (batch.isEmpty()) break;
|
||||||
|
|
||||||
if (book.getMetadata() != null) {
|
for (BookEntity book : batch) {
|
||||||
String embeddingJson = vectorService.serializeVector(embedding);
|
double[] embedding = vectorService.generateEmbedding(book);
|
||||||
if (!Objects.equals(book.getMetadata().getEmbeddingVector(), embeddingJson)) {
|
embeddings.put(book.getId(), embedding);
|
||||||
book.getMetadata().setEmbeddingVector(embeddingJson);
|
|
||||||
book.getMetadata().setEmbeddingUpdatedAt(Instant.now());
|
// Store series name for similarity filtering
|
||||||
|
String series = Optional.ofNullable(book.getMetadata())
|
||||||
|
.map(BookMetadataEntity::getSeriesName)
|
||||||
|
.map(String::toLowerCase)
|
||||||
|
.orElse(null);
|
||||||
|
if (series != null) {
|
||||||
|
seriesNames.put(book.getId(), series);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
embeddingProgress++;
|
||||||
}
|
}
|
||||||
|
|
||||||
embeddingProgress++;
|
// Save embedding vectors for this batch within a transaction
|
||||||
if (embeddingProgress % 10 == 0 || embeddingProgress == totalBooks) {
|
Map<Long, String> batchEmbeddingJson = new HashMap<>();
|
||||||
int progress = 5 + (embeddingProgress * 30 / totalBooks);
|
for (BookEntity book : batch) {
|
||||||
lastNotificationTime = sendTaskProgressNotification(taskId, progress,
|
batchEmbeddingJson.put(book.getId(), vectorService.serializeVector(embeddings.get(book.getId())));
|
||||||
String.format("Generated embeddings: %d/%d books", embeddingProgress, totalBooks),
|
|
||||||
TaskStatus.IN_PROGRESS, lastNotificationTime, false);
|
|
||||||
}
|
}
|
||||||
|
bookQueryService.compareAndSaveEmbeddings(batchEmbeddingJson);
|
||||||
|
|
||||||
|
int progress = 5 + (int) (embeddingProgress * 30L / totalBooks);
|
||||||
|
lastNotificationTime = sendTaskProgressNotification(taskId, progress,
|
||||||
|
String.format("Generated embeddings: %d/%d books", embeddingProgress, totalBooks),
|
||||||
|
TaskStatus.IN_PROGRESS, lastNotificationTime, false);
|
||||||
|
|
||||||
|
if (batch.size() < BATCH_SIZE) break;
|
||||||
|
batchPage++;
|
||||||
}
|
}
|
||||||
|
|
||||||
lastNotificationTime = sendTaskProgressNotification(taskId, 35, "Computing book similarities...", TaskStatus.IN_PROGRESS, lastNotificationTime, false);
|
lastNotificationTime = sendTaskProgressNotification(taskId, 35, "Computing book similarities...", TaskStatus.IN_PROGRESS, lastNotificationTime, false);
|
||||||
|
|
||||||
|
// Compute similarities using only in-memory vectors (no entities needed)
|
||||||
|
Set<Long> allBookIds = embeddings.keySet();
|
||||||
|
Map<Long, Set<BookRecommendationLite>> allRecommendations = new HashMap<>();
|
||||||
|
|
||||||
int processedBooks = 0;
|
int processedBooks = 0;
|
||||||
for (BookEntity targetBook : allBooks) {
|
for (Long targetId : allBookIds) {
|
||||||
try {
|
try {
|
||||||
double[] targetVector = embeddings.get(targetBook.getId());
|
double[] targetVector = embeddings.get(targetId);
|
||||||
if (targetVector == null) continue;
|
if (targetVector == null) continue;
|
||||||
|
|
||||||
String targetSeries = Optional.ofNullable(targetBook.getMetadata())
|
String targetSeries = seriesNames.get(targetId);
|
||||||
.map(BookMetadataEntity::getSeriesName)
|
|
||||||
.map(String::toLowerCase)
|
|
||||||
.orElse(null);
|
|
||||||
|
|
||||||
List<BookVectorService.ScoredBook> candidates = allBooks.stream()
|
List<BookVectorService.ScoredBook> candidates = allBookIds.stream()
|
||||||
.filter(candidate -> !candidate.getId().equals(targetBook.getId()))
|
.filter(candidateId -> !candidateId.equals(targetId))
|
||||||
.filter(candidate -> {
|
.filter(candidateId -> {
|
||||||
String candidateSeries = Optional.ofNullable(candidate.getMetadata())
|
if (targetSeries == null) return true;
|
||||||
.map(BookMetadataEntity::getSeriesName)
|
String candidateSeries = seriesNames.get(candidateId);
|
||||||
.map(String::toLowerCase)
|
return !targetSeries.equals(candidateSeries);
|
||||||
.orElse(null);
|
|
||||||
return targetSeries == null || !targetSeries.equals(candidateSeries);
|
|
||||||
})
|
})
|
||||||
.map(candidate -> {
|
.map(candidateId -> {
|
||||||
double[] candidateVector = embeddings.get(candidate.getId());
|
double[] candidateVector = embeddings.get(candidateId);
|
||||||
double similarity = vectorService.cosineSimilarity(targetVector, candidateVector);
|
double similarity = vectorService.cosineSimilarity(targetVector, candidateVector);
|
||||||
return new BookVectorService.ScoredBook(candidate.getId(), similarity);
|
return new BookVectorService.ScoredBook(candidateId, similarity);
|
||||||
})
|
})
|
||||||
.filter(scored -> scored.getScore() > 0.1)
|
.filter(scored -> scored.getScore() > 0.1)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
@@ -127,25 +143,25 @@ public class BookRecommendationUpdaterTask implements Task {
|
|||||||
.map(scored -> new BookRecommendationLite(scored.getBookId(), scored.getScore()))
|
.map(scored -> new BookRecommendationLite(scored.getBookId(), scored.getScore()))
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
targetBook.setSimilarBooksJson(recommendations);
|
allRecommendations.put(targetId, recommendations);
|
||||||
booksToUpdate.add(targetBook);
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("{}: Error updating similar books for book ID {}", getTaskType(), targetBook.getId(), e);
|
log.error("{}: Error computing similarity for book ID {}", getTaskType(), targetId, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
processedBooks++;
|
processedBooks++;
|
||||||
if (processedBooks % 10 == 0 || processedBooks == totalBooks) {
|
if (processedBooks % 10 == 0 || processedBooks == totalBooks) {
|
||||||
int progress = 35 + (processedBooks * 50 / totalBooks);
|
int progress = 35 + (int) (processedBooks * 50L / totalBooks);
|
||||||
lastNotificationTime = sendTaskProgressNotification(taskId, progress,
|
lastNotificationTime = sendTaskProgressNotification(taskId, progress,
|
||||||
String.format("Computing similarities: %d/%d books", processedBooks, totalBooks),
|
String.format("Computing similarities: %d/%d books", processedBooks, totalBooks),
|
||||||
TaskStatus.IN_PROGRESS, lastNotificationTime, false);
|
TaskStatus.IN_PROGRESS, lastNotificationTime, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
lastNotificationTime = sendTaskProgressNotification(taskId, 85, String.format("Saving recommendations for %d books...", booksToUpdate.size()), TaskStatus.IN_PROGRESS, lastNotificationTime, false);
|
// Save recommendations in batches
|
||||||
|
lastNotificationTime = sendTaskProgressNotification(taskId, 85, String.format("Saving recommendations for %d books...", allRecommendations.size()), TaskStatus.IN_PROGRESS, lastNotificationTime, false);
|
||||||
|
|
||||||
bookQueryService.saveAll(booksToUpdate);
|
bookQueryService.saveRecommendationsInBatches(allRecommendations, BATCH_SIZE);
|
||||||
|
|
||||||
long endTime = System.currentTimeMillis();
|
long endTime = System.currentTimeMillis();
|
||||||
log.info("{}: Task completed. Duration: {} ms", getTaskType(), endTime - startTime);
|
log.info("{}: Task completed. Duration: {} ms", getTaskType(), endTime - startTime);
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ public class EpubCfiService {
|
|||||||
|
|
||||||
public EpubCfiService() {
|
public EpubCfiService() {
|
||||||
this.documentCache = Caffeine.newBuilder()
|
this.documentCache = Caffeine.newBuilder()
|
||||||
.maximumSize(50)
|
.maximumSize(10)
|
||||||
.expireAfterAccess(Duration.ofMinutes(10))
|
.expireAfterAccess(Duration.ofMinutes(5))
|
||||||
.softValues()
|
.softValues()
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ app:
|
|||||||
disk-type: ${DISK_TYPE:LOCAL}
|
disk-type: ${DISK_TYPE:LOCAL}
|
||||||
|
|
||||||
server:
|
server:
|
||||||
max-http-header-size: 128KB
|
|
||||||
forward-headers-strategy: native
|
forward-headers-strategy: native
|
||||||
port: ${BOOKLORE_PORT:6060}
|
port: ${BOOKLORE_PORT:6060}
|
||||||
compression:
|
compression:
|
||||||
@@ -34,8 +33,9 @@ server:
|
|||||||
tomcat:
|
tomcat:
|
||||||
relaxed-query-chars: '[,],%,{,},|'
|
relaxed-query-chars: '[,],%,{,},|'
|
||||||
threads:
|
threads:
|
||||||
max: 20 # Virtual threads handle concurrency; platform threads just overhead
|
max: 10 # Virtual threads handle concurrency; platform threads just overhead
|
||||||
min-spare: 4
|
min-spare: 2
|
||||||
|
max-http-request-header-size: 64KB
|
||||||
|
|
||||||
spring:
|
spring:
|
||||||
jackson:
|
jackson:
|
||||||
@@ -62,6 +62,7 @@ spring:
|
|||||||
password: ${DATABASE_PASSWORD:${MYSQL_ROOT_PASSWORD}}
|
password: ${DATABASE_PASSWORD:${MYSQL_ROOT_PASSWORD}}
|
||||||
hikari:
|
hikari:
|
||||||
pool-name: BookloreHikariPool
|
pool-name: BookloreHikariPool
|
||||||
|
auto-commit: false # Required counterpart to provider_disables_autocommit
|
||||||
max-lifetime: 580000 # 9.6 minutes (avoid DB-side connection cuts)
|
max-lifetime: 580000 # 9.6 minutes (avoid DB-side connection cuts)
|
||||||
connection-test-query: SELECT 1
|
connection-test-query: SELECT 1
|
||||||
connection-timeout: 30000 # 30s to acquire a connection before timeout
|
connection-timeout: 30000 # 30s to acquire a connection before timeout
|
||||||
@@ -69,7 +70,7 @@ spring:
|
|||||||
minimum-idle: 2 # Minimal warm connections; virtual threads handle bursts
|
minimum-idle: 2 # Minimal warm connections; virtual threads handle bursts
|
||||||
idle-timeout: 300000 # 5 minutes before idle connections are closed
|
idle-timeout: 300000 # 5 minutes before idle connections are closed
|
||||||
jpa:
|
jpa:
|
||||||
open-in-view: true # true until we implement proper DTOs and service-layer data fetching
|
open-in-view: false
|
||||||
hibernate:
|
hibernate:
|
||||||
naming:
|
naming:
|
||||||
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
|
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
|
||||||
@@ -78,16 +79,21 @@ spring:
|
|||||||
hibernate:
|
hibernate:
|
||||||
query:
|
query:
|
||||||
timeout: 30 # 30s max for any HQL/JPQL query
|
timeout: 30 # 30s max for any HQL/JPQL query
|
||||||
plan_cache_max_size: 256 # Reduce from 2048 default; ~200 unique queries max
|
plan_cache_max_size: 128 # Reduce from 2048 default; small self-hosted app
|
||||||
|
plan_parameter_metadata_max_size: 32 # Reduce from 128 default
|
||||||
in_clause_parameter_padding: true # Pad IN params to power-of-2; fewer unique plan cache entries
|
in_clause_parameter_padding: true # Pad IN params to power-of-2; fewer unique plan cache entries
|
||||||
|
fail_on_pagination_over_collection_fetch: true # Fail fast when paginating over collection fetches (in-memory pagination)
|
||||||
jdbc:
|
jdbc:
|
||||||
time_zone: UTC
|
time_zone: UTC
|
||||||
batch_size: 500
|
batch_size: 100
|
||||||
fetch_size: 50 # Reduce JDBC roundtrips for large result sets
|
fetch_size: 50 # Reduce JDBC roundtrips for large result sets
|
||||||
order_inserts: true
|
order_inserts: true
|
||||||
order_updates: true
|
order_updates: true
|
||||||
batch_versioned_data: true # Allow batching UPDATEs on @Version entities
|
batch_versioned_data: true # Allow batching UPDATEs on @Version entities
|
||||||
|
connection:
|
||||||
|
provider_disables_autocommit: true # Skip unnecessary JDBC autocommit check; reduces roundtrips
|
||||||
default_batch_fetch_size: 16 # Global batch fetch for all lazy collections (prevents N+1)
|
default_batch_fetch_size: 16 # Global batch fetch for all lazy collections (prevents N+1)
|
||||||
|
log_slow_query: ${HIBERNATE_SLOW_QUERY_MS:500} # Log queries taking longer than 500ms (see org.hibernate.SQL_SLOW)
|
||||||
generate_statistics: ${HIBERNATE_STATISTICS:false}
|
generate_statistics: ${HIBERNATE_STATISTICS:false}
|
||||||
threads:
|
threads:
|
||||||
virtual:
|
virtual:
|
||||||
|
|||||||
+1
-1
@@ -149,7 +149,7 @@ class LogoutServiceTest {
|
|||||||
assertThat(token1.getRevocationDate()).isNotNull();
|
assertThat(token1.getRevocationDate()).isNotNull();
|
||||||
assertThat(token2.isRevoked()).isTrue();
|
assertThat(token2.isRevoked()).isTrue();
|
||||||
assertThat(token2.getRevocationDate()).isNotNull();
|
assertThat(token2.getRevocationDate()).isNotNull();
|
||||||
verify(refreshTokenRepository, times(2)).save(any(RefreshTokenEntity.class));
|
verify(refreshTokenRepository).saveAll(any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+6
-4
@@ -8,6 +8,7 @@ import org.booklore.model.entity.BookMetadataEntity;
|
|||||||
import org.booklore.model.entity.LibraryEntity;
|
import org.booklore.model.entity.LibraryEntity;
|
||||||
import org.booklore.model.entity.LibraryPathEntity;
|
import org.booklore.model.entity.LibraryPathEntity;
|
||||||
import org.booklore.service.task.TaskCronService;
|
import org.booklore.service.task.TaskCronService;
|
||||||
|
import org.flywaydb.core.Flyway;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
@@ -44,7 +45,8 @@ import static org.mockito.Mockito.mock;
|
|||||||
"spring.task.scheduling.enabled=false",
|
"spring.task.scheduling.enabled=false",
|
||||||
"app.task.scan-library-cron=*/1 * * * * *",
|
"app.task.scan-library-cron=*/1 * * * * *",
|
||||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||||
"app.features.oidc-enabled=false"
|
"app.features.oidc-enabled=false",
|
||||||
|
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||||
})
|
})
|
||||||
@Import(BookOpdsRepositoryDataJpaTest.TestConfig.class)
|
@Import(BookOpdsRepositoryDataJpaTest.TestConfig.class)
|
||||||
class BookOpdsRepositoryDataJpaTest {
|
class BookOpdsRepositoryDataJpaTest {
|
||||||
@@ -59,8 +61,8 @@ class BookOpdsRepositoryDataJpaTest {
|
|||||||
public static class TestConfig {
|
public static class TestConfig {
|
||||||
@Bean("flyway")
|
@Bean("flyway")
|
||||||
@Primary
|
@Primary
|
||||||
public org.flywaydb.core.Flyway flyway() {
|
public Flyway flyway() {
|
||||||
return mock(org.flywaydb.core.Flyway.class);
|
return mock(Flyway.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -113,4 +115,4 @@ class BookOpdsRepositoryDataJpaTest {
|
|||||||
assertThat(result).hasSize(1);
|
assertThat(result).hasSize(1);
|
||||||
assertThat(result.get(0).getId()).isEqualTo(book.getId());
|
assertThat(result.get(0).getId()).isEqualTo(book.getId());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,7 +48,8 @@ import static org.mockito.Mockito.mock;
|
|||||||
"spring.task.scheduling.enabled=false",
|
"spring.task.scheduling.enabled=false",
|
||||||
"app.task.scan-library-cron=*/1 * * * * *",
|
"app.task.scan-library-cron=*/1 * * * * *",
|
||||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||||
"app.features.oidc-enabled=false"
|
"app.features.oidc-enabled=false",
|
||||||
|
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||||
})
|
})
|
||||||
@Import(BookRuleEvaluatorEdgeCasesTest.TestConfig.class)
|
@Import(BookRuleEvaluatorEdgeCasesTest.TestConfig.class)
|
||||||
class BookRuleEvaluatorEdgeCasesTest {
|
class BookRuleEvaluatorEdgeCasesTest {
|
||||||
|
|||||||
+5
-3
@@ -8,6 +8,7 @@ import org.booklore.model.entity.*;
|
|||||||
import org.booklore.model.enums.ReadStatus;
|
import org.booklore.model.enums.ReadStatus;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.service.task.TaskCronService;
|
import org.booklore.service.task.TaskCronService;
|
||||||
|
import org.flywaydb.core.Flyway;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Nested;
|
import org.junit.jupiter.api.Nested;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -52,7 +53,8 @@ import static org.mockito.Mockito.mock;
|
|||||||
"spring.task.scheduling.enabled=false",
|
"spring.task.scheduling.enabled=false",
|
||||||
"app.task.scan-library-cron=*/1 * * * * *",
|
"app.task.scan-library-cron=*/1 * * * * *",
|
||||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||||
"app.features.oidc-enabled=false"
|
"app.features.oidc-enabled=false",
|
||||||
|
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||||
})
|
})
|
||||||
@Import(BookRuleEvaluatorFieldCoverageTest.TestConfig.class)
|
@Import(BookRuleEvaluatorFieldCoverageTest.TestConfig.class)
|
||||||
class BookRuleEvaluatorFieldCoverageTest {
|
class BookRuleEvaluatorFieldCoverageTest {
|
||||||
@@ -61,8 +63,8 @@ class BookRuleEvaluatorFieldCoverageTest {
|
|||||||
static class TestConfig {
|
static class TestConfig {
|
||||||
@Bean("flyway")
|
@Bean("flyway")
|
||||||
@Primary
|
@Primary
|
||||||
public org.flywaydb.core.Flyway flyway() {
|
public Flyway flyway() {
|
||||||
return mock(org.flywaydb.core.Flyway.class);
|
return mock(Flyway.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
|||||||
+5
-3
@@ -9,6 +9,7 @@ import org.booklore.model.enums.BookFileType;
|
|||||||
import org.booklore.model.enums.ReadStatus;
|
import org.booklore.model.enums.ReadStatus;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.service.task.TaskCronService;
|
import org.booklore.service.task.TaskCronService;
|
||||||
|
import org.flywaydb.core.Flyway;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Nested;
|
import org.junit.jupiter.api.Nested;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -45,7 +46,8 @@ import static org.mockito.Mockito.mock;
|
|||||||
"spring.task.scheduling.enabled=false",
|
"spring.task.scheduling.enabled=false",
|
||||||
"app.task.scan-library-cron=*/1 * * * * *",
|
"app.task.scan-library-cron=*/1 * * * * *",
|
||||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||||
"app.features.oidc-enabled=false"
|
"app.features.oidc-enabled=false",
|
||||||
|
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||||
})
|
})
|
||||||
@Import(BookRuleEvaluatorNumericFieldsTest.TestConfig.class)
|
@Import(BookRuleEvaluatorNumericFieldsTest.TestConfig.class)
|
||||||
class BookRuleEvaluatorNumericFieldsTest {
|
class BookRuleEvaluatorNumericFieldsTest {
|
||||||
@@ -54,8 +56,8 @@ class BookRuleEvaluatorNumericFieldsTest {
|
|||||||
static class TestConfig {
|
static class TestConfig {
|
||||||
@Bean("flyway")
|
@Bean("flyway")
|
||||||
@Primary
|
@Primary
|
||||||
public org.flywaydb.core.Flyway flyway() {
|
public Flyway flyway() {
|
||||||
return mock(org.flywaydb.core.Flyway.class);
|
return mock(Flyway.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
|||||||
+5
-3
@@ -10,6 +10,7 @@ import org.booklore.model.enums.ComicCreatorRole;
|
|||||||
import org.booklore.model.enums.ReadStatus;
|
import org.booklore.model.enums.ReadStatus;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.service.task.TaskCronService;
|
import org.booklore.service.task.TaskCronService;
|
||||||
|
import org.flywaydb.core.Flyway;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Nested;
|
import org.junit.jupiter.api.Nested;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -51,7 +52,8 @@ import static org.mockito.Mockito.mock;
|
|||||||
"spring.task.scheduling.enabled=false",
|
"spring.task.scheduling.enabled=false",
|
||||||
"app.task.scan-library-cron=*/1 * * * * *",
|
"app.task.scan-library-cron=*/1 * * * * *",
|
||||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||||
"app.features.oidc-enabled=false"
|
"app.features.oidc-enabled=false",
|
||||||
|
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||||
})
|
})
|
||||||
@Import(BookRuleEvaluatorServiceIntegrationTest.TestConfig.class)
|
@Import(BookRuleEvaluatorServiceIntegrationTest.TestConfig.class)
|
||||||
class BookRuleEvaluatorServiceIntegrationTest {
|
class BookRuleEvaluatorServiceIntegrationTest {
|
||||||
@@ -60,8 +62,8 @@ class BookRuleEvaluatorServiceIntegrationTest {
|
|||||||
static class TestConfig {
|
static class TestConfig {
|
||||||
@Bean("flyway")
|
@Bean("flyway")
|
||||||
@Primary
|
@Primary
|
||||||
public org.flywaydb.core.Flyway flyway() {
|
public Flyway flyway() {
|
||||||
return mock(org.flywaydb.core.Flyway.class);
|
return mock(Flyway.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
|||||||
@@ -0,0 +1,962 @@
|
|||||||
|
package org.booklore.service;
|
||||||
|
|
||||||
|
import jakarta.persistence.EntityManager;
|
||||||
|
import jakarta.persistence.PersistenceContext;
|
||||||
|
import org.booklore.BookloreApplication;
|
||||||
|
import org.booklore.model.entity.*;
|
||||||
|
import org.booklore.model.enums.BookFileType;
|
||||||
|
import org.booklore.repository.BookRepository;
|
||||||
|
import org.booklore.repository.LibraryRepository;
|
||||||
|
import org.booklore.service.task.TaskCronService;
|
||||||
|
import org.flywaydb.core.Flyway;
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Nested;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.context.annotation.Primary;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Integration tests verifying Hibernate entity relationships, lazy loading,
|
||||||
|
* and transaction boundaries work correctly after the Hibernate refactoring.
|
||||||
|
*
|
||||||
|
* These tests run against H2 with create-drop DDL, exercising real JPA persistence
|
||||||
|
* to catch regressions that unit tests with mocks cannot detect.
|
||||||
|
*/
|
||||||
|
@SpringBootTest(classes = BookloreApplication.class)
|
||||||
|
@Transactional
|
||||||
|
@TestPropertySource(properties = {
|
||||||
|
"spring.flyway.enabled=false",
|
||||||
|
"spring.jpa.hibernate.ddl-auto=create-drop",
|
||||||
|
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
|
||||||
|
"spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect",
|
||||||
|
"spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1",
|
||||||
|
"spring.datasource.driver-class-name=org.h2.Driver",
|
||||||
|
"spring.datasource.username=sa",
|
||||||
|
"spring.datasource.password=",
|
||||||
|
"app.path-config=build/tmp/test-config",
|
||||||
|
"app.bookdrop-folder=build/tmp/test-bookdrop",
|
||||||
|
"spring.main.allow-bean-definition-overriding=true",
|
||||||
|
"spring.task.scheduling.enabled=false",
|
||||||
|
"app.task.scan-library-cron=*/1 * * * * *",
|
||||||
|
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||||
|
"app.features.oidc-enabled=false",
|
||||||
|
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||||
|
})
|
||||||
|
@Import(HibernateRegressionTest.TestConfig.class)
|
||||||
|
class HibernateRegressionTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private LibraryRepository libraryRepository;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private BookRepository bookRepository;
|
||||||
|
|
||||||
|
@PersistenceContext
|
||||||
|
private EntityManager entityManager;
|
||||||
|
|
||||||
|
@org.springframework.boot.test.context.TestConfiguration
|
||||||
|
public static class TestConfig {
|
||||||
|
@Bean("flyway")
|
||||||
|
@Primary
|
||||||
|
public Flyway flyway() {
|
||||||
|
return mock(Flyway.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Primary
|
||||||
|
public TaskCronService taskCronService() {
|
||||||
|
return mock(TaskCronService.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void contextLoads() {
|
||||||
|
assertThat(libraryRepository).isNotNull();
|
||||||
|
assertThat(bookRepository).isNotNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class LibraryPathBackReference {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression: createLibrary() must set LibraryPathEntity.library back-reference.
|
||||||
|
* Without enableAssociationManagement, Hibernate no longer auto-manages
|
||||||
|
* bidirectional relationships. If the back-reference is missing, the FK
|
||||||
|
* column library_id is NULL and paths are not linked to the library.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void libraryPathsMustHaveLibraryBackReference_whenPersistedViaCascade() {
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("Cascade Test Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.libraryPaths(new ArrayList<>(List.of(
|
||||||
|
LibraryPathEntity.builder().path("/books/fiction").build(),
|
||||||
|
LibraryPathEntity.builder().path("/books/nonfiction").build()
|
||||||
|
)))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// Simulate what createLibrary() must do: set the back-reference
|
||||||
|
library.getLibraryPaths().forEach(p -> p.setLibrary(library));
|
||||||
|
|
||||||
|
LibraryEntity saved = libraryRepository.saveAndFlush(library);
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
LibraryEntity reloaded = libraryRepository.findByIdWithPaths(saved.getId()).orElseThrow();
|
||||||
|
|
||||||
|
assertThat(reloaded.getLibraryPaths()).hasSize(2);
|
||||||
|
for (LibraryPathEntity path : reloaded.getLibraryPaths()) {
|
||||||
|
assertThat(path.getLibrary()).isNotNull();
|
||||||
|
assertThat(path.getLibrary().getId()).isEqualTo(reloaded.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify that the owning side FK is actually persisted to the DB and
|
||||||
|
* the library can find its paths after a fresh session load.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void libraryPathForeignKey_isPersistedCorrectly() {
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("FK Test Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
entityManager.flush();
|
||||||
|
|
||||||
|
LibraryPathEntity path = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/test/path")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(path);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
// Verify via JPQL that the FK is set
|
||||||
|
Long count = entityManager.createQuery(
|
||||||
|
"SELECT COUNT(lp) FROM LibraryPathEntity lp WHERE lp.library.id = :libId", Long.class)
|
||||||
|
.setParameter("libId", library.getId())
|
||||||
|
.getSingleResult();
|
||||||
|
|
||||||
|
assertThat(count).isEqualTo(1L);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Without back-reference, cascade persist puts NULL in library_id.
|
||||||
|
* This test verifies the issue exists if back-ref is not set,
|
||||||
|
* by checking constraint violation.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void cascadePersist_withoutBackReference_failsWithConstraintViolation() {
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("Missing BackRef Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.libraryPaths(new ArrayList<>(List.of(
|
||||||
|
LibraryPathEntity.builder().path("/dangling").build()
|
||||||
|
)))
|
||||||
|
.build();
|
||||||
|
// Intentionally NOT setting library back-reference
|
||||||
|
|
||||||
|
Assertions.assertThrows(
|
||||||
|
org.springframework.dao.DataIntegrityViolationException.class,
|
||||||
|
() -> {
|
||||||
|
libraryRepository.saveAndFlush(library);
|
||||||
|
entityManager.flush();
|
||||||
|
},
|
||||||
|
"Should fail because library_id is NOT NULL but no back-reference was set"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class EntityGraphQueries {
|
||||||
|
|
||||||
|
private LibraryEntity library;
|
||||||
|
private LibraryPathEntity libraryPath;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
library = LibraryEntity.builder()
|
||||||
|
.name("EntityGraph Test Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
|
||||||
|
libraryPath = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/test/books")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(libraryPath);
|
||||||
|
entityManager.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* findByIdWithPaths must eagerly load libraryPaths so they are
|
||||||
|
* accessible outside a Hibernate session (e.g., in virtual threads).
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void findByIdWithPaths_loadsLibraryPathsEagerly() {
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
LibraryEntity loaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
|
||||||
|
|
||||||
|
// Detach to simulate outside-session access
|
||||||
|
entityManager.detach(loaded);
|
||||||
|
|
||||||
|
// This must NOT throw LazyInitializationException
|
||||||
|
assertThat(loaded.getLibraryPaths()).hasSize(1);
|
||||||
|
assertThat(loaded.getLibraryPaths().get(0).getPath()).isEqualTo("/test/books");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* findByIdWithBooks must eagerly load bookEntities.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void findByIdWithBooks_loadsBookEntitiesEagerly() {
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
LibraryEntity loaded = libraryRepository.findByIdWithBooks(library.getId()).orElseThrow();
|
||||||
|
entityManager.detach(loaded);
|
||||||
|
|
||||||
|
assertThat(loaded.getBookEntities()).hasSize(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* findByIdWithBookFiles must eagerly load bookFiles via EntityGraph.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void findByIdWithBookFiles_loadsBookFilesEagerly() {
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
|
||||||
|
BookFileEntity bookFile = BookFileEntity.builder()
|
||||||
|
.book(book)
|
||||||
|
.fileName("test.epub")
|
||||||
|
.fileSubPath("")
|
||||||
|
.isBookFormat(true)
|
||||||
|
.bookType(BookFileType.EPUB)
|
||||||
|
.fileSizeKb(100L)
|
||||||
|
.initialHash("abc123")
|
||||||
|
.currentHash("abc123")
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.build();
|
||||||
|
entityManager.persist(bookFile);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
BookEntity loaded = bookRepository.findByIdWithBookFiles(book.getId()).orElseThrow();
|
||||||
|
entityManager.detach(loaded);
|
||||||
|
|
||||||
|
// Must NOT throw LazyInitializationException
|
||||||
|
assertThat(loaded.getBookFiles()).hasSize(1);
|
||||||
|
assertThat(loaded.getBookFiles().get(0).getFileName()).isEqualTo("test.epub");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class BookEntityDefaults {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression: BookEntity.deleted must default to FALSE (not null)
|
||||||
|
* so that queries filtering on deleted work correctly.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void bookEntity_deletedFieldDefaultsToFalse() {
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("Defaults Test")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
|
||||||
|
LibraryPathEntity path = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/test")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(path);
|
||||||
|
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(path)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.build();
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
BookEntity loaded = entityManager.find(BookEntity.class, book.getId());
|
||||||
|
assertThat(loaded.getDeleted()).isEqualTo(Boolean.FALSE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* findByIdWithBookFiles must find books where deleted = false.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void findByIdWithBookFiles_findsNonDeletedBook() {
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("Non-deleted Test")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
|
||||||
|
LibraryPathEntity path = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/test")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(path);
|
||||||
|
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(path)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
assertThat(bookRepository.findByIdWithBookFiles(book.getId())).isPresent();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* findByIdWithBookFiles must NOT find soft-deleted books.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void findByIdWithBookFiles_excludesDeletedBooks() {
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("Deleted Test")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
|
||||||
|
LibraryPathEntity path = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/test")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(path);
|
||||||
|
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(path)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(true)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
assertThat(bookRepository.findByIdWithBookFiles(book.getId())).isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class CollectionInitialization {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify that @Builder.Default collection fields are initialized
|
||||||
|
* and not null after entity construction via builder.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void libraryEntity_collectionsAreInitialized() {
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("Init Test")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertThat(library.getLibraryPaths()).isNotNull();
|
||||||
|
assertThat(library.getBookEntities()).isNotNull();
|
||||||
|
assertThat(library.getUsers()).isNotNull();
|
||||||
|
assertThat(library.getFormatPriority()).isNotNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void bookEntity_collectionsAreInitialized() {
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assertThat(book.getBookFiles()).isNotNull();
|
||||||
|
assertThat(book.getShelves()).isNotNull();
|
||||||
|
assertThat(book.getUserBookProgress()).isNotNull();
|
||||||
|
assertThat(book.getDeleted()).isEqualTo(Boolean.FALSE);
|
||||||
|
assertThat(book.getIsPhysical()).isEqualTo(Boolean.FALSE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class LibraryScanSimulation {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulate the library scan flow: create library with paths,
|
||||||
|
* then verify paths can be loaded and iterated for scanning.
|
||||||
|
* This is the exact flow broken when enableAssociationManagement
|
||||||
|
* was removed paths had NULL library_id so scanning found 0 paths.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void libraryWithPaths_canBeLoadedAndIteratedForScanning() {
|
||||||
|
// Simulate LibraryService.createLibrary() flow
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("Scan Simulation Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.libraryPaths(new ArrayList<>(List.of(
|
||||||
|
LibraryPathEntity.builder().path("/books").build(),
|
||||||
|
LibraryPathEntity.builder().path("/audiobooks").build()
|
||||||
|
)))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
library.getLibraryPaths().forEach(p -> p.setLibrary(library));
|
||||||
|
|
||||||
|
libraryRepository.saveAndFlush(library);
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
LibraryEntity loaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
|
||||||
|
|
||||||
|
List<String> pathStrings = loaded.getLibraryPaths().stream()
|
||||||
|
.map(LibraryPathEntity::getPath)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertThat(pathStrings).containsExactlyInAnyOrder("/books", "/audiobooks");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify the updateLibrary flow — updating paths preserves back-references.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void updateLibraryPaths_preservesBackReferences() {
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("Update Test Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
|
||||||
|
LibraryPathEntity path1 = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/old/path")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(path1);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
// Simulate updateLibrary() — load, clear paths, add new ones
|
||||||
|
LibraryEntity loaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
|
||||||
|
loaded.getLibraryPaths().clear();
|
||||||
|
|
||||||
|
LibraryPathEntity newPath = LibraryPathEntity.builder()
|
||||||
|
.library(loaded) // back-reference set here
|
||||||
|
.path("/new/path")
|
||||||
|
.build();
|
||||||
|
loaded.getLibraryPaths().add(newPath);
|
||||||
|
|
||||||
|
libraryRepository.saveAndFlush(loaded);
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
LibraryEntity reloaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
|
||||||
|
assertThat(reloaded.getLibraryPaths()).hasSize(1);
|
||||||
|
assertThat(reloaded.getLibraryPaths().get(0).getPath()).isEqualTo("/new/path");
|
||||||
|
assertThat(reloaded.getLibraryPaths().get(0).getLibrary().getId()).isEqualTo(library.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class BookCreationFlow {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulate BookCreatorService.createShellBook() — verify book with
|
||||||
|
* related entities can be saved and reloaded with all relationships intact.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void createShellBook_savesAllRelationships() {
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("Book Creation Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
|
||||||
|
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/books")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(libraryPath);
|
||||||
|
entityManager.flush();
|
||||||
|
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.bookFiles(new ArrayList<>())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
BookFileEntity bookFile = BookFileEntity.builder()
|
||||||
|
.book(book)
|
||||||
|
.fileName("test.epub")
|
||||||
|
.fileSubPath("")
|
||||||
|
.isBookFormat(true)
|
||||||
|
.bookType(BookFileType.EPUB)
|
||||||
|
.fileSizeKb(500L)
|
||||||
|
.initialHash("hash1")
|
||||||
|
.currentHash("hash1")
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.build();
|
||||||
|
book.getBookFiles().add(bookFile);
|
||||||
|
|
||||||
|
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||||
|
.book(book)
|
||||||
|
.title("Test Book Title")
|
||||||
|
.build();
|
||||||
|
book.setMetadata(metadata);
|
||||||
|
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
BookEntity loaded = bookRepository.findByIdWithBookFiles(book.getId()).orElseThrow();
|
||||||
|
|
||||||
|
assertThat(loaded.getLibrary().getId()).isEqualTo(library.getId());
|
||||||
|
assertThat(loaded.getLibraryPath().getId()).isEqualTo(libraryPath.getId());
|
||||||
|
assertThat(loaded.getBookFiles()).hasSize(1);
|
||||||
|
assertThat(loaded.getBookFiles().get(0).getFileName()).isEqualTo("test.epub");
|
||||||
|
assertThat(loaded.getMetadata().getTitle()).isEqualTo("Test Book Title");
|
||||||
|
assertThat(loaded.getDeleted()).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify that saveAndFlush generates an ID that can be used
|
||||||
|
* to refetch the book — critical for bookdrop finalization flow
|
||||||
|
* where processFile() saves in REQUIRES_NEW and the parent
|
||||||
|
* transaction needs to find it.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void saveAndFlush_generatesIdForImmediateRetrieval() {
|
||||||
|
LibraryEntity library = LibraryEntity.builder()
|
||||||
|
.name("SaveFlush Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
|
||||||
|
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/books")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(libraryPath);
|
||||||
|
entityManager.flush();
|
||||||
|
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
BookEntity saved = bookRepository.saveAndFlush(book);
|
||||||
|
|
||||||
|
assertThat(saved.getId()).isNotNull();
|
||||||
|
assertThat(bookRepository.findByIdWithBookFiles(saved.getId())).isPresent();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class FindAllWithPathsQuery {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify findAllWithPaths EntityGraph loads paths for all libraries.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void findAllWithPaths_loadsPathsForAllLibraries() {
|
||||||
|
LibraryEntity lib1 = LibraryEntity.builder().name("Lib1").icon("a").watch(false).build();
|
||||||
|
entityManager.persist(lib1);
|
||||||
|
LibraryPathEntity path1 = LibraryPathEntity.builder().library(lib1).path("/lib1").build();
|
||||||
|
entityManager.persist(path1);
|
||||||
|
|
||||||
|
LibraryEntity lib2 = LibraryEntity.builder().name("Lib2").icon("b").watch(false).build();
|
||||||
|
entityManager.persist(lib2);
|
||||||
|
LibraryPathEntity path2 = LibraryPathEntity.builder().library(lib2).path("/lib2").build();
|
||||||
|
entityManager.persist(path2);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
List<LibraryEntity> libraries = libraryRepository.findAllWithPaths();
|
||||||
|
|
||||||
|
assertThat(libraries).hasSizeGreaterThanOrEqualTo(2);
|
||||||
|
for (LibraryEntity lib : libraries) {
|
||||||
|
entityManager.detach(lib);
|
||||||
|
assertThat(lib.getLibraryPaths()).isNotEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class MetadataDescriptionAccess {
|
||||||
|
|
||||||
|
private LibraryEntity library;
|
||||||
|
private LibraryPathEntity libraryPath;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
library = LibraryEntity.builder()
|
||||||
|
.name("Description Test Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
|
||||||
|
libraryPath = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/test/books")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(libraryPath);
|
||||||
|
entityManager.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression: BookMetadataEntity.description must be accessible after detaching.
|
||||||
|
* Previously, description was @Basic(fetch=LAZY) which caused
|
||||||
|
* LazyInitializationException in MetadataChangeDetector and OPDS feeds.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void descriptionIsAccessibleOnDetachedEntity() {
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(false)
|
||||||
|
.build();
|
||||||
|
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||||
|
.book(book)
|
||||||
|
.title("Description Test Book")
|
||||||
|
.description("A long description of this book for testing purposes.")
|
||||||
|
.build();
|
||||||
|
book.setMetadata(metadata);
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
|
||||||
|
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
|
||||||
|
entityManager.detach(loaded);
|
||||||
|
|
||||||
|
assertThat(loaded.getMetadata().getDescription())
|
||||||
|
.isEqualTo("A long description of this book for testing purposes.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression: findAllWithMetadataByIds EntityGraph must load description
|
||||||
|
* so that MetadataChangeDetector.isDifferent() can compare it.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void findAllWithMetadataByIds_loadsDescriptionEagerly() {
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(false)
|
||||||
|
.build();
|
||||||
|
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||||
|
.book(book)
|
||||||
|
.title("Metadata Load Test")
|
||||||
|
.description("Detailed plot summary here.")
|
||||||
|
.build();
|
||||||
|
book.setMetadata(metadata);
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
List<BookEntity> books = bookRepository.findAllWithMetadataByIds(
|
||||||
|
Collections.singleton(book.getId()));
|
||||||
|
|
||||||
|
assertThat(books).hasSize(1);
|
||||||
|
|
||||||
|
entityManager.detach(books.get(0));
|
||||||
|
|
||||||
|
assertThat(books.get(0).getMetadata().getDescription())
|
||||||
|
.isEqualTo("Detailed plot summary here.");
|
||||||
|
assertThat(books.get(0).getMetadata().getTitle())
|
||||||
|
.isEqualTo("Metadata Load Test");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify embeddingVector and searchText remain lazy and are NOT loaded
|
||||||
|
* by default EntityGraphs, but ARE accessible within a session.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void lazyFieldsAccessibleWithinSession() {
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(false)
|
||||||
|
.build();
|
||||||
|
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||||
|
.book(book)
|
||||||
|
.title("Lazy Fields Test")
|
||||||
|
.embeddingVector("[0.1, 0.2, 0.3]")
|
||||||
|
.build();
|
||||||
|
book.setMetadata(metadata);
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
BookEntity loaded = bookRepository.findByIdWithMetadata(book.getId()).orElseThrow();
|
||||||
|
assertThat(loaded.getMetadata().getEmbeddingVector()).isEqualTo("[0.1, 0.2, 0.3]");
|
||||||
|
assertThat(loaded.getMetadata().getSearchText()).isNotNull();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class CategoryMappingIntegrity {
|
||||||
|
|
||||||
|
private LibraryEntity library;
|
||||||
|
private LibraryPathEntity libraryPath;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
library = LibraryEntity.builder()
|
||||||
|
.name("Category Test Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
|
||||||
|
libraryPath = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/test/books")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(libraryPath);
|
||||||
|
entityManager.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression: Saving a book with categories must not produce duplicate
|
||||||
|
* entries in book_metadata_category_mapping. The old double-save pattern
|
||||||
|
* (service saves, then controller saves again) caused duplicate key errors.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void categoryMappings_noDuplicatesAfterSave() {
|
||||||
|
CategoryEntity cat1 = CategoryEntity.builder().name("Fiction").build();
|
||||||
|
CategoryEntity cat2 = CategoryEntity.builder().name("Science").build();
|
||||||
|
entityManager.persist(cat1);
|
||||||
|
entityManager.persist(cat2);
|
||||||
|
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(false)
|
||||||
|
.build();
|
||||||
|
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||||
|
.book(book)
|
||||||
|
.title("Category Test Book")
|
||||||
|
.categories(new HashSet<>(Set.of(cat1, cat2)))
|
||||||
|
.build();
|
||||||
|
book.setMetadata(metadata);
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
// Verify categories persisted correctly
|
||||||
|
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
|
||||||
|
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
|
||||||
|
|
||||||
|
assertThat(loaded.getMetadata().getCategories()).hasSize(2);
|
||||||
|
assertThat(loaded.getMetadata().getCategories().stream()
|
||||||
|
.map(CategoryEntity::getName)
|
||||||
|
.collect(Collectors.toSet()))
|
||||||
|
.containsExactlyInAnyOrder("Fiction", "Science");
|
||||||
|
|
||||||
|
Long mappingCount = entityManager.createQuery(
|
||||||
|
"SELECT COUNT(1) FROM BookMetadataEntity m JOIN m.categories c WHERE m.book.id = :bookId", Long.class)
|
||||||
|
.setParameter("bookId", book.getId())
|
||||||
|
.getSingleResult();
|
||||||
|
assertThat(mappingCount).isEqualTo(2L);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updating categories on a managed entity should replace correctly
|
||||||
|
* without duplicate key violations.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void updateCategories_replacesWithoutDuplicates() {
|
||||||
|
CategoryEntity cat1 = CategoryEntity.builder().name("OldCat1").build();
|
||||||
|
CategoryEntity cat2 = CategoryEntity.builder().name("OldCat2").build();
|
||||||
|
CategoryEntity cat3 = CategoryEntity.builder().name("NewCat3").build();
|
||||||
|
entityManager.persist(cat1);
|
||||||
|
entityManager.persist(cat2);
|
||||||
|
entityManager.persist(cat3);
|
||||||
|
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(false)
|
||||||
|
.build();
|
||||||
|
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||||
|
.book(book)
|
||||||
|
.title("Update Category Test")
|
||||||
|
.categories(new HashSet<>(Set.of(cat1, cat2)))
|
||||||
|
.build();
|
||||||
|
book.setMetadata(metadata);
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
|
||||||
|
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
|
||||||
|
|
||||||
|
CategoryEntity managedCat2 = entityManager.find(CategoryEntity.class, cat2.getId());
|
||||||
|
CategoryEntity managedCat3 = entityManager.find(CategoryEntity.class, cat3.getId());
|
||||||
|
|
||||||
|
loaded.getMetadata().getCategories().clear();
|
||||||
|
loaded.getMetadata().getCategories().add(managedCat2);
|
||||||
|
loaded.getMetadata().getCategories().add(managedCat3);
|
||||||
|
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
BookEntity reloaded = bookRepository.findAllWithMetadataByIds(
|
||||||
|
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
|
||||||
|
|
||||||
|
assertThat(reloaded.getMetadata().getCategories()).hasSize(2);
|
||||||
|
assertThat(reloaded.getMetadata().getCategories().stream()
|
||||||
|
.map(CategoryEntity::getName)
|
||||||
|
.collect(Collectors.toSet()))
|
||||||
|
.containsExactlyInAnyOrder("OldCat2", "NewCat3");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class EmbeddingBatchProcessing {
|
||||||
|
|
||||||
|
private LibraryEntity library;
|
||||||
|
private LibraryPathEntity libraryPath;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
library = LibraryEntity.builder()
|
||||||
|
.name("Embedding Test Library")
|
||||||
|
.icon("book")
|
||||||
|
.watch(false)
|
||||||
|
.build();
|
||||||
|
entityManager.persist(library);
|
||||||
|
|
||||||
|
libraryPath = LibraryPathEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.path("/test/books")
|
||||||
|
.build();
|
||||||
|
entityManager.persist(libraryPath);
|
||||||
|
entityManager.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression: findAllFullBooksBatch must load metadata.authors and
|
||||||
|
* metadata.categories eagerly (via Hibernate.initialize) so they are
|
||||||
|
* accessible on detached entities for embedding computation.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void findAllFullBooksBatch_initializesLazyCollections() {
|
||||||
|
CategoryEntity cat = CategoryEntity.builder().name("TestCat").build();
|
||||||
|
entityManager.persist(cat);
|
||||||
|
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(false)
|
||||||
|
.build();
|
||||||
|
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||||
|
.book(book)
|
||||||
|
.title("Batch Test Book")
|
||||||
|
.categories(new HashSet<>(Set.of(cat)))
|
||||||
|
.build();
|
||||||
|
book.setMetadata(metadata);
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
List<BookEntity> batch = bookRepository.findAllFullBooksBatch(
|
||||||
|
PageRequest.of(0, 100));
|
||||||
|
|
||||||
|
assertThat(batch).isNotEmpty();
|
||||||
|
|
||||||
|
BookEntity loaded = batch.stream()
|
||||||
|
.filter(b -> b.getId().equals(book.getId()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow();
|
||||||
|
|
||||||
|
assertThat(loaded.getMetadata().getCategories()).hasSize(1);
|
||||||
|
assertThat(loaded.getMetadata().getTitle()).isEqualTo("Batch Test Book");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify embedding vector can be compared and updated within a session.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void embeddingVector_comparableAndUpdatableInSession() {
|
||||||
|
BookEntity book = BookEntity.builder()
|
||||||
|
.library(library)
|
||||||
|
.libraryPath(libraryPath)
|
||||||
|
.addedOn(Instant.now())
|
||||||
|
.deleted(false)
|
||||||
|
.build();
|
||||||
|
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||||
|
.book(book)
|
||||||
|
.title("Embedding Update Test")
|
||||||
|
.embeddingVector("[0.1, 0.2]")
|
||||||
|
.build();
|
||||||
|
book.setMetadata(metadata);
|
||||||
|
entityManager.persist(book);
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
|
||||||
|
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
|
||||||
|
|
||||||
|
String oldEmbedding = loaded.getMetadata().getEmbeddingVector();
|
||||||
|
assertThat(oldEmbedding).isEqualTo("[0.1, 0.2]");
|
||||||
|
|
||||||
|
loaded.getMetadata().setEmbeddingVector("[0.3, 0.4]");
|
||||||
|
loaded.getMetadata().setEmbeddingUpdatedAt(Instant.now());
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
BookEntity reloaded = bookRepository.findByIdWithMetadata(book.getId()).orElseThrow();
|
||||||
|
assertThat(reloaded.getMetadata().getEmbeddingVector()).isEqualTo("[0.3, 0.4]");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,6 +22,8 @@ import java.util.Optional;
|
|||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.argThat;
|
import static org.mockito.ArgumentMatchers.argThat;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
@@ -68,7 +70,15 @@ class BookCreatorServiceTest {
|
|||||||
void addAuthorsToBook_givenNullOrEmptySet_doesNothing(Set<String> authors) {
|
void addAuthorsToBook_givenNullOrEmptySet_doesNothing(Set<String> authors) {
|
||||||
bookCreatorService.addAuthorsToBook(authors, bookEntity);
|
bookCreatorService.addAuthorsToBook(authors, bookEntity);
|
||||||
|
|
||||||
assertThat(bookEntity.getMetadata().getAuthors()).isNull();
|
assertTrue(bookEntity.getMetadata().getAuthors().isEmpty());
|
||||||
|
verifyNoInteractions(authorRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void addAuthorsToBook_emptyAuthors_doesNothing() {
|
||||||
|
bookCreatorService.addAuthorsToBook(Set.of(), bookEntity);
|
||||||
|
|
||||||
|
assertTrue(bookEntity.getMetadata().getAuthors().isEmpty());
|
||||||
verifyNoInteractions(authorRepository);
|
verifyNoInteractions(authorRepository);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,12 +94,32 @@ class BookCreatorServiceTest {
|
|||||||
.containsExactly("Test Author");
|
.containsExactly("Test Author");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ParameterizedTest
|
@Test
|
||||||
@NullAndEmptySource
|
void addAuthorsToBook_nullExistingAuthorsOnEntity_initializesSet() {
|
||||||
void addCategoriesToBook_givenNullOrEmptySet_doesNothing(Set<String> categories) {
|
assertTrue(bookEntity.getMetadata().getAuthors().isEmpty());
|
||||||
bookCreatorService.addCategoriesToBook(categories, bookEntity);
|
|
||||||
|
|
||||||
assertThat(bookEntity.getMetadata().getCategories()).isNull();
|
AuthorEntity author = AuthorEntity.builder().name("Author").build();
|
||||||
|
when(authorRepository.findByName("Author")).thenReturn(Optional.of(author));
|
||||||
|
|
||||||
|
bookCreatorService.addAuthorsToBook(Set.of("Author"), bookEntity);
|
||||||
|
|
||||||
|
assertNotNull(bookEntity.getMetadata().getAuthors());
|
||||||
|
assertTrue(bookEntity.getMetadata().getAuthors().contains(author));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void addCategoriesToBook_nullCategories_doesNothing() {
|
||||||
|
bookCreatorService.addCategoriesToBook(null, bookEntity);
|
||||||
|
|
||||||
|
assertTrue(bookEntity.getMetadata().getCategories().isEmpty());
|
||||||
|
verifyNoInteractions(categoryRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void addCategoriesToBook_emptyCategories_doesNothing() {
|
||||||
|
bookCreatorService.addCategoriesToBook(Set.of(), bookEntity);
|
||||||
|
|
||||||
|
assertTrue(bookEntity.getMetadata().getCategories().isEmpty());
|
||||||
verifyNoInteractions(categoryRepository);
|
verifyNoInteractions(categoryRepository);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,7 +140,15 @@ class BookCreatorServiceTest {
|
|||||||
void addMoodsToBook_givenNullOrEmptySet_doesNothing(Set<String> moods) {
|
void addMoodsToBook_givenNullOrEmptySet_doesNothing(Set<String> moods) {
|
||||||
bookCreatorService.addMoodsToBook(moods, bookEntity);
|
bookCreatorService.addMoodsToBook(moods, bookEntity);
|
||||||
|
|
||||||
assertThat(bookEntity.getMetadata().getMoods()).isNull();
|
assertTrue(bookEntity.getMetadata().getMoods().isEmpty());
|
||||||
|
verifyNoInteractions(moodRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void addMoodsToBook_emptyMoods_doesNothing() {
|
||||||
|
bookCreatorService.addMoodsToBook(Set.of(), bookEntity);
|
||||||
|
|
||||||
|
assertTrue(bookEntity.getMetadata().getMoods().isEmpty());
|
||||||
verifyNoInteractions(moodRepository);
|
verifyNoInteractions(moodRepository);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,7 +169,23 @@ class BookCreatorServiceTest {
|
|||||||
void addTagsToBook_givenNullOrEmptySet_doesNothing(Set<String> tags) {
|
void addTagsToBook_givenNullOrEmptySet_doesNothing(Set<String> tags) {
|
||||||
bookCreatorService.addTagsToBook(tags, bookEntity);
|
bookCreatorService.addTagsToBook(tags, bookEntity);
|
||||||
|
|
||||||
assertThat(bookEntity.getMetadata().getTags()).isNull();
|
assertTrue(bookEntity.getMetadata().getTags().isEmpty());
|
||||||
|
verifyNoInteractions(tagRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void addTagsToBook_nullTags_doesNothing() {
|
||||||
|
bookCreatorService.addTagsToBook(null, bookEntity);
|
||||||
|
|
||||||
|
assertTrue(bookEntity.getMetadata().getTags().isEmpty());
|
||||||
|
verifyNoInteractions(tagRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void addTagsToBook_emptyTags_doesNothing() {
|
||||||
|
bookCreatorService.addTagsToBook(Set.of(), bookEntity);
|
||||||
|
|
||||||
|
assertTrue(bookEntity.getMetadata().getTags().isEmpty());
|
||||||
verifyNoInteractions(tagRepository);
|
verifyNoInteractions(tagRepository);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,7 +226,7 @@ class BookCreatorServiceTest {
|
|||||||
bookCreatorService.addAuthorsToBook(Set.of("Brand New"), bookEntity);
|
bookCreatorService.addAuthorsToBook(Set.of("Brand New"), bookEntity);
|
||||||
|
|
||||||
verify(authorRepository).save(argThat(author -> "Brand New".equals(author.getName())));
|
verify(authorRepository).save(argThat(author -> "Brand New".equals(author.getName())));
|
||||||
|
|
||||||
assertThat(bookEntity.getMetadata().getAuthors())
|
assertThat(bookEntity.getMetadata().getAuthors())
|
||||||
.isNotNull()
|
.isNotNull()
|
||||||
.extracting(AuthorEntity::getName)
|
.extracting(AuthorEntity::getName)
|
||||||
|
|||||||
+4
@@ -99,6 +99,7 @@ class BookFileAttachmentServiceTest {
|
|||||||
Files.createDirectories(dir);
|
Files.createDirectories(dir);
|
||||||
Files.createFile(dir.resolve(fileName));
|
Files.createFile(dir.resolve(fileName));
|
||||||
|
|
||||||
|
book.getBookFiles().add(file);
|
||||||
return file;
|
return file;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,6 +114,7 @@ class BookFileAttachmentServiceTest {
|
|||||||
.folderBased(false)
|
.folderBased(false)
|
||||||
.bookType(BookFileType.EPUB)
|
.bookType(BookFileType.EPUB)
|
||||||
.build();
|
.build();
|
||||||
|
book.getBookFiles().add(file);
|
||||||
return file;
|
return file;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -791,6 +793,7 @@ class BookFileAttachmentServiceTest {
|
|||||||
Path sourceDir = tempDir.resolve("other_root/source_dir");
|
Path sourceDir = tempDir.resolve("other_root/source_dir");
|
||||||
Files.createDirectories(sourceDir);
|
Files.createDirectories(sourceDir);
|
||||||
Files.createFile(sourceDir.resolve("source.pdf"));
|
Files.createFile(sourceDir.resolve("source.pdf"));
|
||||||
|
source.getBookFiles().add(sourceFile);
|
||||||
|
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||||
@@ -822,6 +825,7 @@ class BookFileAttachmentServiceTest {
|
|||||||
.build();
|
.build();
|
||||||
Files.createDirectories(tempDir.resolve("source_dir"));
|
Files.createDirectories(tempDir.resolve("source_dir"));
|
||||||
Files.createFile(tempDir.resolve("source_dir/noextension"));
|
Files.createFile(tempDir.resolve("source_dir/noextension"));
|
||||||
|
source.getBookFiles().add(sourceFile);
|
||||||
|
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||||
|
|||||||
+5
-7
@@ -86,6 +86,7 @@ class BookFileDetachmentServiceTest {
|
|||||||
.isBookFormat(isBookFormat)
|
.isBookFormat(isBookFormat)
|
||||||
.bookType(type)
|
.bookType(type)
|
||||||
.build();
|
.build();
|
||||||
|
book.getBookFiles().add(file);
|
||||||
return file;
|
return file;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,7 +124,6 @@ class BookFileDetachmentServiceTest {
|
|||||||
assertThat(book.getBookFiles().getFirst().getId()).isEqualTo(10L);
|
assertThat(book.getBookFiles().getFirst().getId()).isEqualTo(10L);
|
||||||
verify(auditService).log(eq(org.booklore.model.enums.AuditAction.BOOK_FILE_DETACHED), anyString(), eq(1L), anyString());
|
verify(auditService).log(eq(org.booklore.model.enums.AuditAction.BOOK_FILE_DETACHED), anyString(), eq(1L), anyString());
|
||||||
verify(bookRepository).saveAndFlush(argThat(newBook -> {
|
verify(bookRepository).saveAndFlush(argThat(newBook -> {
|
||||||
assertThat(newBook.getBookFiles()).hasSize(1);
|
|
||||||
assertThat(newBook.getMetadata().getTitle()).isEqualTo("Test Book 1");
|
assertThat(newBook.getMetadata().getTitle()).isEqualTo("Test Book 1");
|
||||||
return true;
|
return true;
|
||||||
}));
|
}));
|
||||||
@@ -173,11 +173,9 @@ class BookFileDetachmentServiceTest {
|
|||||||
service.detachBookFile(1L, 11L, false);
|
service.detachBookFile(1L, 11L, false);
|
||||||
|
|
||||||
assertThat(book.getBookFiles()).hasSize(1);
|
assertThat(book.getBookFiles()).hasSize(1);
|
||||||
verify(bookRepository).saveAndFlush(argThat(newBook -> {
|
assertThat(suppFile.getBook()).isNotSameAs(book);
|
||||||
assertThat(newBook.getBookFiles()).hasSize(1);
|
assertThat(suppFile.getFileName()).isEqualTo("notes.txt");
|
||||||
assertThat(newBook.getBookFiles().getFirst().getFileName()).isEqualTo("notes.txt");
|
verify(bookRepository).saveAndFlush(any(BookEntity.class));
|
||||||
return true;
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -281,8 +279,8 @@ class BookFileDetachmentServiceTest {
|
|||||||
|
|
||||||
verify(bookRepository).saveAndFlush(argThat(newBook -> {
|
verify(bookRepository).saveAndFlush(argThat(newBook -> {
|
||||||
assertThat(newBook.getLibraryPath().getId()).isEqualTo(2L);
|
assertThat(newBook.getLibraryPath().getId()).isEqualTo(2L);
|
||||||
assertThat(newBook.getBookFiles().getFirst().getFileSubPath()).isEmpty();
|
|
||||||
return true;
|
return true;
|
||||||
}));
|
}));
|
||||||
|
assertThat(altFile.getFileSubPath()).isEmpty();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,8 @@ import org.springframework.data.domain.Page;
|
|||||||
import org.springframework.data.domain.PageImpl;
|
import org.springframework.data.domain.PageImpl;
|
||||||
import org.springframework.data.domain.PageRequest;
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.transaction.PlatformTransactionManager;
|
||||||
|
import org.springframework.transaction.TransactionStatus;
|
||||||
import tools.jackson.databind.ObjectMapper;
|
import tools.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -87,6 +89,8 @@ class BookDropServiceTest {
|
|||||||
private FileMovingHelper fileMovingHelper;
|
private FileMovingHelper fileMovingHelper;
|
||||||
@Mock
|
@Mock
|
||||||
private KoboAutoShelfService koboAutoShelfService;
|
private KoboAutoShelfService koboAutoShelfService;
|
||||||
|
@Mock
|
||||||
|
private PlatformTransactionManager transactionManager;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private BookDropService bookDropService;
|
private BookDropService bookDropService;
|
||||||
@@ -122,6 +126,9 @@ class BookDropServiceTest {
|
|||||||
bookdropFile.setFileName("test-book.pdf");
|
bookdropFile.setFileName("test-book.pdf");
|
||||||
|
|
||||||
Files.createFile(tempDir.resolve("test-book.pdf"));
|
Files.createFile(tempDir.resolve("test-book.pdf"));
|
||||||
|
|
||||||
|
TransactionStatus txStatus = mock(TransactionStatus.class);
|
||||||
|
lenient().when(transactionManager.getTransaction(any())).thenReturn(txStatus);
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterEach
|
@AfterEach
|
||||||
|
|||||||
+2
-2
@@ -72,11 +72,11 @@ class KoboLibrarySnapshotServiceTest {
|
|||||||
otherUser = BookLoreUserEntity.builder().id(2L).isDefaultPassword(false).build();
|
otherUser = BookLoreUserEntity.builder().id(2L).isDefaultPassword(false).build();
|
||||||
|
|
||||||
LibraryEntity ownersLibrary = LibraryEntity.builder()
|
LibraryEntity ownersLibrary = LibraryEntity.builder()
|
||||||
.users(List.of(owner))
|
.users(Set.of(owner))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
LibraryEntity othersLibrary = LibraryEntity.builder()
|
LibraryEntity othersLibrary = LibraryEntity.builder()
|
||||||
.users(List.of(otherUser))
|
.users(Set.of(otherUser))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
ownersBook = BookEntity.builder()
|
ownersBook = BookEntity.builder()
|
||||||
|
|||||||
@@ -102,12 +102,11 @@ class KomgaServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void shouldReturnAllBooksWhenUnpagedIsTrue() {
|
void shouldReturnAllBooksWhenUnpagedIsTrue() {
|
||||||
// Given
|
// Given
|
||||||
when(bookRepository.findAllWithMetadataByLibraryId(anyLong())).thenReturn(seriesBooks);
|
when(komgaMapper.getUnknownSeriesName()).thenReturn("Unknown Series");
|
||||||
|
when(bookRepository.findDistinctSeriesNamesGroupedByLibraryId(1L, "Unknown Series"))
|
||||||
// Mock mapper.getBookSeriesName to return "test-series" for all books
|
.thenReturn(List.of("Test Series"));
|
||||||
for (BookEntity book : seriesBooks) {
|
when(bookRepository.findBooksBySeriesNameGroupedByLibraryId("Test Series", 1L, "Unknown Series"))
|
||||||
when(komgaMapper.getBookSeriesName(book)).thenReturn("test-series");
|
.thenReturn(seriesBooks);
|
||||||
}
|
|
||||||
|
|
||||||
// Mock the mapper to return DTOs
|
// Mock the mapper to return DTOs
|
||||||
for (BookEntity book : seriesBooks) {
|
for (BookEntity book : seriesBooks) {
|
||||||
@@ -133,12 +132,11 @@ class KomgaServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void shouldReturnPagedBooksWhenUnpagedIsFalse() {
|
void shouldReturnPagedBooksWhenUnpagedIsFalse() {
|
||||||
// Given
|
// Given
|
||||||
when(bookRepository.findAllWithMetadataByLibraryId(anyLong())).thenReturn(seriesBooks);
|
when(komgaMapper.getUnknownSeriesName()).thenReturn("Unknown Series");
|
||||||
|
when(bookRepository.findDistinctSeriesNamesGroupedByLibraryId(1L, "Unknown Series"))
|
||||||
// Mock mapper.getBookSeriesName to return "test-series" for all books
|
.thenReturn(List.of("Test Series"));
|
||||||
for (BookEntity book : seriesBooks) {
|
when(bookRepository.findBooksBySeriesNameGroupedByLibraryId("Test Series", 1L, "Unknown Series"))
|
||||||
when(komgaMapper.getBookSeriesName(book)).thenReturn("test-series");
|
.thenReturn(seriesBooks);
|
||||||
}
|
|
||||||
|
|
||||||
// Mock the mapper to return DTOs (only for the books that will be used)
|
// Mock the mapper to return DTOs (only for the books that will be used)
|
||||||
for (int i = 0; i < 20; i++) {
|
for (int i = 0; i < 20; i++) {
|
||||||
|
|||||||
+6
-1
@@ -6,6 +6,7 @@ import org.booklore.model.entity.BookEntity;
|
|||||||
import org.booklore.model.entity.LibraryEntity;
|
import org.booklore.model.entity.LibraryEntity;
|
||||||
import org.booklore.model.entity.LibraryPathEntity;
|
import org.booklore.model.entity.LibraryPathEntity;
|
||||||
import org.booklore.repository.BookAdditionalFileRepository;
|
import org.booklore.repository.BookAdditionalFileRepository;
|
||||||
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.repository.LibraryRepository;
|
import org.booklore.repository.LibraryRepository;
|
||||||
import org.booklore.service.NotificationService;
|
import org.booklore.service.NotificationService;
|
||||||
import org.booklore.task.options.RescanLibraryContext;
|
import org.booklore.task.options.RescanLibraryContext;
|
||||||
@@ -32,6 +33,8 @@ class LibraryProcessingServiceRegressionTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private LibraryRepository libraryRepository;
|
private LibraryRepository libraryRepository;
|
||||||
@Mock
|
@Mock
|
||||||
|
private BookRepository bookRepository;
|
||||||
|
@Mock
|
||||||
private NotificationService notificationService;
|
private NotificationService notificationService;
|
||||||
@Mock
|
@Mock
|
||||||
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||||
@@ -54,6 +57,7 @@ class LibraryProcessingServiceRegressionTest {
|
|||||||
void setUp() {
|
void setUp() {
|
||||||
libraryProcessingService = new LibraryProcessingService(
|
libraryProcessingService = new LibraryProcessingService(
|
||||||
libraryRepository,
|
libraryRepository,
|
||||||
|
bookRepository,
|
||||||
notificationService,
|
notificationService,
|
||||||
bookAdditionalFileRepository,
|
bookAdditionalFileRepository,
|
||||||
fileAsBookProcessor,
|
fileAsBookProcessor,
|
||||||
@@ -88,7 +92,8 @@ class LibraryProcessingServiceRegressionTest {
|
|||||||
|
|
||||||
libraryEntity.setBookEntities(List.of(filelessBook));
|
libraryEntity.setBookEntities(List.of(filelessBook));
|
||||||
|
|
||||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(filelessBook));
|
||||||
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(
|
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(
|
||||||
LibraryFile.builder()
|
LibraryFile.builder()
|
||||||
.libraryPathEntity(pathEntity)
|
.libraryPathEntity(pathEntity)
|
||||||
|
|||||||
+26
-9
@@ -8,6 +8,7 @@ import org.booklore.model.entity.BookFileEntity;
|
|||||||
import org.booklore.model.entity.LibraryEntity;
|
import org.booklore.model.entity.LibraryEntity;
|
||||||
import org.booklore.model.entity.LibraryPathEntity;
|
import org.booklore.model.entity.LibraryPathEntity;
|
||||||
import org.booklore.repository.BookAdditionalFileRepository;
|
import org.booklore.repository.BookAdditionalFileRepository;
|
||||||
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.repository.LibraryRepository;
|
import org.booklore.repository.LibraryRepository;
|
||||||
import org.booklore.service.NotificationService;
|
import org.booklore.service.NotificationService;
|
||||||
import org.booklore.task.options.RescanLibraryContext;
|
import org.booklore.task.options.RescanLibraryContext;
|
||||||
@@ -35,6 +36,8 @@ class LibraryProcessingServiceTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private LibraryRepository libraryRepository;
|
private LibraryRepository libraryRepository;
|
||||||
@Mock
|
@Mock
|
||||||
|
private BookRepository bookRepository;
|
||||||
|
@Mock
|
||||||
private NotificationService notificationService;
|
private NotificationService notificationService;
|
||||||
@Mock
|
@Mock
|
||||||
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||||
@@ -57,6 +60,7 @@ class LibraryProcessingServiceTest {
|
|||||||
void setUp() {
|
void setUp() {
|
||||||
libraryProcessingService = new LibraryProcessingService(
|
libraryProcessingService = new LibraryProcessingService(
|
||||||
libraryRepository,
|
libraryRepository,
|
||||||
|
bookRepository,
|
||||||
notificationService,
|
notificationService,
|
||||||
bookAdditionalFileRepository,
|
bookAdditionalFileRepository,
|
||||||
fileAsBookProcessor,
|
fileAsBookProcessor,
|
||||||
@@ -89,6 +93,7 @@ class LibraryProcessingServiceTest {
|
|||||||
libraryEntity.setBookEntities(List.of(existingBook));
|
libraryEntity.setBookEntities(List.of(existingBook));
|
||||||
|
|
||||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
|
||||||
|
|
||||||
LibraryFile existingFile = LibraryFile.builder()
|
LibraryFile existingFile = LibraryFile.builder()
|
||||||
.libraryEntity(libraryEntity)
|
.libraryEntity(libraryEntity)
|
||||||
@@ -150,6 +155,7 @@ class LibraryProcessingServiceTest {
|
|||||||
libraryEntity.setBookEntities(List.of(existingBook));
|
libraryEntity.setBookEntities(List.of(existingBook));
|
||||||
|
|
||||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
|
||||||
|
|
||||||
LibraryFile existingFile = LibraryFile.builder()
|
LibraryFile existingFile = LibraryFile.builder()
|
||||||
.libraryEntity(libraryEntity)
|
.libraryEntity(libraryEntity)
|
||||||
@@ -183,6 +189,7 @@ class LibraryProcessingServiceTest {
|
|||||||
pathEntity.setPath("/library");
|
pathEntity.setPath("/library");
|
||||||
|
|
||||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
LibraryFile newFile1 = LibraryFile.builder()
|
LibraryFile newFile1 = LibraryFile.builder()
|
||||||
.libraryEntity(libraryEntity)
|
.libraryEntity(libraryEntity)
|
||||||
@@ -230,6 +237,7 @@ class LibraryProcessingServiceTest {
|
|||||||
pathEntity.setPath("/library");
|
pathEntity.setPath("/library");
|
||||||
|
|
||||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
LibraryFile newFileInSub = LibraryFile.builder()
|
LibraryFile newFileInSub = LibraryFile.builder()
|
||||||
.libraryEntity(libraryEntity)
|
.libraryEntity(libraryEntity)
|
||||||
@@ -274,6 +282,7 @@ class LibraryProcessingServiceTest {
|
|||||||
pathEntity.setPath("/library");
|
pathEntity.setPath("/library");
|
||||||
|
|
||||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
LibraryFile additionalFileAsLibraryFile = LibraryFile.builder()
|
LibraryFile additionalFileAsLibraryFile = LibraryFile.builder()
|
||||||
.libraryEntity(libraryEntity)
|
.libraryEntity(libraryEntity)
|
||||||
@@ -346,7 +355,8 @@ class LibraryProcessingServiceTest {
|
|||||||
book.setBookFiles(List.of(epub, pdf, image));
|
book.setBookFiles(List.of(epub, pdf, image));
|
||||||
libraryEntity.setBookEntities(List.of(book));
|
libraryEntity.setBookEntities(List.of(book));
|
||||||
|
|
||||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(book));
|
||||||
|
|
||||||
// Only epub exists on disk, pdf was removed
|
// Only epub exists on disk, pdf was removed
|
||||||
LibraryFile epubOnDisk = LibraryFile.builder()
|
LibraryFile epubOnDisk = LibraryFile.builder()
|
||||||
@@ -385,7 +395,7 @@ class LibraryProcessingServiceTest {
|
|||||||
libraryEntity.setLibraryPaths(List.of(pathEntity));
|
libraryEntity.setLibraryPaths(List.of(pathEntity));
|
||||||
libraryEntity.setBookEntities(Collections.emptyList());
|
libraryEntity.setBookEntities(Collections.emptyList());
|
||||||
|
|
||||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
|
||||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||||
|
|
||||||
@@ -422,7 +432,8 @@ class LibraryProcessingServiceTest {
|
|||||||
existingBook.getPrimaryBookFile().setFileName("book1.epub");
|
existingBook.getPrimaryBookFile().setFileName("book1.epub");
|
||||||
libraryEntity.setBookEntities(List.of(existingBook));
|
libraryEntity.setBookEntities(List.of(existingBook));
|
||||||
|
|
||||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
|
||||||
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
|
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||||
@@ -467,11 +478,12 @@ class LibraryProcessingServiceTest {
|
|||||||
.fileName("book1.epub")
|
.fileName("book1.epub")
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
|
||||||
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk));
|
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk));
|
||||||
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
|
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
|
||||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||||
when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity)))
|
when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class)))
|
||||||
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
|
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
|
||||||
|
|
||||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||||
@@ -497,11 +509,12 @@ class LibraryProcessingServiceTest {
|
|||||||
libraryEntity.setLibraryPaths(List.of(pathEntity));
|
libraryEntity.setLibraryPaths(List.of(pathEntity));
|
||||||
libraryEntity.setBookEntities(Collections.emptyList());
|
libraryEntity.setBookEntities(Collections.emptyList());
|
||||||
|
|
||||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
|
||||||
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
|
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
|
||||||
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
|
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
|
||||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||||
when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity)))
|
when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class)))
|
||||||
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
|
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
|
||||||
|
|
||||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||||
@@ -551,9 +564,12 @@ class LibraryProcessingServiceTest {
|
|||||||
.fileName("book (with parens).epub")
|
.fileName("book (with parens).epub")
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
when(libraryRepository.findByIdWithBooks(libraryId))
|
when(libraryRepository.findByIdWithPaths(libraryId))
|
||||||
.thenReturn(Optional.of(libraryEntity))
|
.thenReturn(Optional.of(libraryEntity))
|
||||||
.thenReturn(Optional.of(freshLibraryEntity)); // Second call returns fresh entity
|
.thenReturn(Optional.of(freshLibraryEntity)); // Second call returns fresh entity
|
||||||
|
when(bookRepository.findAllByLibraryIdForRescan(libraryId))
|
||||||
|
.thenReturn(new ArrayList<>(List.of(existingBook)))
|
||||||
|
.thenReturn(new ArrayList<>(List.of(existingBook)));
|
||||||
when(libraryFileHelper.getAllLibraryFiles(any(LibraryEntity.class))).thenReturn(List.of(fileOnDisk));
|
when(libraryFileHelper.getAllLibraryFiles(any(LibraryEntity.class))).thenReturn(List.of(fileOnDisk));
|
||||||
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
|
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
|
||||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||||
@@ -564,7 +580,8 @@ class LibraryProcessingServiceTest {
|
|||||||
|
|
||||||
libraryProcessingService.rescanLibrary(context);
|
libraryProcessingService.rescanLibrary(context);
|
||||||
|
|
||||||
verify(libraryRepository, times(2)).findByIdWithBooks(libraryId);
|
verify(libraryRepository, times(2)).findByIdWithPaths(libraryId);
|
||||||
|
verify(bookRepository, times(2)).findAllByLibraryIdForRescan(libraryId);
|
||||||
|
|
||||||
verify(bookGroupingService).groupForRescan(eq(Collections.emptyList()), any(LibraryEntity.class));
|
verify(bookGroupingService).groupForRescan(eq(Collections.emptyList()), any(LibraryEntity.class));
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -68,7 +68,7 @@ class LibraryFileEventProcessorTest {
|
|||||||
.organizationMode(LibraryOrganizationMode.AUTO_DETECT)
|
.organizationMode(LibraryOrganizationMode.AUTO_DETECT)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
when(libraryRepository.findById(1L)).thenReturn(Optional.of(library));
|
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
|
||||||
when(bookFilePersistenceService.findMatchingLibraryPath(eq(library), any(Path.class)))
|
when(bookFilePersistenceService.findMatchingLibraryPath(eq(library), any(Path.class)))
|
||||||
.thenReturn(tempDir.toString());
|
.thenReturn(tempDir.toString());
|
||||||
when(bookFilePersistenceService.getLibraryPathEntityForFile(eq(library), eq(tempDir.toString())))
|
when(bookFilePersistenceService.getLibraryPathEntityForFile(eq(library), eq(tempDir.toString())))
|
||||||
|
|||||||
+37
-25
@@ -2,6 +2,7 @@ package org.booklore.task.tasks;
|
|||||||
|
|
||||||
import org.booklore.exception.APIException;
|
import org.booklore.exception.APIException;
|
||||||
import org.booklore.model.dto.BookLoreUser;
|
import org.booklore.model.dto.BookLoreUser;
|
||||||
|
import org.booklore.model.dto.BookRecommendationLite;
|
||||||
import org.booklore.model.dto.request.TaskCreateRequest;
|
import org.booklore.model.dto.request.TaskCreateRequest;
|
||||||
import org.booklore.model.dto.response.TaskCreateResponse;
|
import org.booklore.model.dto.response.TaskCreateResponse;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
@@ -15,13 +16,13 @@ import org.booklore.task.TaskStatus;
|
|||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Captor;
|
||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.ArgumentMatchers.*;
|
import static org.mockito.ArgumentMatchers.*;
|
||||||
@@ -40,6 +41,9 @@ class BookRecommendationUpdaterTaskTest {
|
|||||||
@InjectMocks
|
@InjectMocks
|
||||||
private BookRecommendationUpdaterTask task;
|
private BookRecommendationUpdaterTask task;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<Map<Long, Set<BookRecommendationLite>>> recommendationsCaptor;
|
||||||
|
|
||||||
private BookLoreUser user;
|
private BookLoreUser user;
|
||||||
private TaskCreateRequest request;
|
private TaskCreateRequest request;
|
||||||
|
|
||||||
@@ -60,13 +64,15 @@ class BookRecommendationUpdaterTaskTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void execute_shouldHandleEmptyBookList() {
|
void execute_shouldHandleEmptyBookList() {
|
||||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(Collections.emptyList());
|
when(bookQueryService.countAllNonDeleted()).thenReturn(0L);
|
||||||
|
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
TaskCreateResponse response = task.execute(request);
|
TaskCreateResponse response = task.execute(request);
|
||||||
|
|
||||||
assertEquals(TaskType.UPDATE_BOOK_RECOMMENDATIONS, response.getTaskType());
|
assertEquals(TaskType.UPDATE_BOOK_RECOMMENDATIONS, response.getTaskType());
|
||||||
verify(bookQueryService).getAllFullBookEntities();
|
verify(bookQueryService).countAllNonDeleted();
|
||||||
verify(bookQueryService).saveAll(anyList()); // Should be called with empty list
|
verify(bookQueryService).getAllFullBookEntitiesBatch(any());
|
||||||
|
verify(bookQueryService).saveRecommendationsInBatches(eq(Collections.emptyMap()), anyInt());
|
||||||
verify(notificationService, atLeastOnce()).sendMessage(eq(Topic.TASK_PROGRESS), any());
|
verify(notificationService, atLeastOnce()).sendMessage(eq(Topic.TASK_PROGRESS), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,32 +82,41 @@ class BookRecommendationUpdaterTaskTest {
|
|||||||
BookEntity book2 = BookEntity.builder().id(2L).metadata(BookMetadataEntity.builder().title("B2").build()).build();
|
BookEntity book2 = BookEntity.builder().id(2L).metadata(BookMetadataEntity.builder().title("B2").build()).build();
|
||||||
List<BookEntity> books = List.of(book1, book2);
|
List<BookEntity> books = List.of(book1, book2);
|
||||||
|
|
||||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(books);
|
when(bookQueryService.countAllNonDeleted()).thenReturn(2L);
|
||||||
|
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(books).thenReturn(Collections.emptyList());
|
||||||
when(vectorService.generateEmbedding(any())).thenReturn(new double[]{0.1, 0.2});
|
when(vectorService.generateEmbedding(any())).thenReturn(new double[]{0.1, 0.2});
|
||||||
when(vectorService.serializeVector(any())).thenReturn("[0.1, 0.2]");
|
when(vectorService.serializeVector(any())).thenReturn("[0.1, 0.2]");
|
||||||
// Lenient stubs for similarity calculations
|
when(vectorService.cosineSimilarity(any(), any())).thenReturn(0.9);
|
||||||
lenient().when(vectorService.cosineSimilarity(any(), any())).thenReturn(0.9);
|
when(vectorService.findTopKSimilar(any(), anyList(), anyInt())).thenAnswer(invocation -> {
|
||||||
lenient().when(vectorService.findTopKSimilar(any(), anyList(), anyInt())).thenReturn(new ArrayList<>());
|
List<BookVectorService.ScoredBook> candidates = invocation.getArgument(1);
|
||||||
|
return candidates.isEmpty() ? new ArrayList<>() : List.of(candidates.getFirst());
|
||||||
|
});
|
||||||
|
|
||||||
TaskCreateResponse response = task.execute(request);
|
TaskCreateResponse response = task.execute(request);
|
||||||
|
|
||||||
assertEquals("task-123", response.getTaskId());
|
assertEquals("task-123", response.getTaskId());
|
||||||
assertEquals(TaskStatus.COMPLETED, response.getStatus());
|
assertEquals(TaskStatus.COMPLETED, response.getStatus());
|
||||||
|
|
||||||
org.mockito.ArgumentCaptor<List<BookEntity>> captor = org.mockito.ArgumentCaptor.forClass(List.class);
|
verify(bookQueryService).compareAndSaveEmbeddings(any());
|
||||||
verify(bookQueryService).saveAll(captor.capture());
|
|
||||||
|
|
||||||
List<BookEntity> savedBooks = captor.getValue();
|
|
||||||
assertEquals(2, savedBooks.size());
|
|
||||||
// Verify embeddings were set
|
|
||||||
assertNotNull(savedBooks.get(0).getMetadata().getEmbeddingVector());
|
|
||||||
verify(vectorService, times(2)).generateEmbedding(any());
|
verify(vectorService, times(2)).generateEmbedding(any());
|
||||||
|
verify(bookQueryService).saveRecommendationsInBatches(recommendationsCaptor.capture(), anyInt());
|
||||||
|
|
||||||
|
Map<Long, Set<BookRecommendationLite>> recommendations = recommendationsCaptor.getValue();
|
||||||
|
assertNotNull(recommendations);
|
||||||
|
assertEquals(2, recommendations.size(), "Should have recommendations for both books");
|
||||||
|
assertTrue(recommendations.containsKey(1L), "Should have recommendations for book 1");
|
||||||
|
assertTrue(recommendations.containsKey(2L), "Should have recommendations for book 2");
|
||||||
|
// Each book should recommend the other
|
||||||
|
recommendations.values().forEach(recs ->
|
||||||
|
assertFalse(recs.isEmpty(), "Each book should have at least one recommendation"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void execute_shouldFail_whenEmbeddingGenerationThrows() {
|
void execute_shouldFail_whenEmbeddingGenerationThrows() {
|
||||||
BookEntity book1 = BookEntity.builder().id(1L).build();
|
BookEntity book1 = BookEntity.builder().id(1L).metadata(BookMetadataEntity.builder().title("B1").build()).build();
|
||||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(book1));
|
|
||||||
|
when(bookQueryService.countAllNonDeleted()).thenReturn(1L);
|
||||||
|
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(List.of(book1));
|
||||||
when(vectorService.generateEmbedding(any())).thenThrow(new RuntimeException("Embedding failed"));
|
when(vectorService.generateEmbedding(any())).thenThrow(new RuntimeException("Embedding failed"));
|
||||||
|
|
||||||
assertThrows(RuntimeException.class, () -> task.execute(request));
|
assertThrows(RuntimeException.class, () -> task.execute(request));
|
||||||
@@ -113,18 +128,15 @@ class BookRecommendationUpdaterTaskTest {
|
|||||||
BookEntity book2 = BookEntity.builder().id(2L).metadata(BookMetadataEntity.builder().title("B2").build()).build();
|
BookEntity book2 = BookEntity.builder().id(2L).metadata(BookMetadataEntity.builder().title("B2").build()).build();
|
||||||
List<BookEntity> books = List.of(book1, book2);
|
List<BookEntity> books = List.of(book1, book2);
|
||||||
|
|
||||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(books);
|
when(bookQueryService.countAllNonDeleted()).thenReturn(2L);
|
||||||
|
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(books).thenReturn(Collections.emptyList());
|
||||||
when(vectorService.generateEmbedding(any())).thenReturn(new double[]{0.1});
|
when(vectorService.generateEmbedding(any())).thenReturn(new double[]{0.1});
|
||||||
when(vectorService.serializeVector(any())).thenReturn("[0.1]");
|
when(vectorService.serializeVector(any())).thenReturn("[0.1]");
|
||||||
|
|
||||||
// Mock similarity to throw for first book, pass for second (actually it iterates as target)
|
|
||||||
// target=book1, candidate=book2.
|
|
||||||
when(vectorService.cosineSimilarity(any(), any())).thenThrow(new RuntimeException("Math error"));
|
when(vectorService.cosineSimilarity(any(), any())).thenThrow(new RuntimeException("Math error"));
|
||||||
|
|
||||||
TaskCreateResponse response = task.execute(request);
|
TaskCreateResponse response = task.execute(request);
|
||||||
|
|
||||||
assertEquals(TaskStatus.COMPLETED, response.getStatus());
|
assertEquals(TaskStatus.COMPLETED, response.getStatus());
|
||||||
// Should still try to save updates (even if empty list added)
|
verify(bookQueryService).saveRecommendationsInBatches(any(Map.class), anyInt());
|
||||||
verify(bookQueryService).saveAll(anyList());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ spring:
|
|||||||
properties:
|
properties:
|
||||||
hibernate:
|
hibernate:
|
||||||
format_sql: true
|
format_sql: true
|
||||||
|
query:
|
||||||
|
fail_on_pagination_over_collection_fetch: true
|
||||||
|
connection:
|
||||||
|
provider_disables_autocommit: false
|
||||||
flyway:
|
flyway:
|
||||||
enabled: false
|
enabled: false
|
||||||
app:
|
app:
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ services:
|
|||||||
- DATABASE_PASSWORD=grimmory
|
- DATABASE_PASSWORD=grimmory
|
||||||
- REMOTE_DEBUG_ENABLED=true
|
- REMOTE_DEBUG_ENABLED=true
|
||||||
- ALLOWED_ORIGINS=http://localhost:4200
|
- ALLOWED_ORIGINS=http://localhost:4200
|
||||||
|
- JAVA_TOOL_OPTIONS=-XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=60.0 -XX:InitialRAMPercentage=8.0 -XX:+ExitOnOutOfMemoryError -XX:MaxMetaspaceSize=192m -XX:ReservedCodeCacheSize=64m -Xss512k -XX:CICompilerCount=2 -XX:+UnlockExperimentalVMOptions -XX:ShenandoahUncommitDelay=5000 -XX:ShenandoahGuaranteedGCInterval=30000
|
||||||
stdin_open: true
|
stdin_open: true
|
||||||
tty: true
|
tty: true
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
@@ -101,7 +101,8 @@ export class BookService {
|
|||||||
private getBooksQueryOptions() {
|
private getBooksQueryOptions() {
|
||||||
return queryOptions({
|
return queryOptions({
|
||||||
queryKey: BOOKS_QUERY_KEY,
|
queryKey: BOOKS_QUERY_KEY,
|
||||||
queryFn: () => lastValueFrom(this.http.get<Book[]>(this.url, {params: {stripForListView: false}}))
|
queryFn: () => lastValueFrom(this.http.get<Book[]>(this.url, {params: {stripForListView: false}})),
|
||||||
|
staleTime: 30_000,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user