fix(cover): apply bulk cover actions to audiobook covers (#2623)
This commit is contained in:
@@ -239,7 +239,14 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
""")
|
||||
List<BookEntity> findFilelessBooksByLibraryId(@Param("libraryId") Long libraryId);
|
||||
|
||||
@Query("SELECT b.id as id, m.coverUpdatedOn as coverUpdatedOn FROM BookEntity b LEFT JOIN b.metadata m WHERE b.id IN :bookIds")
|
||||
@Query("""
|
||||
SELECT b.id as id,
|
||||
m.coverUpdatedOn as coverUpdatedOn,
|
||||
m.audiobookCoverUpdatedOn as audiobookCoverUpdatedOn
|
||||
FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
WHERE b.id IN :bookIds
|
||||
""")
|
||||
List<BookCoverUpdateProjection> findCoverUpdateInfoByIds(@Param("bookIds") Collection<Long> bookIds);
|
||||
|
||||
@Modifying
|
||||
|
||||
+1
@@ -5,5 +5,6 @@ import java.time.Instant;
|
||||
public interface BookCoverUpdateProjection {
|
||||
Long getId();
|
||||
Instant getCoverUpdatedOn();
|
||||
Instant getAudiobookCoverUpdatedOn();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package org.booklore.service.fileprocessor;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.mapper.BookMapper;
|
||||
import org.booklore.model.dto.AudiobookMetadata;
|
||||
import org.booklore.model.dto.BookMetadata;
|
||||
@@ -97,7 +96,7 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil
|
||||
return false;
|
||||
}
|
||||
|
||||
return extractAndSaveCover(bookEntity, audioFile, false);
|
||||
return extractAndSaveCover(bookEntity, audioFile);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover for audiobook '{}': {}", bookEntity.getPrimaryBookFile().getFileName(), e.getMessage(), e);
|
||||
@@ -118,10 +117,8 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil
|
||||
}
|
||||
|
||||
log.debug("Extracting cover from audio file: {}", audioFile.getAbsolutePath());
|
||||
return extractAndSaveCover(bookEntity, audioFile, true);
|
||||
return extractAndSaveCover(bookEntity, audioFile);
|
||||
|
||||
} catch (RuntimeException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover for audiobook '{}' (bookId: {}): {}",
|
||||
audiobookFile.getFileName(), bookEntity.getId(), e.getMessage(), e);
|
||||
@@ -129,14 +126,11 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil
|
||||
}
|
||||
}
|
||||
|
||||
private boolean extractAndSaveCover(BookEntity bookEntity, File audioFile, boolean throwOnNoCover) throws Exception {
|
||||
private boolean extractAndSaveCover(BookEntity bookEntity, File audioFile) throws Exception {
|
||||
byte[] coverData = audiobookMetadataExtractor.extractCover(audioFile);
|
||||
|
||||
if (coverData == null) {
|
||||
log.warn("No embedded cover image found in audiobook file '{}' (bookId: {})", audioFile.getAbsolutePath(), bookEntity.getId());
|
||||
if (throwOnNoCover) {
|
||||
throw ApiError.NO_COVER_IN_FILE.createException();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@ import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.model.enums.PermissionType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@@ -94,13 +96,7 @@ public class BookCoverService {
|
||||
throw ApiError.METADATA_LOCKED.createException();
|
||||
}
|
||||
|
||||
String title = bookEntity.getMetadata().getTitle();
|
||||
String author = getAuthorNames(bookEntity);
|
||||
byte[] coverBytes = coverImageGenerator.generateCover(title, author);
|
||||
|
||||
fileService.createThumbnailFromBytes(bookId, coverBytes);
|
||||
writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromBytes(book, coverBytes));
|
||||
updateBookCoverMetadata(bookEntity);
|
||||
applyCustomBookCover(bookEntity);
|
||||
bookRepository.save(bookEntity);
|
||||
notifyBookCoverUpdate(bookEntity);
|
||||
}
|
||||
@@ -221,13 +217,7 @@ public class BookCoverService {
|
||||
throw ApiError.METADATA_LOCKED.createException();
|
||||
}
|
||||
|
||||
String title = bookEntity.getMetadata().getTitle();
|
||||
String author = getAuthorNames(bookEntity);
|
||||
byte[] coverBytes = coverImageGenerator.generateSquareCover(title, author);
|
||||
|
||||
fileService.createAudiobookThumbnailFromBytes(bookId, coverBytes);
|
||||
writeAudiobookCoverToFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromBytes(book, coverBytes));
|
||||
updateAudiobookCoverMetadata(bookEntity);
|
||||
applyCustomAudiobookCover(bookEntity);
|
||||
bookRepository.save(bookEntity);
|
||||
notifyBookCoverUpdate(bookEntity);
|
||||
}
|
||||
@@ -238,9 +228,12 @@ public class BookCoverService {
|
||||
public void updateCoverFromFileForBooks(Set<Long> bookIds, MultipartFile file) {
|
||||
validateCoverFile(file);
|
||||
byte[] coverImageBytes = extractBytesFromMultipartFile(file);
|
||||
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
|
||||
List<BookCoverInfo> unlockedBooks = getBooksWithAnyUnlockedCoverSlot(bookIds);
|
||||
String username = getCurrentUsername();
|
||||
taskExecutor.execute(() -> processBulkCoverUpdate(unlockedBooks, coverImageBytes, username));
|
||||
taskExecutor.execute(() -> processBulkCoverOperation(unlockedBooks, username,
|
||||
new BulkCoverMessages("Started updating covers for %d selected book(s)", "Updating cover for",
|
||||
"Finished updating covers for selected books"),
|
||||
book -> applyUploadedCoverSlots(book, coverImageBytes)));
|
||||
}
|
||||
|
||||
// =========================
|
||||
@@ -272,53 +265,32 @@ public class BookCoverService {
|
||||
bookRepository.save(bookEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the best ebook (non-audiobook) file for a book, respecting library format priority.
|
||||
*/
|
||||
private BookFileEntity findEbookFile(BookEntity bookEntity) {
|
||||
var bookFiles = bookEntity.getBookFiles();
|
||||
if (bookFiles == null || bookFiles.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var library = bookEntity.getLibrary();
|
||||
if (library != null && library.getFormatPriority() != null && !library.getFormatPriority().isEmpty()) {
|
||||
for (BookFileType format : library.getFormatPriority()) {
|
||||
if (format == BookFileType.AUDIOBOOK) {
|
||||
continue;
|
||||
}
|
||||
var match = bookFiles.stream()
|
||||
.filter(bf -> bf.isBookFormat() && bf.getBookType() == format)
|
||||
.min(Comparator.comparingLong(BookFileEntity::getId));
|
||||
if (match.isPresent()) {
|
||||
return match.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: return first non-audiobook file
|
||||
return bookFiles.stream()
|
||||
.filter(f -> f.getBookType() != BookFileType.AUDIOBOOK)
|
||||
.min(Comparator.comparingLong(BookFileEntity::getId))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate covers for a set of books.
|
||||
*/
|
||||
public void regenerateCoversForBooks(Set<Long> bookIds) {
|
||||
List<BookCoverInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds);
|
||||
List<BookCoverInfo> unlockedBooks = bookQueryService.findAllWithMetadataByIds(bookIds).stream()
|
||||
.filter(book -> book.getMetadata() != null)
|
||||
.filter(book -> needsRegeneration(book, false))
|
||||
.map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle()))
|
||||
.toList();
|
||||
String username = getCurrentUsername();
|
||||
taskExecutor.execute(() -> processBulkCoverRegeneration(unlockedBooks, username));
|
||||
taskExecutor.execute(() -> processBulkCoverOperation(unlockedBooks, username,
|
||||
new BulkCoverMessages("Started regenerating covers for %d selected book(s)", "Regenerating cover for",
|
||||
"Finished regenerating covers for selected books"),
|
||||
book -> regenerateCoverSlots(book, false)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate custom covers for a set of books.
|
||||
*/
|
||||
public void generateCustomCoversForBooks(Set<Long> bookIds) {
|
||||
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
|
||||
List<BookCoverInfo> unlockedBooks = getBooksWithAnyUnlockedCoverSlot(bookIds);
|
||||
String username = getCurrentUsername();
|
||||
taskExecutor.execute(() -> processBulkCustomCoverGeneration(unlockedBooks, username));
|
||||
taskExecutor.execute(() -> processBulkCoverOperation(unlockedBooks, username,
|
||||
new BulkCoverMessages("Started generating custom covers for %d selected book(s)", "Generating custom cover for",
|
||||
"Finished generating custom covers for selected books"),
|
||||
this::generateCustomCoverSlots));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -330,50 +302,14 @@ public class BookCoverService {
|
||||
try {
|
||||
List<BookCoverInfo> books = bookQueryService.getAllFullBookEntitiesWithFiles().stream()
|
||||
.filter(book -> book.getMetadata() != null)
|
||||
.filter(book -> !isCoverLocked(book))
|
||||
.filter(book -> book.getPrimaryBookFile() != null)
|
||||
.filter(book -> !missingOnly || book.getBookCoverHash() == null)
|
||||
.filter(book -> needsRegeneration(book, missingOnly))
|
||||
.map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle()))
|
||||
.toList();
|
||||
int total = books.size();
|
||||
String label = missingOnly ? "missing" : "all";
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " books (" + label + ")"));
|
||||
|
||||
int current = 1;
|
||||
|
||||
for (BookCoverInfo bookInfo : books) {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
|
||||
var primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
log.warn("{}Skipping physical book ID {} ({}) - no file to regenerate cover from", progress, book.getId(), bookInfo.title());
|
||||
return;
|
||||
}
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(primaryFile.getBookType());
|
||||
boolean success = processor.generateCover(book);
|
||||
|
||||
if (success) {
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
notifyBulkCoverUpdate(List.of(book.getId()), username);
|
||||
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), bookInfo.title());
|
||||
} else {
|
||||
log.warn("{}Failed to regenerate cover for book ID {} ({})", progress, book.getId(), bookInfo.title());
|
||||
}
|
||||
});
|
||||
return null;
|
||||
});
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
|
||||
}
|
||||
current++;
|
||||
}
|
||||
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Finished regenerating covers"));
|
||||
processBulkCoverOperation(books, username,
|
||||
new BulkCoverMessages("Started regenerating covers for %d books (" + label + ")", "Regenerating cover for",
|
||||
"Finished regenerating covers"),
|
||||
book -> regenerateCoverSlots(book, missingOnly));
|
||||
} catch (Exception e) {
|
||||
log.error("Error during cover regeneration: {}", e.getMessage(), e);
|
||||
sendNotification(username, Topic.LOG, LogNotification.error("Error occurred during cover regeneration"));
|
||||
@@ -385,127 +321,130 @@ public class BookCoverService {
|
||||
// SECTION: BULK OPERATIONS
|
||||
// =========================
|
||||
|
||||
private void processBulkCoverUpdate(List<BookCoverInfo> books, byte[] coverImageBytes, String username) {
|
||||
private record BulkCoverMessages(String startFormat, String itemVerb, String finishMessage) {
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface CoverBatchAction {
|
||||
boolean apply(BookEntity book);
|
||||
}
|
||||
|
||||
private void processBulkCoverOperation(List<BookCoverInfo> books, String username,
|
||||
BulkCoverMessages messages, CoverBatchAction action) {
|
||||
try {
|
||||
int total = books.size();
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Started updating covers for " + total + " selected book(s)"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(String.format(messages.startFormat(), total)));
|
||||
|
||||
int current = 1;
|
||||
|
||||
for (BookCoverInfo bookInfo : books) {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Updating cover for: " + bookInfo.title()));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + messages.itemVerb() + ": " + bookInfo.title()));
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
|
||||
fileService.createThumbnailFromBytes(bookInfo.id(), coverImageBytes);
|
||||
writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverImageBytes));
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
notifyBulkCoverUpdate(List.of(book.getId()), username);
|
||||
});
|
||||
return null;
|
||||
});
|
||||
Boolean updated = transactionTemplate.execute(status ->
|
||||
bookRepository.findByIdWithBookFiles(bookInfo.id())
|
||||
.map(book -> {
|
||||
boolean changed = action.apply(book);
|
||||
if (changed) {
|
||||
bookRepository.save(book);
|
||||
}
|
||||
return changed;
|
||||
})
|
||||
.orElse(false)
|
||||
);
|
||||
|
||||
log.info("{}Successfully updated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
|
||||
if (Boolean.TRUE.equals(updated)) {
|
||||
notifyBulkCoverUpdate(List.of(bookInfo.id()), username);
|
||||
log.info("{}{} book ID {} ({})", progress, messages.itemVerb(), bookInfo.id(), bookInfo.title());
|
||||
} else {
|
||||
log.warn("{}No cover updated for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to update cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
|
||||
log.error("Failed cover operation for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
|
||||
}
|
||||
current++;
|
||||
}
|
||||
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Finished updating covers for selected books"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(messages.finishMessage()));
|
||||
} catch (Exception e) {
|
||||
log.error("Error during cover update: {}", e.getMessage(), e);
|
||||
sendNotification(username, Topic.LOG, LogNotification.error("Error occurred during cover update"));
|
||||
log.error("Error during bulk cover operation: {}", e.getMessage(), e);
|
||||
sendNotification(username, Topic.LOG, LogNotification.error("Error occurred during cover operation"));
|
||||
}
|
||||
}
|
||||
|
||||
private void processBulkCoverRegeneration(List<BookCoverInfo> books, String username) {
|
||||
try {
|
||||
int total = books.size();
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)"));
|
||||
|
||||
int current = 1;
|
||||
|
||||
for (BookCoverInfo bookInfo : books) {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
|
||||
var primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
log.warn("{}Skipping book ID {} ({}) - no primary file", progress, book.getId(), bookInfo.title());
|
||||
return;
|
||||
}
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(primaryFile.getBookType());
|
||||
boolean success = processor.generateCover(book);
|
||||
|
||||
if (success) {
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
notifyBulkCoverUpdate(List.of(book.getId()), username);
|
||||
}
|
||||
});
|
||||
return null;
|
||||
});
|
||||
|
||||
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
|
||||
}
|
||||
current++;
|
||||
private boolean applyUploadedCoverSlots(BookEntity book, byte[] coverBytes) {
|
||||
boolean updated = false;
|
||||
if (hasUnlockedEbookSlot(book)) {
|
||||
try {
|
||||
fileService.createThumbnailFromBytes(book.getId(), coverBytes);
|
||||
writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverBytes));
|
||||
updateBookCoverMetadata(book);
|
||||
updated = true;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to update ebook cover slot for book ID {}: {}", book.getId(), e.getMessage(), e);
|
||||
}
|
||||
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Finished regenerating covers for selected books"));
|
||||
} catch (Exception e) {
|
||||
log.error("Error during cover regeneration: {}", e.getMessage(), e);
|
||||
sendNotification(username, Topic.LOG, LogNotification.error("Error occurred during cover regeneration"));
|
||||
}
|
||||
if (hasUnlockedAudiobookSlot(book)) {
|
||||
try {
|
||||
fileService.createAudiobookThumbnailFromBytes(book.getId(), coverBytes);
|
||||
writeAudiobookCoverToFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverBytes));
|
||||
updateAudiobookCoverMetadata(book);
|
||||
updated = true;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to update audiobook cover slot for book ID {}: {}", book.getId(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
private void processBulkCustomCoverGeneration(List<BookCoverInfo> books, String username) {
|
||||
try {
|
||||
int total = books.size();
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Started generating custom covers for " + total + " selected book(s)"));
|
||||
|
||||
int current = 1;
|
||||
|
||||
for (BookCoverInfo bookInfo : books) {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Generating custom cover for: " + bookInfo.title()));
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
|
||||
String title = book.getMetadata().getTitle();
|
||||
String author = getAuthorNames(book);
|
||||
byte[] coverBytes = coverImageGenerator.generateCover(title, author);
|
||||
|
||||
fileService.createThumbnailFromBytes(book.getId(), coverBytes);
|
||||
writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverBytes));
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
notifyBulkCoverUpdate(List.of(book.getId()), username);
|
||||
});
|
||||
return null;
|
||||
});
|
||||
|
||||
log.info("{}Successfully generated custom cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to generate custom cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
|
||||
private boolean regenerateCoverSlots(BookEntity book, boolean missingOnly) {
|
||||
boolean updated = false;
|
||||
if (ebookSlotNeedsRegeneration(book, missingOnly)) {
|
||||
try {
|
||||
BookFileEntity ebookFile = findEbookFile(book);
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(ebookFile.getBookType());
|
||||
if (processor.generateCover(book, ebookFile)) {
|
||||
updateBookCoverMetadata(book);
|
||||
updated = true;
|
||||
}
|
||||
current++;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to regenerate book cover slot for book ID {}: {}", book.getId(), e.getMessage(), e);
|
||||
}
|
||||
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Finished generating custom covers for selected books"));
|
||||
} catch (Exception e) {
|
||||
log.error("Error during custom cover generation: {}", e.getMessage(), e);
|
||||
sendNotification(username, Topic.LOG, LogNotification.error("Error occurred during custom cover generation"));
|
||||
}
|
||||
if (audiobookSlotNeedsRegeneration(book, missingOnly)) {
|
||||
try {
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(BookFileType.AUDIOBOOK);
|
||||
if (processor.generateAudiobookCover(book)) {
|
||||
updateAudiobookCoverMetadata(book);
|
||||
updated = true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to regenerate audiobook cover slot for book ID {}: {}", book.getId(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
private boolean generateCustomCoverSlots(BookEntity book) {
|
||||
boolean updated = false;
|
||||
if (hasUnlockedEbookSlot(book)) {
|
||||
try {
|
||||
applyCustomBookCover(book);
|
||||
updated = true;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to generate custom ebook cover for book ID {}: {}", book.getId(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
if (hasUnlockedAudiobookSlot(book)) {
|
||||
try {
|
||||
applyCustomAudiobookCover(book);
|
||||
updated = true;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to generate custom audiobook cover for book ID {}: {}", book.getId(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
// =========================
|
||||
@@ -554,19 +493,10 @@ public class BookCoverService {
|
||||
}
|
||||
}
|
||||
|
||||
private List<BookCoverInfo> getUnlockedBookCoverInfos(Set<Long> bookIds) {
|
||||
private List<BookCoverInfo> getBooksWithAnyUnlockedCoverSlot(Set<Long> bookIds) {
|
||||
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
|
||||
.filter(book -> book.getMetadata() != null)
|
||||
.filter(book -> !isCoverLocked(book))
|
||||
.map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private List<BookCoverInfo> getUnlockedBookRegenerationInfos(Set<Long> bookIds) {
|
||||
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
|
||||
.filter(book -> book.getMetadata() != null)
|
||||
.filter(book -> !isCoverLocked(book))
|
||||
.filter(book -> book.getPrimaryBookFile() != null)
|
||||
.filter(book -> hasUnlockedEbookSlot(book) || hasUnlockedAudiobookSlot(book))
|
||||
.map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle()))
|
||||
.toList();
|
||||
}
|
||||
@@ -579,6 +509,82 @@ public class BookCoverService {
|
||||
return book.getMetadata() != null && Boolean.TRUE.equals(book.getMetadata().getAudiobookCoverLocked());
|
||||
}
|
||||
|
||||
private boolean isEbookBookFile(BookFileEntity file) {
|
||||
return file.isBookFormat() && file.getBookType() != BookFileType.AUDIOBOOK;
|
||||
}
|
||||
|
||||
private boolean hasAudiobookFile(BookEntity book) {
|
||||
var files = book.getBookFiles();
|
||||
return files != null && files.stream()
|
||||
.anyMatch(f -> f.isBookFormat() && f.getBookType() == BookFileType.AUDIOBOOK);
|
||||
}
|
||||
|
||||
private boolean hasEbookFile(BookEntity book) {
|
||||
var files = book.getBookFiles();
|
||||
return files != null && files.stream().anyMatch(this::isEbookBookFile);
|
||||
}
|
||||
|
||||
private BookFileEntity findEbookFile(BookEntity bookEntity) {
|
||||
var bookFiles = bookEntity.getBookFiles();
|
||||
if (bookFiles == null || bookFiles.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var library = bookEntity.getLibrary();
|
||||
if (library != null && library.getFormatPriority() != null && !library.getFormatPriority().isEmpty()) {
|
||||
for (BookFileType format : library.getFormatPriority()) {
|
||||
if (format == BookFileType.AUDIOBOOK) {
|
||||
continue;
|
||||
}
|
||||
var match = bookFiles.stream()
|
||||
.filter(bf -> bf.isBookFormat() && bf.getBookType() == format)
|
||||
.min(Comparator.comparingLong(BookFileEntity::getId));
|
||||
if (match.isPresent()) {
|
||||
return match.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bookFiles.stream()
|
||||
.filter(this::isEbookBookFile)
|
||||
.min(Comparator.comparingLong(BookFileEntity::getId))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private boolean hasUnlockedEbookSlot(BookEntity book) {
|
||||
return (!hasAudiobookFile(book) || hasEbookFile(book)) && !isCoverLocked(book);
|
||||
}
|
||||
|
||||
private boolean hasUnlockedAudiobookSlot(BookEntity book) {
|
||||
return hasAudiobookFile(book) && !isAudiobookCoverLocked(book);
|
||||
}
|
||||
|
||||
private boolean ebookSlotNeedsRegeneration(BookEntity book, boolean missingOnly) {
|
||||
return hasEbookFile(book) && !isCoverLocked(book) && (!missingOnly || book.getBookCoverHash() == null);
|
||||
}
|
||||
|
||||
private boolean audiobookSlotNeedsRegeneration(BookEntity book, boolean missingOnly) {
|
||||
return hasUnlockedAudiobookSlot(book) && (!missingOnly || book.getAudiobookCoverHash() == null);
|
||||
}
|
||||
|
||||
private boolean needsRegeneration(BookEntity book, boolean missingOnly) {
|
||||
return ebookSlotNeedsRegeneration(book, missingOnly) || audiobookSlotNeedsRegeneration(book, missingOnly);
|
||||
}
|
||||
|
||||
private void applyCustomBookCover(BookEntity bookEntity) {
|
||||
byte[] coverBytes = coverImageGenerator.generateCover(bookEntity.getMetadata().getTitle(), getAuthorNames(bookEntity));
|
||||
fileService.createThumbnailFromBytes(bookEntity.getId(), coverBytes);
|
||||
writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromBytes(book, coverBytes));
|
||||
updateBookCoverMetadata(bookEntity);
|
||||
}
|
||||
|
||||
private void applyCustomAudiobookCover(BookEntity bookEntity) {
|
||||
byte[] coverBytes = coverImageGenerator.generateSquareCover(bookEntity.getMetadata().getTitle(), getAuthorNames(bookEntity));
|
||||
fileService.createAudiobookThumbnailFromBytes(bookEntity.getId(), coverBytes);
|
||||
writeAudiobookCoverToFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromBytes(book, coverBytes));
|
||||
updateAudiobookCoverMetadata(bookEntity);
|
||||
}
|
||||
|
||||
private String getAuthorNames(BookEntity bookEntity) {
|
||||
if (bookEntity.getMetadata().getAuthors() != null && !bookEntity.getMetadata().getAuthors().isEmpty()) {
|
||||
return bookEntity.getMetadata().getAuthors().stream()
|
||||
@@ -662,9 +668,26 @@ public class BookCoverService {
|
||||
}
|
||||
|
||||
private void notifyBookCoverUpdate(BookEntity bookEntity) {
|
||||
List<BookCoverUpdateProjection> updates = bookRepository.findCoverUpdateInfoByIds(List.of(bookEntity.getId()));
|
||||
if (!updates.isEmpty()) {
|
||||
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, updates);
|
||||
Long bookId = bookEntity.getId();
|
||||
Runnable notify = () -> {
|
||||
try {
|
||||
List<BookCoverUpdateProjection> updates = bookRepository.findCoverUpdateInfoByIds(List.of(bookId));
|
||||
if (!updates.isEmpty()) {
|
||||
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, updates);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to send cover update notification for book ID {}: {}", bookId, e.getMessage());
|
||||
}
|
||||
};
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
notify.run();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
notify.run();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -672,9 +695,13 @@ public class BookCoverService {
|
||||
if (refreshedIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<BookCoverUpdateProjection> updates = bookRepository.findCoverUpdateInfoByIds(refreshedIds);
|
||||
if (!updates.isEmpty()) {
|
||||
sendNotification(username, Topic.BOOKS_COVER_UPDATE, updates);
|
||||
try {
|
||||
List<BookCoverUpdateProjection> updates = bookRepository.findCoverUpdateInfoByIds(refreshedIds);
|
||||
if (!updates.isEmpty()) {
|
||||
sendNotification(username, Topic.BOOKS_COVER_UPDATE, updates);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to send cover update notification for book IDs {}: {}", refreshedIds, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+10
-6
@@ -230,14 +230,14 @@ public class AudiobookMetadataWriter implements MetadataWriter {
|
||||
return;
|
||||
}
|
||||
|
||||
File file = audioFile.getFullFilePath().toFile();
|
||||
if (!shouldSaveMetadataToFile(file)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (audioFile.isFolderBased()) {
|
||||
Path folderPath = audioFile.getFullFilePath();
|
||||
saveCoverToFolder(folderPath, coverData);
|
||||
saveCoverToFolder(file.toPath(), coverData);
|
||||
} else {
|
||||
File file = audioFile.getFullFilePath().toFile();
|
||||
if (!shouldSaveMetadataToFile(file)) {
|
||||
return;
|
||||
}
|
||||
replaceCoverImageInternal(file, coverData, "byte array");
|
||||
}
|
||||
}
|
||||
@@ -317,6 +317,10 @@ public class AudiobookMetadataWriter implements MetadataWriter {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (audioFile.isDirectory()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
long fileSizeInMb = audioFile.length() / (1024 * 1024);
|
||||
if (fileSizeInMb > audiobookSettings.getMaxFileSizeInMb()) {
|
||||
log.info("Audiobook file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.",
|
||||
|
||||
@@ -32,6 +32,8 @@ import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.transaction.support.TransactionCallback;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@@ -97,6 +99,29 @@ class BookCoverServiceTest {
|
||||
.build();
|
||||
}
|
||||
|
||||
private void runAsyncInline() {
|
||||
doAnswer(inv -> {
|
||||
inv.<Runnable>getArgument(0).run();
|
||||
return null;
|
||||
}).when(taskExecutor).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
private void runTransactionsInline() {
|
||||
when(transactionTemplate.execute(any())).thenAnswer(inv -> {
|
||||
var callback = inv.getArgument(0, TransactionCallback.class);
|
||||
return callback.doInTransaction(null);
|
||||
});
|
||||
}
|
||||
|
||||
private MultipartFile validPngFile() throws Exception {
|
||||
MultipartFile file = mock(MultipartFile.class);
|
||||
when(file.isEmpty()).thenReturn(false);
|
||||
when(file.getSize()).thenReturn(1024L);
|
||||
when(file.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[]{(byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}));
|
||||
when(file.getBytes()).thenReturn(new byte[]{1, 2, 3});
|
||||
return file;
|
||||
}
|
||||
|
||||
@Nested
|
||||
class BookNotFound {
|
||||
|
||||
@@ -688,23 +713,44 @@ class BookCoverServiceTest {
|
||||
class BulkRegenerateCoversForBooks {
|
||||
|
||||
@Test
|
||||
void delegatesToAsyncExecutorWithUnlockedBooks() {
|
||||
BookEntity unlocked = buildBook(1L, false);
|
||||
unlocked.setBookFiles(Set.of(BookFileEntity.builder().bookType(BookFileType.EPUB).isBookFormat(true).build()));
|
||||
unlocked.setLibrary(LibraryEntity.builder().build());
|
||||
BookEntity locked = buildBook(2L, true);
|
||||
void regeneratesBothBooksInMixedBookAndAudiobookSelection() {
|
||||
BookEntity ebook = buildBook(1L, false);
|
||||
BookFileEntity ebookFile = BookFileEntity.builder()
|
||||
.bookType(BookFileType.EPUB)
|
||||
.isBookFormat(true)
|
||||
.build();
|
||||
ebook.setBookFiles(Set.of(ebookFile));
|
||||
BookEntity audiobook = buildBookWithAudiobookLock(2L, false);
|
||||
audiobook.setBookFiles(Set.of(BookFileEntity.builder()
|
||||
.bookType(BookFileType.AUDIOBOOK)
|
||||
.isBookFormat(true)
|
||||
.build()));
|
||||
|
||||
BookFileProcessor ebookProcessor = mock(BookFileProcessor.class);
|
||||
BookFileProcessor audiobookProcessor = mock(BookFileProcessor.class);
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L)))
|
||||
.thenReturn(List.of(unlocked, locked));
|
||||
|
||||
doAnswer(inv -> {
|
||||
inv.<Runnable>getArgument(0).run();
|
||||
return null;
|
||||
}).when(taskExecutor).execute(any(Runnable.class));
|
||||
.thenReturn(List.of(ebook, audiobook));
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(ebook));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(audiobook));
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(ebookProcessor);
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.AUDIOBOOK)).thenReturn(audiobookProcessor);
|
||||
when(ebookProcessor.generateCover(ebook, ebookFile)).thenReturn(true);
|
||||
when(audiobookProcessor.generateAudiobookCover(audiobook)).thenReturn(true);
|
||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
|
||||
runAsyncInline();
|
||||
runTransactionsInline();
|
||||
|
||||
service.regenerateCoversForBooks(Set.of(1L, 2L));
|
||||
|
||||
verify(taskExecutor).execute(any(Runnable.class));
|
||||
verify(ebookProcessor).generateCover(ebook, ebookFile);
|
||||
verify(audiobookProcessor).generateAudiobookCover(audiobook);
|
||||
verify(bookRepository).save(ebook);
|
||||
verify(bookRepository).save(audiobook);
|
||||
assertThat(ebook.getMetadata().getCoverUpdatedOn()).isNotNull();
|
||||
assertThat(audiobook.getMetadata().getAudiobookCoverUpdatedOn()).isNotNull();
|
||||
assertThat(audiobook.getAudiobookCoverHash()).isNotNull();
|
||||
assertThat(audiobook.getMetadata().getCoverUpdatedOn()).isNull();
|
||||
assertThat(audiobook.getBookCoverHash()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -712,21 +758,39 @@ class BookCoverServiceTest {
|
||||
class BulkGenerateCustomCoversForBooks {
|
||||
|
||||
@Test
|
||||
void delegatesToAsyncExecutorWithUnlockedBooks() {
|
||||
BookEntity unlocked = buildBook(1L, false);
|
||||
BookEntity locked = buildBook(2L, true);
|
||||
void generatesTheCorrectCoverShapeForMixedBookAndAudiobookSelection() {
|
||||
when(appProperties.isLocalStorage()).thenReturn(false);
|
||||
BookEntity ebook = buildBook(1L, false);
|
||||
ebook.setBookFiles(Set.of(BookFileEntity.builder()
|
||||
.bookType(BookFileType.EPUB)
|
||||
.isBookFormat(true)
|
||||
.build()));
|
||||
BookEntity audiobook = buildBookWithAudiobookLock(2L, false);
|
||||
audiobook.setBookFiles(Set.of(BookFileEntity.builder()
|
||||
.bookType(BookFileType.AUDIOBOOK)
|
||||
.isBookFormat(true)
|
||||
.build()));
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L)))
|
||||
.thenReturn(List.of(unlocked, locked));
|
||||
|
||||
doAnswer(inv -> {
|
||||
inv.<Runnable>getArgument(0).run();
|
||||
return null;
|
||||
}).when(taskExecutor).execute(any(Runnable.class));
|
||||
.thenReturn(List.of(ebook, audiobook));
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(ebook));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(audiobook));
|
||||
when(coverImageGenerator.generateCover("Test Book", null)).thenReturn(new byte[]{1});
|
||||
when(coverImageGenerator.generateSquareCover("Test Audiobook", null)).thenReturn(new byte[]{2});
|
||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
|
||||
runAsyncInline();
|
||||
runTransactionsInline();
|
||||
|
||||
service.generateCustomCoversForBooks(Set.of(1L, 2L));
|
||||
|
||||
verify(taskExecutor).execute(any(Runnable.class));
|
||||
verify(coverImageGenerator).generateCover("Test Book", null);
|
||||
verify(coverImageGenerator).generateSquareCover("Test Audiobook", null);
|
||||
verify(fileService).createThumbnailFromBytes(eq(1L), any());
|
||||
verify(fileService).createAudiobookThumbnailFromBytes(eq(2L), any());
|
||||
verify(fileService, never()).createThumbnailFromBytes(eq(2L), any());
|
||||
verify(fileService, never()).createAudiobookThumbnailFromBytes(eq(1L), any());
|
||||
verify(bookRepository).save(ebook);
|
||||
verify(bookRepository).save(audiobook);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -734,30 +798,30 @@ class BookCoverServiceTest {
|
||||
class BulkUpdateCoverFromFileForBooks {
|
||||
|
||||
@Test
|
||||
void processesOnlyUnlockedBooks() throws Exception {
|
||||
void appliesUploadedCoverToAudiobookSlotForAudiobookOnlyBooks() throws Exception {
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
when(appSettings.getMaxFileUploadSizeInMb()).thenReturn(5);
|
||||
|
||||
BookEntity unlocked = buildBook(1L, false);
|
||||
BookEntity locked = buildBook(2L, true);
|
||||
BookEntity audiobook = buildBookWithAudiobookLock(1L, false);
|
||||
audiobook.setBookFiles(Set.of(BookFileEntity.builder()
|
||||
.bookType(BookFileType.AUDIOBOOK)
|
||||
.isBookFormat(true)
|
||||
.build()));
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L)))
|
||||
.thenReturn(List.of(unlocked, locked));
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(audiobook));
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(audiobook));
|
||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
|
||||
MultipartFile file = validPngFile();
|
||||
runAsyncInline();
|
||||
runTransactionsInline();
|
||||
|
||||
MultipartFile file = mock(MultipartFile.class);
|
||||
when(file.isEmpty()).thenReturn(false);
|
||||
when(file.getSize()).thenReturn(1024L);
|
||||
when(file.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[]{(byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}));
|
||||
when(file.getBytes()).thenReturn(new byte[]{1, 2, 3});
|
||||
service.updateCoverFromFileForBooks(Set.of(1L), file);
|
||||
|
||||
doAnswer(inv -> {
|
||||
inv.<Runnable>getArgument(0).run();
|
||||
return null;
|
||||
}).when(taskExecutor).execute(any(Runnable.class));
|
||||
|
||||
service.updateCoverFromFileForBooks(Set.of(1L, 2L), file);
|
||||
|
||||
verify(taskExecutor).execute(any(Runnable.class));
|
||||
verify(fileService).createAudiobookThumbnailFromBytes(eq(1L), any());
|
||||
verify(fileService, never()).createThumbnailFromBytes(eq(1L), any());
|
||||
verify(bookRepository).save(audiobook);
|
||||
assertThat(audiobook.getMetadata().getAudiobookCoverUpdatedOn()).isNotNull();
|
||||
assertThat(audiobook.getAudiobookCoverHash()).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -781,13 +845,10 @@ class BookCoverServiceTest {
|
||||
});
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(processor);
|
||||
when(processor.generateCover(book)).thenReturn(true);
|
||||
when(processor.generateCover(book, ebookFile)).thenReturn(true);
|
||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
|
||||
|
||||
doAnswer(inv -> {
|
||||
inv.<Runnable>getArgument(0).run();
|
||||
return null;
|
||||
}).when(taskExecutor).execute(any(Runnable.class));
|
||||
runAsyncInline();
|
||||
|
||||
service.regenerateCovers(false);
|
||||
|
||||
@@ -805,10 +866,7 @@ class BookCoverServiceTest {
|
||||
|
||||
when(bookQueryService.getAllFullBookEntitiesWithFiles()).thenReturn(List.of(locked));
|
||||
|
||||
doAnswer(inv -> {
|
||||
inv.<Runnable>getArgument(0).run();
|
||||
return null;
|
||||
}).when(taskExecutor).execute(any(Runnable.class));
|
||||
runAsyncInline();
|
||||
|
||||
service.regenerateCovers(false);
|
||||
|
||||
@@ -840,13 +898,10 @@ class BookCoverServiceTest {
|
||||
});
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(withoutCover));
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(processor);
|
||||
when(processor.generateCover(withoutCover)).thenReturn(true);
|
||||
when(processor.generateCover(withoutCover, ebookFile2)).thenReturn(true);
|
||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
|
||||
|
||||
doAnswer(inv -> {
|
||||
inv.<Runnable>getArgument(0).run();
|
||||
return null;
|
||||
}).when(taskExecutor).execute(any(Runnable.class));
|
||||
runAsyncInline();
|
||||
|
||||
service.regenerateCovers(true);
|
||||
|
||||
@@ -863,10 +918,7 @@ class BookCoverServiceTest {
|
||||
|
||||
when(bookQueryService.getAllFullBookEntitiesWithFiles()).thenReturn(List.of(book));
|
||||
|
||||
doAnswer(inv -> {
|
||||
inv.<Runnable>getArgument(0).run();
|
||||
return null;
|
||||
}).when(taskExecutor).execute(any(Runnable.class));
|
||||
runAsyncInline();
|
||||
|
||||
service.regenerateCovers(false);
|
||||
|
||||
@@ -885,10 +937,7 @@ class BookCoverServiceTest {
|
||||
|
||||
when(bookQueryService.getAllFullBookEntitiesWithFiles()).thenReturn(List.of(book));
|
||||
|
||||
doAnswer(inv -> {
|
||||
inv.<Runnable>getArgument(0).run();
|
||||
return null;
|
||||
}).when(taskExecutor).execute(any(Runnable.class));
|
||||
runAsyncInline();
|
||||
|
||||
service.regenerateCovers(false);
|
||||
|
||||
@@ -904,12 +953,8 @@ class BookCoverServiceTest {
|
||||
BookEntity book = BookEntity.builder().id(1L).metadata(null).build();
|
||||
when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||
|
||||
// Test getUnlockedBookCoverInfos via updateCoverFromFileForBooks (async)
|
||||
doAnswer(inv -> {
|
||||
inv.<Runnable>getArgument(0).run();
|
||||
return null;
|
||||
}).when(taskExecutor).execute(any(Runnable.class));
|
||||
|
||||
runAsyncInline();
|
||||
|
||||
MultipartFile file = mock(MultipartFile.class);
|
||||
when(file.isEmpty()).thenReturn(false);
|
||||
when(file.getSize()).thenReturn(1024L);
|
||||
@@ -1086,6 +1131,29 @@ class BookCoverServiceTest {
|
||||
verify(notificationService).sendMessage(any(), eq(List.of(projection)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendsNotificationAfterCommitNotBefore() {
|
||||
BookEntity book = buildBook(1L, false);
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
|
||||
BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class);
|
||||
when(bookRepository.findCoverUpdateInfoByIds(List.of(1L))).thenReturn(List.of(projection));
|
||||
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
|
||||
|
||||
verify(notificationService, never()).sendMessage(any(), anyList());
|
||||
|
||||
List<TransactionSynchronization> syncs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertThat(syncs).hasSize(1);
|
||||
|
||||
syncs.forEach(TransactionSynchronization::afterCommit);
|
||||
verify(notificationService).sendMessage(any(), eq(List.of(projection)));
|
||||
} finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotSendNotificationWhenNoUpdates() {
|
||||
BookEntity book = buildBook(1L, false);
|
||||
|
||||
Reference in New Issue
Block a user