fix(cover): apply bulk cover actions to audiobook covers (#2623)

This commit is contained in:
Alex
2026-09-28 07:54:27 +01:00
committed by GitHub
parent e937943c40
commit 3c04d916d9
6 changed files with 389 additions and 288 deletions
@@ -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
@@ -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());
}
}
}
@@ -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.",