refactor(library): implement asynchronous book addition and cover generation with event handling (#329)

* refactor(library): implement asynchronous book addition and cover generation with event handling

* fix(bookcover): handle null metadata before updating audiobook and ebook cover information

* fic(library): add library processing service and task executor
This commit is contained in:
brios
2026-04-22 17:27:08 -04:00
committed by Zach Yale
parent 10c7fac190
commit 536daa996e
19 changed files with 540 additions and 448 deletions
@@ -3,14 +3,12 @@ package org.booklore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.booklore.config.AppProperties;
import org.booklore.config.BookmarkProperties;
@EnableScheduling
@EnableAsync
@EnableConfigurationProperties({AppProperties.class, BookmarkProperties.class})
@SpringBootApplication
public class BookloreApplication {
@@ -3,13 +3,18 @@ package org.booklore.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.VirtualThreadTaskExecutor;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler;
import org.springframework.security.concurrent.DelegatingSecurityContextExecutor;
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class TaskExecutorConfig {
@Bean(name = "taskExecutor")
@@ -28,10 +33,9 @@ public class TaskExecutorConfig {
@Bean
public TaskScheduler taskScheduler() {
SimpleAsyncTaskScheduler scheduler = new SimpleAsyncTaskScheduler();
var scheduler = new SimpleAsyncTaskScheduler();
scheduler.setVirtualThreads(true);
scheduler.setThreadNamePrefix("scheduler-");
return scheduler;
}
}
@@ -27,13 +27,14 @@ import org.booklore.repository.BookRepository;
import org.booklore.repository.BookdropFileRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.NotificationService;
import org.booklore.service.event.BookAddedEvent;
import org.booklore.service.file.FileMovingHelper;
import org.booklore.service.fileprocessor.BookFileProcessor;
import org.booklore.service.fileprocessor.BookFileProcessorRegistry;
import org.booklore.service.kobo.KoboAutoShelfService;
import org.booklore.service.metadata.MetadataRefreshService;
import org.booklore.service.monitoring.MonitoringRegistrationService;
import org.booklore.util.FileUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
@@ -77,7 +78,7 @@ public class BookDropService {
private final ObjectMapper objectMapper;
private final FileMovingHelper fileMovingHelper;
private final MonitoringRegistrationService monitoringRegistrationService;
private final KoboAutoShelfService koboAutoShelfService;
private final ApplicationEventPublisher eventPublisher;
private final PlatformTransactionManager transactionManager;
private static final int CHUNK_SIZE = 100;
@@ -493,7 +494,7 @@ public class BookDropService {
.build();
metadataRefreshService.updateBookMetadata(context);
koboAutoShelfService.autoAddBookToKoboShelves(bookEntity.getId());
eventPublisher.publishEvent(new BookAddedEvent(fileProcessResult.getBook()));
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook());
});
@@ -0,0 +1,12 @@
package org.booklore.service.event;
import org.booklore.model.dto.Book;
/**
* Event published after a book has been successfully created.
* Listeners can react to this event after the transaction commits.
*
* @param book the newly created book
*/
public record BookAddedEvent(Book book) {
}
@@ -0,0 +1,38 @@
package org.booklore.service.event;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.Book;
import org.booklore.service.kobo.KoboAutoShelfService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
/**
* Handles book creation events after the triggering transaction commits.
* Broadcasts notifications and adds books to Kobo shelves automatically.
* Execution is asynchronous with security context propagation.
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BookAddedEventListener {
private final BookEventBroadcaster bookEventBroadcaster;
private final KoboAutoShelfService koboAutoShelfService;
@Async("taskExecutor")
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
public void handle(BookAddedEvent event) {
Book book = event.book();
try {
log.debug("Processing book added event for book ID {}", book.getId());
bookEventBroadcaster.broadcastBookAddEvent(book);
koboAutoShelfService.autoAddBookToKoboShelves(book.getId());
log.info("Book {} notifications and Kobo shelf updates completed", book.getId());
} catch (Exception e) {
log.error("Failed to process book added event for book ID {}: {}", book.getId(), e.getMessage(), e);
}
}
}
@@ -0,0 +1,167 @@
package org.booklore.service.library;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.settings.LibraryFile;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookRepository;
import org.booklore.service.metadata.extractor.AudiobookMetadataExtractor;
import org.booklore.service.metadata.extractor.MetadataExtractorFactory;
import org.booklore.util.BookCoverUtils;
import org.booklore.util.FileService;
import org.booklore.util.FileUtils;
import org.springframework.stereotype.Component;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.file.Path;
import java.time.Instant;
/**
* Handles cover image generation from book files.
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BookCoverGenerator {
private final BookRepository bookRepository;
private final FileService fileService;
private final MetadataExtractorFactory metadataExtractorFactory;
private final AudiobookMetadataExtractor audiobookMetadataExtractor;
/**
* Generates a cover image from an additional file and attaches it to the book.
*/
public void generateCoverFromAdditionalFile(BookEntity bookEntity, LibraryFile additionalFile) {
BookFileType additionalType = additionalFile.getBookFileType();
boolean additionalIsAudiobook = additionalType == BookFileType.AUDIOBOOK;
if (!bookEntity.hasFiles()) {
try {
if (additionalIsAudiobook) {
generateAudiobookCoverFromFile(bookEntity, additionalFile);
} else {
generateEbookCoverFromFile(bookEntity, additionalFile);
}
} catch (Exception e) {
log.warn("Failed to generate cover from additional file {}: {}", additionalFile.getFileName(), e.getMessage());
}
return;
}
BookFileType primaryType = bookEntity.getPrimaryBookFile().getBookType();
boolean primaryIsAudiobook = primaryType == BookFileType.AUDIOBOOK;
if (primaryIsAudiobook == additionalIsAudiobook) {
return;
}
try {
if (additionalIsAudiobook) {
generateAudiobookCoverFromFile(bookEntity, additionalFile);
} else {
generateEbookCoverFromFile(bookEntity, additionalFile);
}
} catch (Exception e) {
log.warn("Failed to generate cover from additional file {}: {}", additionalFile.getFileName(), e.getMessage());
}
}
private void generateAudiobookCoverFromFile(BookEntity bookEntity, LibraryFile audioFile) {
try {
File file = getFileForCoverExtraction(audioFile);
if (file == null || !file.exists()) {
log.debug("Audio file not found for cover extraction: {}", audioFile.getFileName());
return;
}
byte[] coverData = audiobookMetadataExtractor.extractCover(file);
if (coverData == null) {
log.debug("No cover image found in audiobook '{}'", audioFile.getFileName());
return;
}
try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) {
BufferedImage originalImage = FileService.readImage(bais);
if (originalImage == null) {
log.warn("Failed to decode cover image for audiobook '{}'", audioFile.getFileName());
return;
}
boolean saved = fileService.saveAudiobookCoverImages(originalImage, bookEntity.getId());
originalImage.flush();
if (saved) {
if (bookEntity.getMetadata() != null) {
bookEntity.getMetadata().setAudiobookCoverUpdatedOn(Instant.now());
} else {
log.debug("Skipping audiobook cover update on metadata for book ID {}: metadata is null", bookEntity.getId());
}
bookEntity.setAudiobookCoverHash(BookCoverUtils.generateCoverHash());
bookRepository.save(bookEntity);
log.info("Generated audiobook cover from additional file: {}", audioFile.getFileName());
}
}
} catch (Exception e) {
log.warn("Error generating audiobook cover from {}: {}", audioFile.getFileName(), e.getMessage());
}
}
private void generateEbookCoverFromFile(BookEntity bookEntity, LibraryFile ebookFile) {
try {
File file = ebookFile.getFullPath().toFile();
if (!file.exists()) {
log.debug("Ebook file not found for cover extraction: {}", ebookFile.getFileName());
return;
}
var extractor = metadataExtractorFactory.getExtractor(ebookFile.getBookFileType());
if (extractor == null) {
log.debug("No extractor available for file type: {}", ebookFile.getBookFileType());
return;
}
byte[] coverData = extractor.extractCover(file);
if (coverData == null) {
log.debug("No cover image found in ebook '{}'", ebookFile.getFileName());
return;
}
try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) {
BufferedImage originalImage = FileService.readImage(bais);
if (originalImage == null) {
log.warn("Failed to decode cover image for ebook '{}'", ebookFile.getFileName());
return;
}
boolean saved = fileService.saveCoverImages(originalImage, bookEntity.getId());
originalImage.flush();
if (saved) {
if (bookEntity.getMetadata() != null) {
FileService.setBookCoverPath(bookEntity.getMetadata());
} else {
log.debug("Skipping ebook cover path update for book ID {}: metadata is null", bookEntity.getId());
}
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
bookRepository.save(bookEntity);
log.info("Generated ebook cover from additional file: {}", ebookFile.getFileName());
}
}
} catch (Exception e) {
log.warn("Error generating ebook cover from {}: {}", ebookFile.getFileName(), e.getMessage());
}
}
private File getFileForCoverExtraction(LibraryFile libraryFile) {
if (libraryFile.isFolderBased()) {
Path folderPath = libraryFile.getFullPath();
return FileUtils.getFirstAudioFileInFolder(folderPath)
.map(Path::toFile)
.orElse(null);
} else {
return libraryFile.getFullPath().toFile();
}
}
}
@@ -0,0 +1,149 @@
package org.booklore.service.library;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.exception.ApiError;
import org.booklore.model.FileProcessResult;
import org.booklore.model.dto.Book;
import org.booklore.model.dto.settings.LibraryFile;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookAdditionalFileRepository;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.event.BookAddedEvent;
import org.booklore.service.file.FileFingerprint;
import org.booklore.service.fileprocessor.BookFileProcessor;
import org.booklore.service.fileprocessor.BookFileProcessorRegistry;
import org.booklore.util.FileUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
/**
* Transactional processor for book file groups.
* Each process() call runs in its own REQUIRES_NEW transaction.
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BookGroupProcessor {
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final BookFileProcessorRegistry processorRegistry;
private final BookCoverGenerator bookCoverGenerator;
private final ApplicationEventPublisher eventPublisher;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void process(List<LibraryFile> group, long libraryId) {
LibraryEntity library = libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
group.forEach(lf -> lf.setLibraryEntity(library));
Optional<LibraryFile> primaryFile = findBestPrimaryFile(group, library);
if (primaryFile.isEmpty()) {
log.warn("No suitable book file found in group");
return;
}
LibraryFile primary = primaryFile.get();
log.info("Processing file: {}", primary.getFileName());
BookFileType type = primary.getBookFileType();
if (type == null) {
log.warn("Unsupported file type for file: {}", primary.getFileName());
return;
}
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
FileProcessResult result = processor.processFile(primary);
if (result == null || result.getBook() == null) {
log.warn("Failed to process primary file: {}", primary.getFileName());
return;
}
Book book = result.getBook();
long bookId = book.getId();
List<LibraryFile> additionalFiles = group.stream()
.filter(f -> !f.equals(primary))
.toList();
if (!additionalFiles.isEmpty()) {
BookEntity bookEntity = bookRepository.getReferenceById(bookId);
for (LibraryFile additionalFile : additionalFiles) {
createAdditionalBookFile(bookEntity, additionalFile);
}
}
eventPublisher.publishEvent(new BookAddedEvent(book));
}
private Optional<LibraryFile> findBestPrimaryFile(List<LibraryFile> group, LibraryEntity library) {
List<BookFileType> formatPriority = library.getFormatPriority();
return group.stream()
.filter(f -> f.getBookFileType() != null)
.min(Comparator.comparingInt((LibraryFile f) -> {
BookFileType bookFileType = f.getBookFileType();
if (formatPriority != null && !formatPriority.isEmpty()) {
int index = formatPriority.indexOf(bookFileType);
return index >= 0 ? index : Integer.MAX_VALUE;
}
return bookFileType.ordinal();
}).thenComparing(LibraryFile::getFileName));
}
private void createAdditionalBookFile(BookEntity bookEntity, LibraryFile file) {
Optional<BookFileEntity> existing = bookAdditionalFileRepository
.findByLibraryPath_IdAndFileSubPathAndFileName(
file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName());
if (existing.isPresent()) {
log.debug("Additional file already exists: {}", file.getFileName());
return;
}
String hash;
Long fileSizeKb;
if (file.isFolderBased()) {
hash = FileFingerprint.generateFolderHash(file.getFullPath());
fileSizeKb = FileUtils.getFolderSizeInKb(file.getFullPath());
} else {
hash = FileFingerprint.generateHash(file.getFullPath());
fileSizeKb = FileUtils.getFileSizeInKb(file.getFullPath());
}
BookFileEntity additionalFile = BookFileEntity.builder()
.book(bookEntity)
.fileName(file.getFileName())
.fileSubPath(file.getFileSubPath())
.isBookFormat(true)
.folderBased(file.isFolderBased())
.bookType(file.getBookFileType())
.fileSizeKb(fileSizeKb)
.initialHash(hash)
.currentHash(hash)
.addedOn(Instant.now())
.build();
try {
bookAdditionalFileRepository.save(additionalFile);
String primaryFileName = bookEntity.getPrimaryBookFile() != null ? bookEntity.getPrimaryBookFile().getFileName() : "unknown";
log.info("Attached additional format {} to book: {}", file.getFileName(), primaryFileName);
bookCoverGenerator.generateCoverFromAdditionalFile(bookEntity, file);
} catch (Exception e) {
log.error("Error creating additional file {}: {}", file.getFileName(), e.getMessage());
}
}
}
@@ -1,303 +1,42 @@
package org.booklore.service.library;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.exception.ApiError;
import org.booklore.model.FileProcessResult;
import org.booklore.model.dto.settings.LibraryFile;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookAdditionalFileRepository;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.event.BookEventBroadcaster;
import org.booklore.service.file.FileFingerprint;
import org.booklore.service.fileprocessor.BookFileProcessor;
import org.booklore.service.fileprocessor.BookFileProcessorRegistry;
import org.booklore.service.kobo.KoboAutoShelfService;
import org.booklore.service.metadata.extractor.AudiobookMetadataExtractor;
import org.booklore.service.metadata.extractor.MetadataExtractorFactory;
import org.booklore.util.BookCoverUtils;
import org.booklore.util.BookFileGroupingUtils;
import org.booklore.util.FileService;
import org.booklore.util.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@AllArgsConstructor
/**
* Orchestrator for processing library files as books.
* Delegates transactional processing to BookGroupProcessor.
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class FileAsBookProcessor {
private final BookEventBroadcaster bookEventBroadcaster;
private final BookFileProcessorRegistry processorRegistry;
private final KoboAutoShelfService koboAutoShelfService;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final LibraryRepository libraryRepository;
private final FileService fileService;
private final MetadataExtractorFactory metadataExtractorFactory;
private final AudiobookMetadataExtractor audiobookMetadataExtractor;
private final BookGroupProcessor bookGroupProcessor;
@Transactional
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(libraryFiles);
processLibraryFilesGrouped(groups, libraryEntity);
}
@Transactional
public void processLibraryFilesGrouped(Map<String, List<LibraryFile>> groups, LibraryEntity libraryEntity) {
LibraryEntity managedLibrary = ensureManaged(libraryEntity);
long libraryId = libraryEntity.getId();
for (Map.Entry<String, List<LibraryFile>> entry : groups.entrySet()) {
entry.getValue().forEach(lf -> lf.setLibraryEntity(managedLibrary));
processGroupWithErrorHandling(entry.getValue(), managedLibrary);
}
log.info("Finished processing library '{}'", managedLibrary.getName());
}
private LibraryEntity ensureManaged(LibraryEntity entity) {
if (entity.getId() == null) return entity;
return libraryRepository.findById(entity.getId())
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(entity.getId()));
}
private void processGroupWithErrorHandling(List<LibraryFile> group, LibraryEntity libraryEntity) {
try {
processGroup(group, libraryEntity);
} catch (Exception e) {
String fileNames = group.stream().map(LibraryFile::getFileName).toList().toString();
log.error("Failed to process file group {}: {}", fileNames, e.getMessage());
}
}
private void processGroup(List<LibraryFile> group, LibraryEntity libraryEntity) {
Optional<LibraryFile> primaryFile = findBestPrimaryFile(group, libraryEntity);
if (primaryFile.isEmpty()) {
log.warn("No suitable book file found in group");
return;
}
LibraryFile primary = primaryFile.get();
log.info("Processing file: {}", primary.getFileName());
BookFileType type = primary.getBookFileType();
if (type == null) {
log.warn("Unsupported file type for file: {}", primary.getFileName());
return;
}
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
FileProcessResult result = processor.processFile(primary);
if (result == null || result.getBook() == null) {
log.warn("Failed to process primary file: {}", primary.getFileName());
return;
}
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
koboAutoShelfService.autoAddBookToKoboShelves(result.getBook().getId());
List<LibraryFile> additionalFiles = group.stream()
.filter(f -> !f.equals(primary))
.toList();
if (!additionalFiles.isEmpty()) {
BookEntity bookEntity = bookRepository.getReferenceById(result.getBook().getId());
for (LibraryFile additionalFile : additionalFiles) {
createAdditionalBookFile(bookEntity, additionalFile);
}
}
}
private Optional<LibraryFile> findBestPrimaryFile(List<LibraryFile> group, LibraryEntity libraryEntity) {
List<BookFileType> formatPriority = libraryEntity.getFormatPriority();
return group.stream()
.filter(f -> f.getBookFileType() != null)
.min(Comparator.<LibraryFile, Integer>comparing(f -> {
BookFileType bookFileType = f.getBookFileType();
if (formatPriority != null && !formatPriority.isEmpty()) {
int index = formatPriority.indexOf(bookFileType);
return index >= 0 ? index : Integer.MAX_VALUE;
}
return bookFileType.ordinal();
}).thenComparing(LibraryFile::getFileName));
}
private void createAdditionalBookFile(BookEntity bookEntity, LibraryFile file) {
Optional<BookFileEntity> existing = bookAdditionalFileRepository
.findByLibraryPath_IdAndFileSubPathAndFileName(
file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName());
if (existing.isPresent()) {
log.debug("Additional file already exists: {}", file.getFileName());
return;
}
String hash;
Long fileSizeKb;
if (file.isFolderBased()) {
hash = FileFingerprint.generateFolderHash(file.getFullPath());
fileSizeKb = FileUtils.getFolderSizeInKb(file.getFullPath());
} else {
hash = FileFingerprint.generateHash(file.getFullPath());
fileSizeKb = FileUtils.getFileSizeInKb(file.getFullPath());
}
BookFileEntity additionalFile = BookFileEntity.builder()
.book(bookEntity)
.fileName(file.getFileName())
.fileSubPath(file.getFileSubPath())
.isBookFormat(true)
.folderBased(file.isFolderBased())
.bookType(file.getBookFileType())
.fileSizeKb(fileSizeKb)
.initialHash(hash)
.currentHash(hash)
.addedOn(Instant.now())
.build();
try {
bookAdditionalFileRepository.save(additionalFile);
log.info("Attached additional format {} to book: {}", file.getFileName(), bookEntity.getPrimaryBookFile().getFileName());
generateCoverFromAdditionalFile(bookEntity, file);
} catch (Exception e) {
log.error("Error creating additional file {}: {}", file.getFileName(), e.getMessage());
}
}
void generateCoverFromAdditionalFile(BookEntity bookEntity, LibraryFile additionalFile) {
BookFileType additionalType = additionalFile.getBookFileType();
boolean additionalIsAudiobook = additionalType == BookFileType.AUDIOBOOK;
// For fileless books, generate cover based on the additional file type
if (!bookEntity.hasFiles()) {
try {
if (additionalIsAudiobook) {
generateAudiobookCoverFromFile(bookEntity, additionalFile);
} else {
generateEbookCoverFromFile(bookEntity, additionalFile);
}
bookGroupProcessor.process(entry.getValue(), libraryId);
} catch (Exception e) {
log.warn("Failed to generate cover from additional file {}: {}", additionalFile.getFileName(), e.getMessage());
String fileNames = entry.getValue().stream()
.map(LibraryFile::getFileName).toList().toString();
log.error("Failed to process file group {}: {}", fileNames, e.getMessage());
}
return;
}
BookFileType primaryType = bookEntity.getPrimaryBookFile().getBookType();
boolean primaryIsAudiobook = primaryType == BookFileType.AUDIOBOOK;
// Only generate cover when mixing audiobook with ebook formats
if (primaryIsAudiobook == additionalIsAudiobook) {
return;
}
try {
if (additionalIsAudiobook) {
generateAudiobookCoverFromFile(bookEntity, additionalFile);
} else {
generateEbookCoverFromFile(bookEntity, additionalFile);
}
} catch (Exception e) {
log.warn("Failed to generate cover from additional file {}: {}", additionalFile.getFileName(), e.getMessage());
}
}
private void generateAudiobookCoverFromFile(BookEntity bookEntity, LibraryFile audioFile) {
try {
File file = getFileForCoverExtraction(audioFile);
if (file == null || !file.exists()) {
log.debug("Audio file not found for cover extraction: {}", audioFile.getFileName());
return;
}
byte[] coverData = audiobookMetadataExtractor.extractCover(file);
if (coverData == null) {
log.debug("No cover image found in audiobook '{}'", audioFile.getFileName());
return;
}
try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) {
BufferedImage originalImage = FileService.readImage(bais);
if (originalImage == null) {
log.warn("Failed to decode cover image for audiobook '{}'", audioFile.getFileName());
return;
}
boolean saved = fileService.saveAudiobookCoverImages(originalImage, bookEntity.getId());
originalImage.flush();
if (saved) {
bookEntity.getMetadata().setAudiobookCoverUpdatedOn(Instant.now());
bookEntity.setAudiobookCoverHash(BookCoverUtils.generateCoverHash());
bookRepository.save(bookEntity);
log.info("Generated audiobook cover from additional file: {}", audioFile.getFileName());
}
}
} catch (Exception e) {
log.warn("Error generating audiobook cover from {}: {}", audioFile.getFileName(), e.getMessage());
}
}
private void generateEbookCoverFromFile(BookEntity bookEntity, LibraryFile ebookFile) {
try {
File file = ebookFile.getFullPath().toFile();
if (!file.exists()) {
log.debug("Ebook file not found for cover extraction: {}", ebookFile.getFileName());
return;
}
var extractor = metadataExtractorFactory.getExtractor(ebookFile.getBookFileType());
if (extractor == null) {
log.debug("No extractor available for file type: {}", ebookFile.getBookFileType());
return;
}
byte[] coverData = extractor.extractCover(file);
if (coverData == null) {
log.debug("No cover image found in ebook '{}'", ebookFile.getFileName());
return;
}
try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) {
BufferedImage originalImage = FileService.readImage(bais);
if (originalImage == null) {
log.warn("Failed to decode cover image for ebook '{}'", ebookFile.getFileName());
return;
}
boolean saved = fileService.saveCoverImages(originalImage, bookEntity.getId());
originalImage.flush();
if (saved) {
FileService.setBookCoverPath(bookEntity.getMetadata());
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
bookRepository.save(bookEntity);
log.info("Generated ebook cover from additional file: {}", ebookFile.getFileName());
}
}
} catch (Exception e) {
log.warn("Error generating ebook cover from {}: {}", ebookFile.getFileName(), e.getMessage());
}
}
private File getFileForCoverExtraction(LibraryFile libraryFile) {
if (libraryFile.isFolderBased()) {
Path folderPath = libraryFile.getFullPath();
return FileUtils.getFirstAudioFileInFolder(folderPath)
.map(Path::toFile)
.orElse(null);
} else {
return libraryFile.getFullPath().toFile();
}
log.info("Finished processing library '{}'", libraryEntity.getName());
}
}
@@ -46,6 +46,7 @@ public class LibraryProcessingService {
private final BookDeletionService bookDeletionService;
private final LibraryFileHelper libraryFileHelper;
private final BookGroupingService bookGroupingService;
private final BookCoverGenerator bookCoverGenerator;
@PersistenceContext
private final EntityManager entityManager;
@@ -222,7 +223,7 @@ public class LibraryProcessingService {
bookAdditionalFileRepository.save(additionalFile);
String primaryFileName = book.hasFiles() ? book.getPrimaryBookFile().getFileName() : "book#" + book.getId();
log.info("Auto-attached new format {} to existing book: {}", file.getFileName(), primaryFileName);
fileAsBookProcessor.generateCoverFromAdditionalFile(book, file);
bookCoverGenerator.generateCoverFromAdditionalFile(book, file);
} catch (Exception e) {
log.error("Error auto-attaching file {}: {}", file.getFileName(), e.getMessage());
}
@@ -0,0 +1,62 @@
package org.booklore.service.library;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
import org.booklore.task.options.RescanLibraryContext;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Handles library scan requests after the triggering transaction commits.
* Scans are executed asynchronously with deduplication to prevent concurrent scans.
* Security context is automatically propagated via DelegatingSecurityContextExecutor.
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class LibraryScanListener {
private final LibraryProcessingService libraryProcessingService;
private final Set<Long> scanningLibraries = ConcurrentHashMap.newKeySet();
public boolean isScanning(long libraryId) {
return scanningLibraries.contains(libraryId);
}
@Async("taskExecutor")
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
public void handle(LibraryScanRequestedEvent event) {
long libraryId = event.libraryId();
if (!scanningLibraries.add(libraryId)) {
log.warn("Library {} is already being scanned, skipping duplicate request", libraryId);
return;
}
try {
log.info("Starting background scan for library ID {} (full rescan: {})", libraryId, event.fullRescan());
if (event.fullRescan()) {
libraryProcessingService.rescanLibrary(RescanLibraryContext.builder().libraryId(libraryId).build());
} else {
libraryProcessingService.processLibrary(libraryId);
}
log.info("Completed background scan for library ID {}", libraryId);
} catch (InvalidDataAccessApiUsageException e) {
log.debug("InvalidDataAccessApiUsageException during library scan - Library id: {}", libraryId, e);
} catch (IOException e) {
log.error("IO error during library scan for library ID {}: {}", libraryId, e.getMessage(), e);
} catch (Exception e) {
log.error("Unexpected error during library scan for library ID {}: {}", libraryId, e.getMessage(), e);
} finally {
scanningLibraries.remove(libraryId);
}
}
}
@@ -0,0 +1,10 @@
package org.booklore.service.library;
/**
* Event published when a library scan is requested.
* The actual scan will be performed after the current transaction commits.
*
* @param libraryId the ID of the library to scan
*/
public record LibraryScanRequestedEvent(long libraryId, boolean fullRescan) {
}
@@ -33,9 +33,9 @@ import org.springframework.context.event.EventListener;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
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.annotation.Transactional;
import java.io.IOException;
import java.nio.file.DirectoryStream;
@@ -54,21 +54,9 @@ import java.util.stream.Collectors;
@Transactional(readOnly = true)
public class LibraryService {
private static final Set<Long> scanningLibraries = ConcurrentHashMap.newKeySet();
/**
* Checks whether a library is currently being scanned.
* Can be used by other components (e.g., file watcher) to avoid processing
* files while a full scan is in progress.
*/
public static boolean isLibraryScanning(long libraryId) {
return scanningLibraries.contains(libraryId);
}
private final LibraryRepository libraryRepository;
private final LibraryPathRepository libraryPathRepository;
private final BookRepository bookRepository;
private final LibraryProcessingService libraryProcessingService;
private final BookMapper bookMapper;
private final LibraryMapper libraryMapper;
private final NotificationService notificationService;
@@ -77,7 +65,9 @@ public class LibraryService {
private final AuthenticationService authenticationService;
private final UserRepository userRepository;
private final AuditService auditService;
private final LibraryProcessingService libraryProcessingService;
private final Executor taskExecutor;
private final Set<Long> scanningLibraries = ConcurrentHashMap.newKeySet();
@Transactional
@EventListener(ApplicationReadyEvent.class)
@@ -12,6 +12,7 @@ import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.file.FileFingerprint;
import org.booklore.service.library.LibraryProcessingService;
import org.booklore.service.library.LibraryScanListener;
import org.booklore.util.FileUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -45,6 +46,7 @@ public class LibraryFileEventProcessor implements SmartLifecycle {
private final BookFileTransactionalHandler bookFileTransactionalHandler;
private final BookFilePersistenceService bookFilePersistenceService;
private final LibraryProcessingService libraryProcessingService;
private final LibraryScanListener libraryScanListener;
private final PendingDeletionPool pendingDeletionPool;
private ScheduledExecutorService scheduler;
@@ -104,6 +106,11 @@ public class LibraryFileEventProcessor implements SmartLifecycle {
}
public void processEvent(WatchEvent.Kind<?> eventKind, long libraryId, Path fullPath, boolean isDirectory) {
if (libraryScanListener.isScanning(libraryId)) {
log.debug("[SKIP] Library {} is currently being scanned, ignoring file event for '{}'", libraryId, fullPath);
return;
}
Path path = fullPath.toAbsolutePath().normalize();
if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {