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:
@@ -3,14 +3,12 @@ package org.booklore;
|
|||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
import org.springframework.scheduling.annotation.EnableAsync;
|
|
||||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
|
||||||
import org.booklore.config.AppProperties;
|
import org.booklore.config.AppProperties;
|
||||||
import org.booklore.config.BookmarkProperties;
|
import org.booklore.config.BookmarkProperties;
|
||||||
|
|
||||||
@EnableScheduling
|
@EnableScheduling
|
||||||
@EnableAsync
|
|
||||||
@EnableConfigurationProperties({AppProperties.class, BookmarkProperties.class})
|
@EnableConfigurationProperties({AppProperties.class, BookmarkProperties.class})
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class BookloreApplication {
|
public class BookloreApplication {
|
||||||
|
|||||||
@@ -3,13 +3,18 @@ package org.booklore.config;
|
|||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.core.task.AsyncTaskExecutor;
|
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.TaskScheduler;
|
||||||
|
import org.springframework.scheduling.annotation.EnableAsync;
|
||||||
import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler;
|
import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler;
|
||||||
|
import org.springframework.security.concurrent.DelegatingSecurityContextExecutor;
|
||||||
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
|
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
|
@EnableAsync
|
||||||
public class TaskExecutorConfig {
|
public class TaskExecutorConfig {
|
||||||
|
|
||||||
@Bean(name = "taskExecutor")
|
@Bean(name = "taskExecutor")
|
||||||
@@ -28,10 +33,9 @@ public class TaskExecutorConfig {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public TaskScheduler taskScheduler() {
|
public TaskScheduler taskScheduler() {
|
||||||
SimpleAsyncTaskScheduler scheduler = new SimpleAsyncTaskScheduler();
|
var scheduler = new SimpleAsyncTaskScheduler();
|
||||||
scheduler.setVirtualThreads(true);
|
scheduler.setVirtualThreads(true);
|
||||||
scheduler.setThreadNamePrefix("scheduler-");
|
scheduler.setThreadNamePrefix("scheduler-");
|
||||||
return scheduler;
|
return scheduler;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,13 +27,14 @@ import org.booklore.repository.BookRepository;
|
|||||||
import org.booklore.repository.BookdropFileRepository;
|
import org.booklore.repository.BookdropFileRepository;
|
||||||
import org.booklore.repository.LibraryRepository;
|
import org.booklore.repository.LibraryRepository;
|
||||||
import org.booklore.service.NotificationService;
|
import org.booklore.service.NotificationService;
|
||||||
|
import org.booklore.service.event.BookAddedEvent;
|
||||||
import org.booklore.service.file.FileMovingHelper;
|
import org.booklore.service.file.FileMovingHelper;
|
||||||
import org.booklore.service.fileprocessor.BookFileProcessor;
|
import org.booklore.service.fileprocessor.BookFileProcessor;
|
||||||
import org.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
import org.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||||
import org.booklore.service.kobo.KoboAutoShelfService;
|
|
||||||
import org.booklore.service.metadata.MetadataRefreshService;
|
import org.booklore.service.metadata.MetadataRefreshService;
|
||||||
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
import org.springframework.core.io.FileSystemResource;
|
import org.springframework.core.io.FileSystemResource;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
@@ -77,7 +78,7 @@ public class BookDropService {
|
|||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
private final FileMovingHelper fileMovingHelper;
|
private final FileMovingHelper fileMovingHelper;
|
||||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||||
private final KoboAutoShelfService koboAutoShelfService;
|
private final ApplicationEventPublisher eventPublisher;
|
||||||
private final PlatformTransactionManager transactionManager;
|
private final PlatformTransactionManager transactionManager;
|
||||||
|
|
||||||
private static final int CHUNK_SIZE = 100;
|
private static final int CHUNK_SIZE = 100;
|
||||||
@@ -493,7 +494,7 @@ public class BookDropService {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
metadataRefreshService.updateBookMetadata(context);
|
metadataRefreshService.updateBookMetadata(context);
|
||||||
koboAutoShelfService.autoAddBookToKoboShelves(bookEntity.getId());
|
eventPublisher.publishEvent(new BookAddedEvent(fileProcessResult.getBook()));
|
||||||
|
|
||||||
notificationService.sendMessage(Topic.BOOK_ADD, 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;
|
package org.booklore.service.library;
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
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.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.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.BookFileGroupingUtils;
|
||||||
import org.booklore.util.FileService;
|
|
||||||
import org.booklore.util.FileUtils;
|
|
||||||
import org.springframework.stereotype.Component;
|
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.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
/**
|
||||||
|
* Orchestrator for processing library files as books.
|
||||||
|
* Delegates transactional processing to BookGroupProcessor.
|
||||||
|
*/
|
||||||
@Component
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class FileAsBookProcessor {
|
public class FileAsBookProcessor {
|
||||||
|
|
||||||
private final BookEventBroadcaster bookEventBroadcaster;
|
private final BookGroupProcessor bookGroupProcessor;
|
||||||
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;
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(libraryFiles);
|
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(libraryFiles);
|
||||||
processLibraryFilesGrouped(groups, libraryEntity);
|
processLibraryFilesGrouped(groups, libraryEntity);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void processLibraryFilesGrouped(Map<String, List<LibraryFile>> groups, LibraryEntity libraryEntity) {
|
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()) {
|
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 {
|
try {
|
||||||
if (additionalIsAudiobook) {
|
bookGroupProcessor.process(entry.getValue(), libraryId);
|
||||||
generateAudiobookCoverFromFile(bookEntity, additionalFile);
|
|
||||||
} else {
|
|
||||||
generateEbookCoverFromFile(bookEntity, additionalFile);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
} 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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -46,6 +46,7 @@ public class LibraryProcessingService {
|
|||||||
private final BookDeletionService bookDeletionService;
|
private final BookDeletionService bookDeletionService;
|
||||||
private final LibraryFileHelper libraryFileHelper;
|
private final LibraryFileHelper libraryFileHelper;
|
||||||
private final BookGroupingService bookGroupingService;
|
private final BookGroupingService bookGroupingService;
|
||||||
|
private final BookCoverGenerator bookCoverGenerator;
|
||||||
@PersistenceContext
|
@PersistenceContext
|
||||||
private final EntityManager entityManager;
|
private final EntityManager entityManager;
|
||||||
|
|
||||||
@@ -222,7 +223,7 @@ public class LibraryProcessingService {
|
|||||||
bookAdditionalFileRepository.save(additionalFile);
|
bookAdditionalFileRepository.save(additionalFile);
|
||||||
String primaryFileName = book.hasFiles() ? book.getPrimaryBookFile().getFileName() : "book#" + book.getId();
|
String primaryFileName = book.hasFiles() ? book.getPrimaryBookFile().getFileName() : "book#" + book.getId();
|
||||||
log.info("Auto-attached new format {} to existing book: {}", file.getFileName(), primaryFileName);
|
log.info("Auto-attached new format {} to existing book: {}", file.getFileName(), primaryFileName);
|
||||||
fileAsBookProcessor.generateCoverFromAdditionalFile(book, file);
|
bookCoverGenerator.generateCoverFromAdditionalFile(book, file);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Error auto-attaching file {}: {}", file.getFileName(), e.getMessage());
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
@@ -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.dao.InvalidDataAccessApiUsageException;
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.transaction.support.TransactionSynchronization;
|
import org.springframework.transaction.support.TransactionSynchronization;
|
||||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.DirectoryStream;
|
import java.nio.file.DirectoryStream;
|
||||||
@@ -54,21 +54,9 @@ import java.util.stream.Collectors;
|
|||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public class LibraryService {
|
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 LibraryRepository libraryRepository;
|
||||||
private final LibraryPathRepository libraryPathRepository;
|
private final LibraryPathRepository libraryPathRepository;
|
||||||
private final BookRepository bookRepository;
|
private final BookRepository bookRepository;
|
||||||
private final LibraryProcessingService libraryProcessingService;
|
|
||||||
private final BookMapper bookMapper;
|
private final BookMapper bookMapper;
|
||||||
private final LibraryMapper libraryMapper;
|
private final LibraryMapper libraryMapper;
|
||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
@@ -77,7 +65,9 @@ public class LibraryService {
|
|||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final AuditService auditService;
|
private final AuditService auditService;
|
||||||
|
private final LibraryProcessingService libraryProcessingService;
|
||||||
private final Executor taskExecutor;
|
private final Executor taskExecutor;
|
||||||
|
private final Set<Long> scanningLibraries = ConcurrentHashMap.newKeySet();
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
@EventListener(ApplicationReadyEvent.class)
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import org.booklore.repository.BookRepository;
|
|||||||
import org.booklore.repository.LibraryRepository;
|
import org.booklore.repository.LibraryRepository;
|
||||||
import org.booklore.service.file.FileFingerprint;
|
import org.booklore.service.file.FileFingerprint;
|
||||||
import org.booklore.service.library.LibraryProcessingService;
|
import org.booklore.service.library.LibraryProcessingService;
|
||||||
|
import org.booklore.service.library.LibraryScanListener;
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -45,6 +46,7 @@ public class LibraryFileEventProcessor implements SmartLifecycle {
|
|||||||
private final BookFileTransactionalHandler bookFileTransactionalHandler;
|
private final BookFileTransactionalHandler bookFileTransactionalHandler;
|
||||||
private final BookFilePersistenceService bookFilePersistenceService;
|
private final BookFilePersistenceService bookFilePersistenceService;
|
||||||
private final LibraryProcessingService libraryProcessingService;
|
private final LibraryProcessingService libraryProcessingService;
|
||||||
|
private final LibraryScanListener libraryScanListener;
|
||||||
private final PendingDeletionPool pendingDeletionPool;
|
private final PendingDeletionPool pendingDeletionPool;
|
||||||
|
|
||||||
private ScheduledExecutorService scheduler;
|
private ScheduledExecutorService scheduler;
|
||||||
@@ -104,6 +106,11 @@ public class LibraryFileEventProcessor implements SmartLifecycle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void processEvent(WatchEvent.Kind<?> eventKind, long libraryId, Path fullPath, boolean isDirectory) {
|
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();
|
Path path = fullPath.toAbsolutePath().normalize();
|
||||||
|
|
||||||
if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {
|
if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {
|
||||||
|
|||||||
@@ -18,13 +18,14 @@ import org.booklore.repository.BookdropFileRepository;
|
|||||||
import org.booklore.repository.LibraryPathRepository;
|
import org.booklore.repository.LibraryPathRepository;
|
||||||
import org.booklore.repository.LibraryRepository;
|
import org.booklore.repository.LibraryRepository;
|
||||||
import org.booklore.service.NotificationService;
|
import org.booklore.service.NotificationService;
|
||||||
|
import org.booklore.service.event.BookAddedEvent;
|
||||||
import org.booklore.service.file.FileMovingHelper;
|
import org.booklore.service.file.FileMovingHelper;
|
||||||
import org.booklore.service.fileprocessor.BookFileProcessor;
|
import org.booklore.service.fileprocessor.BookFileProcessor;
|
||||||
import org.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
import org.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||||
import org.booklore.service.kobo.KoboAutoShelfService;
|
|
||||||
import org.booklore.service.metadata.MetadataRefreshService;
|
import org.booklore.service.metadata.MetadataRefreshService;
|
||||||
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
||||||
import org.junit.jupiter.api.AfterEach;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Disabled;
|
import org.junit.jupiter.api.Disabled;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -88,7 +89,7 @@ class BookDropServiceTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private FileMovingHelper fileMovingHelper;
|
private FileMovingHelper fileMovingHelper;
|
||||||
@Mock
|
@Mock
|
||||||
private KoboAutoShelfService koboAutoShelfService;
|
private ApplicationEventPublisher eventPublisher;
|
||||||
@Mock
|
@Mock
|
||||||
private PlatformTransactionManager transactionManager;
|
private PlatformTransactionManager transactionManager;
|
||||||
|
|
||||||
|
|||||||
+50
-144
@@ -1,118 +1,49 @@
|
|||||||
package org.booklore.service.library;
|
package org.booklore.service.library;
|
||||||
|
|
||||||
import org.booklore.model.FileProcessResult;
|
|
||||||
import org.booklore.model.dto.Book;
|
|
||||||
import org.booklore.model.dto.BookFile;
|
|
||||||
import org.booklore.model.dto.settings.LibraryFile;
|
import org.booklore.model.dto.settings.LibraryFile;
|
||||||
import org.booklore.model.entity.LibraryEntity;
|
import org.booklore.model.entity.LibraryEntity;
|
||||||
import org.booklore.model.entity.LibraryPathEntity;
|
import org.booklore.model.entity.LibraryPathEntity;
|
||||||
import org.booklore.model.enums.BookFileType;
|
import org.booklore.model.enums.BookFileType;
|
||||||
import org.booklore.model.enums.FileProcessStatus;
|
|
||||||
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.FileService;
|
|
||||||
import org.booklore.util.FileUtils;
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.MockedStatic;
|
|
||||||
import org.mockito.MockitoAnnotations;
|
import org.mockito.MockitoAnnotations;
|
||||||
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.ArgumentMatchers.anyLong;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.times;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
class FileAsBookProcessorTest {
|
class FileAsBookProcessorTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private BookEventBroadcaster bookEventBroadcaster;
|
private BookGroupProcessor bookGroupProcessor;
|
||||||
|
|
||||||
@Mock
|
|
||||||
private BookFileProcessorRegistry processorRegistry;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private KoboAutoShelfService koboAutoShelfService;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private BookRepository bookRepository;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private LibraryRepository libraryRepository;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private FileService fileService;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private MetadataExtractorFactory metadataExtractorFactory;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private AudiobookMetadataExtractor audiobookMetadataExtractor;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private BookFileProcessor bookFileProcessor;
|
|
||||||
|
|
||||||
private FileAsBookProcessor fileAsBookProcessor;
|
private FileAsBookProcessor fileAsBookProcessor;
|
||||||
|
|
||||||
private AutoCloseable mocks;
|
private AutoCloseable mocks;
|
||||||
private MockedStatic<FileFingerprint> fileFingerprintMock;
|
|
||||||
private MockedStatic<FileUtils> fileUtilsMock;
|
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
mocks = MockitoAnnotations.openMocks(this);
|
mocks = MockitoAnnotations.openMocks(this);
|
||||||
fileAsBookProcessor = new FileAsBookProcessor(
|
fileAsBookProcessor = new FileAsBookProcessor(bookGroupProcessor);
|
||||||
bookEventBroadcaster,
|
|
||||||
processorRegistry,
|
|
||||||
koboAutoShelfService,
|
|
||||||
bookRepository,
|
|
||||||
bookAdditionalFileRepository,
|
|
||||||
libraryRepository,
|
|
||||||
fileService,
|
|
||||||
metadataExtractorFactory,
|
|
||||||
audiobookMetadataExtractor
|
|
||||||
);
|
|
||||||
fileFingerprintMock = mockStatic(FileFingerprint.class);
|
|
||||||
fileFingerprintMock.when(() -> FileFingerprint.generateHash(any(Path.class))).thenReturn("testhash");
|
|
||||||
fileUtilsMock = mockStatic(FileUtils.class);
|
|
||||||
fileUtilsMock.when(() -> FileUtils.getFileSizeInKb(any(Path.class))).thenReturn(100L);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterEach
|
@AfterEach
|
||||||
void tearDown() throws Exception {
|
void tearDown() throws Exception {
|
||||||
if (fileFingerprintMock != null) fileFingerprintMock.close();
|
|
||||||
if (fileUtilsMock != null) fileUtilsMock.close();
|
|
||||||
if (mocks != null) mocks.close();
|
if (mocks != null) mocks.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
void staticMocksShouldWork() {
|
|
||||||
// Verify static mocks are working
|
|
||||||
Path testPath = Path.of("/test/path");
|
|
||||||
String hash = FileFingerprint.generateHash(testPath);
|
|
||||||
Long size = FileUtils.getFileSizeInKb(testPath);
|
|
||||||
assert hash.equals("testhash") : "Expected 'testhash' but got: " + hash;
|
|
||||||
assert size.equals(100L) : "Expected 100L but got: " + size;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void processLibraryFiles_shouldProcessDifferentNamedFilesSeparately() {
|
void processLibraryFiles_shouldProcessDifferentNamedFilesSeparately() {
|
||||||
LibraryEntity libraryEntity = new LibraryEntity();
|
LibraryEntity libraryEntity = new LibraryEntity();
|
||||||
|
libraryEntity.setId(1L);
|
||||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||||
libraryPathEntity.setId(1L);
|
libraryPathEntity.setId(1L);
|
||||||
libraryPathEntity.setPath("/library/path");
|
libraryPathEntity.setPath("/library/path");
|
||||||
@@ -133,77 +64,26 @@ class FileAsBookProcessorTest {
|
|||||||
.bookFileType(BookFileType.PDF)
|
.bookFileType(BookFileType.PDF)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
Book book1 = Book.builder().id(1L).primaryFile(BookFile.builder().fileName("book1.epub").bookType(BookFileType.EPUB).build()).build();
|
|
||||||
Book book2 = Book.builder().id(2L).primaryFile(BookFile.builder().fileName("book2.pdf").bookType(BookFileType.PDF).build()).build();
|
|
||||||
|
|
||||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
|
||||||
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
|
|
||||||
when(bookFileProcessor.processFile(file1)).thenReturn(new FileProcessResult(book1, FileProcessStatus.NEW));
|
|
||||||
when(bookFileProcessor.processFile(file2)).thenReturn(new FileProcessResult(book2, FileProcessStatus.NEW));
|
|
||||||
|
|
||||||
fileAsBookProcessor.processLibraryFiles(List.of(file1, file2), libraryEntity);
|
fileAsBookProcessor.processLibraryFiles(List.of(file1, file2), libraryEntity);
|
||||||
|
|
||||||
verify(bookEventBroadcaster, times(2)).broadcastBookAddEvent(any());
|
// Files with different base names are in separate groups
|
||||||
verify(bookFileProcessor, times(2)).processFile(any());
|
verify(bookGroupProcessor, times(2)).process(any(), anyLong());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void processLibraryFiles_shouldHandleEmptyList() {
|
void processLibraryFiles_shouldHandleEmptyList() {
|
||||||
LibraryEntity libraryEntity = new LibraryEntity();
|
LibraryEntity libraryEntity = new LibraryEntity();
|
||||||
|
libraryEntity.setId(1L);
|
||||||
|
|
||||||
fileAsBookProcessor.processLibraryFiles(new ArrayList<>(), libraryEntity);
|
fileAsBookProcessor.processLibraryFiles(new ArrayList<>(), libraryEntity);
|
||||||
|
|
||||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
verify(bookGroupProcessor, never()).process(any(), anyLong());
|
||||||
verify(processorRegistry, never()).getProcessorOrThrow(any());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void processLibraryFiles_shouldSkipFilesWithNullBookFileType() {
|
|
||||||
LibraryEntity libraryEntity = new LibraryEntity();
|
|
||||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
|
||||||
libraryPathEntity.setId(1L);
|
|
||||||
libraryPathEntity.setPath("/library/path");
|
|
||||||
|
|
||||||
LibraryFile invalidFile = LibraryFile.builder()
|
|
||||||
.libraryEntity(libraryEntity)
|
|
||||||
.libraryPathEntity(libraryPathEntity)
|
|
||||||
.fileName("document.txt")
|
|
||||||
.fileSubPath("docs")
|
|
||||||
.bookFileType(null)
|
|
||||||
.build();
|
|
||||||
|
|
||||||
fileAsBookProcessor.processLibraryFiles(List.of(invalidFile), libraryEntity);
|
|
||||||
|
|
||||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
|
||||||
verify(processorRegistry, never()).getProcessorOrThrow(any());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void processLibraryFiles_shouldNotBroadcastWhenProcessorReturnsNull() {
|
|
||||||
LibraryEntity libraryEntity = new LibraryEntity();
|
|
||||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
|
||||||
libraryPathEntity.setId(1L);
|
|
||||||
libraryPathEntity.setPath("/library/path");
|
|
||||||
|
|
||||||
LibraryFile file = LibraryFile.builder()
|
|
||||||
.libraryEntity(libraryEntity)
|
|
||||||
.libraryPathEntity(libraryPathEntity)
|
|
||||||
.fileName("book.epub")
|
|
||||||
.fileSubPath("books")
|
|
||||||
.bookFileType(BookFileType.EPUB)
|
|
||||||
.build();
|
|
||||||
|
|
||||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
|
||||||
when(bookFileProcessor.processFile(file)).thenReturn(null);
|
|
||||||
|
|
||||||
fileAsBookProcessor.processLibraryFiles(List.of(file), libraryEntity);
|
|
||||||
|
|
||||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void processLibraryFiles_shouldNotGroupFilesInDifferentDirectories() {
|
void processLibraryFiles_shouldNotGroupFilesInDifferentDirectories() {
|
||||||
LibraryEntity libraryEntity = new LibraryEntity();
|
LibraryEntity libraryEntity = new LibraryEntity();
|
||||||
|
libraryEntity.setId(1L);
|
||||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||||
libraryPathEntity.setId(1L);
|
libraryPathEntity.setId(1L);
|
||||||
libraryPathEntity.setPath("/library/path");
|
libraryPathEntity.setPath("/library/path");
|
||||||
@@ -224,18 +104,44 @@ class FileAsBookProcessorTest {
|
|||||||
.bookFileType(BookFileType.PDF)
|
.bookFileType(BookFileType.PDF)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
Book book1 = Book.builder().id(1L).primaryFile(BookFile.builder().fileName("book.epub").bookType(BookFileType.EPUB).build()).build();
|
|
||||||
Book book2 = Book.builder().id(2L).primaryFile(BookFile.builder().fileName("book.pdf").bookType(BookFileType.PDF).build()).build();
|
|
||||||
|
|
||||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
|
||||||
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
|
|
||||||
when(bookFileProcessor.processFile(file1)).thenReturn(new FileProcessResult(book1, FileProcessStatus.NEW));
|
|
||||||
when(bookFileProcessor.processFile(file2)).thenReturn(new FileProcessResult(book2, FileProcessStatus.NEW));
|
|
||||||
|
|
||||||
fileAsBookProcessor.processLibraryFiles(List.of(file1, file2), libraryEntity);
|
fileAsBookProcessor.processLibraryFiles(List.of(file1, file2), libraryEntity);
|
||||||
|
|
||||||
// Both should be processed as separate books
|
// Files in different directories should be processed separately
|
||||||
verify(bookFileProcessor, times(2)).processFile(any());
|
verify(bookGroupProcessor, times(2)).process(any(), anyLong());
|
||||||
verify(bookEventBroadcaster, times(2)).broadcastBookAddEvent(any());
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void processLibraryFilesGrouped_shouldCallProcessForEachGroup() {
|
||||||
|
LibraryEntity libraryEntity = new LibraryEntity();
|
||||||
|
libraryEntity.setId(1L);
|
||||||
|
|
||||||
|
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||||
|
libraryPathEntity.setId(1L);
|
||||||
|
libraryPathEntity.setPath("/library/path");
|
||||||
|
|
||||||
|
LibraryFile file1 = LibraryFile.builder()
|
||||||
|
.libraryEntity(libraryEntity)
|
||||||
|
.libraryPathEntity(libraryPathEntity)
|
||||||
|
.fileName("book1.epub")
|
||||||
|
.fileSubPath("books")
|
||||||
|
.bookFileType(BookFileType.EPUB)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
LibraryFile file2 = LibraryFile.builder()
|
||||||
|
.libraryEntity(libraryEntity)
|
||||||
|
.libraryPathEntity(libraryPathEntity)
|
||||||
|
.fileName("book2.pdf")
|
||||||
|
.fileSubPath("books")
|
||||||
|
.bookFileType(BookFileType.PDF)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
Map<String, List<LibraryFile>> groups = Map.of(
|
||||||
|
"group1", List.of(file1),
|
||||||
|
"group2", List.of(file2)
|
||||||
|
);
|
||||||
|
|
||||||
|
fileAsBookProcessor.processLibraryFilesGrouped(groups, libraryEntity);
|
||||||
|
|
||||||
|
verify(bookGroupProcessor, times(2)).process(any(), anyLong());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
@@ -49,6 +49,8 @@ class LibraryProcessingServiceRegressionTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private BookGroupingService bookGroupingService;
|
private BookGroupingService bookGroupingService;
|
||||||
@Mock
|
@Mock
|
||||||
|
private BookCoverGenerator bookCoverGenerator;
|
||||||
|
@Mock
|
||||||
private EntityManager entityManager;
|
private EntityManager entityManager;
|
||||||
|
|
||||||
private LibraryProcessingService libraryProcessingService;
|
private LibraryProcessingService libraryProcessingService;
|
||||||
@@ -65,6 +67,7 @@ class LibraryProcessingServiceRegressionTest {
|
|||||||
bookDeletionService,
|
bookDeletionService,
|
||||||
libraryFileHelper,
|
libraryFileHelper,
|
||||||
bookGroupingService,
|
bookGroupingService,
|
||||||
|
bookCoverGenerator,
|
||||||
entityManager
|
entityManager
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+3
@@ -52,6 +52,8 @@ class LibraryProcessingServiceTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private BookGroupingService bookGroupingService;
|
private BookGroupingService bookGroupingService;
|
||||||
@Mock
|
@Mock
|
||||||
|
private BookCoverGenerator bookCoverGenerator;
|
||||||
|
@Mock
|
||||||
private EntityManager entityManager;
|
private EntityManager entityManager;
|
||||||
|
|
||||||
private LibraryProcessingService libraryProcessingService;
|
private LibraryProcessingService libraryProcessingService;
|
||||||
@@ -68,6 +70,7 @@ class LibraryProcessingServiceTest {
|
|||||||
bookDeletionService,
|
bookDeletionService,
|
||||||
libraryFileHelper,
|
libraryFileHelper,
|
||||||
bookGroupingService,
|
bookGroupingService,
|
||||||
|
bookCoverGenerator,
|
||||||
entityManager
|
entityManager
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import org.booklore.model.entity.BookLoreUserEntity;
|
|||||||
import org.booklore.service.NotificationService;
|
import org.booklore.service.NotificationService;
|
||||||
import org.booklore.service.monitoring.LibraryWatchService;
|
import org.booklore.service.monitoring.LibraryWatchService;
|
||||||
import org.booklore.util.FileService;
|
import org.booklore.util.FileService;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -65,6 +66,8 @@ class LibraryServiceIconTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private AuditService auditService;
|
private AuditService auditService;
|
||||||
@Mock
|
@Mock
|
||||||
|
private ApplicationEventPublisher eventPublisher;
|
||||||
|
@Mock
|
||||||
private Executor taskExecutor;
|
private Executor taskExecutor;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
|
|||||||
+4
-6
@@ -9,11 +9,10 @@ import org.booklore.model.enums.LibraryOrganizationMode;
|
|||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.repository.LibraryRepository;
|
import org.booklore.repository.LibraryRepository;
|
||||||
import org.booklore.service.library.LibraryProcessingService;
|
import org.booklore.service.library.LibraryProcessingService;
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.service.library.LibraryScanListener;
|
||||||
import org.junit.jupiter.api.*;
|
import org.junit.jupiter.api.*;
|
||||||
import org.junit.jupiter.api.io.TempDir;
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.MockedStatic;
|
|
||||||
import org.mockito.MockitoAnnotations;
|
import org.mockito.MockitoAnnotations;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -24,8 +23,6 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.CountDownLatch;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.mockito.ArgumentMatchers.*;
|
import static org.mockito.ArgumentMatchers.*;
|
||||||
@@ -38,6 +35,7 @@ class LibraryFileEventProcessorTest {
|
|||||||
@Mock private BookFileTransactionalHandler bookFileTransactionalHandler;
|
@Mock private BookFileTransactionalHandler bookFileTransactionalHandler;
|
||||||
@Mock private BookFilePersistenceService bookFilePersistenceService;
|
@Mock private BookFilePersistenceService bookFilePersistenceService;
|
||||||
@Mock private LibraryProcessingService libraryProcessingService;
|
@Mock private LibraryProcessingService libraryProcessingService;
|
||||||
|
@Mock private LibraryScanListener libraryScanListener;
|
||||||
@Mock private PendingDeletionPool pendingDeletionPool;
|
@Mock private PendingDeletionPool pendingDeletionPool;
|
||||||
|
|
||||||
private LibraryFileEventProcessor processor;
|
private LibraryFileEventProcessor processor;
|
||||||
@@ -55,7 +53,7 @@ class LibraryFileEventProcessorTest {
|
|||||||
mocks = MockitoAnnotations.openMocks(this);
|
mocks = MockitoAnnotations.openMocks(this);
|
||||||
processor = new LibraryFileEventProcessor(
|
processor = new LibraryFileEventProcessor(
|
||||||
libraryRepository, bookRepository, bookFileTransactionalHandler,
|
libraryRepository, bookRepository, bookFileTransactionalHandler,
|
||||||
bookFilePersistenceService, libraryProcessingService, pendingDeletionPool);
|
bookFilePersistenceService, libraryProcessingService, libraryScanListener, pendingDeletionPool);
|
||||||
|
|
||||||
libraryPath = new LibraryPathEntity();
|
libraryPath = new LibraryPathEntity();
|
||||||
libraryPath.setId(1L);
|
libraryPath.setId(1L);
|
||||||
@@ -399,7 +397,7 @@ class LibraryFileEventProcessorTest {
|
|||||||
// Reinitialize so tearDown's shutdown doesn't fail
|
// Reinitialize so tearDown's shutdown doesn't fail
|
||||||
processor = new LibraryFileEventProcessor(
|
processor = new LibraryFileEventProcessor(
|
||||||
libraryRepository, bookRepository, bookFileTransactionalHandler,
|
libraryRepository, bookRepository, bookFileTransactionalHandler,
|
||||||
bookFilePersistenceService, libraryProcessingService, pendingDeletionPool);
|
bookFilePersistenceService, libraryProcessingService, libraryScanListener, pendingDeletionPool);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user