diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java index 0d9edeef0..505e842a7 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java @@ -45,9 +45,7 @@ public class BookDropService { private final NotificationService notificationService; private final MetadataRefreshService metadataRefreshService; private final BookdropNotificationService bookdropNotificationService; - private final PdfProcessor pdfProcessor; - private final EpubProcessor epubProcessor; - private final CbxProcessor cbxProcessor; + private final BookFileProcessorRegistry processorRegistry; private final AppProperties appProperties; public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) { @@ -169,11 +167,8 @@ public class BookDropService { .fileName(fileName) .build(); - return switch (type) { - case PDF -> pdfProcessor.processFile(libraryFile); - case EPUB -> epubProcessor.processFile(libraryFile); - case CBX -> cbxProcessor.processFile(libraryFile); - }; + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type); + return processor.processFile(libraryFile); } public void discardAllFiles() { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/BookFileProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/BookFileProcessor.java index 7a2cb394a..fb6dfa094 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/BookFileProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/BookFileProcessor.java @@ -3,8 +3,12 @@ package com.adityachandel.booklore.service.fileprocessor; import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.settings.LibraryFile; import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.enums.BookFileType; + +import java.util.List; public interface BookFileProcessor { + List getSupportedTypes(); Book processFile(LibraryFile libraryFile); boolean generateCover(BookEntity bookEntity); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/BookFileProcessorRegistry.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/BookFileProcessorRegistry.java new file mode 100644 index 000000000..027fbb997 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/BookFileProcessorRegistry.java @@ -0,0 +1,44 @@ +package com.adityachandel.booklore.service.fileprocessor; + +import com.adityachandel.booklore.model.enums.BookFileType; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Component +@Slf4j +public class BookFileProcessorRegistry { + + private final Map processorMap; + + public BookFileProcessorRegistry(List processors) { + this.processorMap = new EnumMap<>(BookFileType.class); + initializeProcessorMap(processors); + } + + private void initializeProcessorMap(List processors) { + for (BookFileProcessor processor : processors) { + List supportedTypes = processor.getSupportedTypes(); + for (BookFileType type : supportedTypes) { + processorMap.put(type, processor); + log.debug("Registered {} for type: {}", processor.getClass().getSimpleName(), type); + } + } + log.info("Initialized BookFileProcessorRegistry with {} processors for {} types", + processors.size(), processorMap.size()); + } + + public Optional getProcessor(BookFileType type) { + return Optional.ofNullable(processorMap.get(type)); + } + + public BookFileProcessor getProcessorOrThrow(BookFileType type) { + return getProcessor(type) + .orElseThrow(() -> new IllegalArgumentException( + "No processor found for file type: " + type)); + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index 542c519a0..3e0b743dd 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -1,7 +1,6 @@ package com.adityachandel.booklore.service.fileprocessor; import com.adityachandel.booklore.mapper.BookMapper; -import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.settings.LibraryFile; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.enums.BookFileType; @@ -70,6 +69,11 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce return false; } + @Override + public List getSupportedTypes() { + return List.of(BookFileType.CBX); + } + private Optional extractImagesFromArchive(File file) { String name = file.getName().toLowerCase(); if (name.endsWith(".cbz")) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java index fc13a8c22..7664952c0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java @@ -21,6 +21,7 @@ import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.time.Instant; +import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -92,6 +93,11 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc } } + @Override + public List getSupportedTypes() { + return List.of(BookFileType.EPUB); + } + private void setBookMetadata(BookEntity bookEntity) { File bookFile = new File(bookEntity.getFullFilePath().toUri()); BookMetadata epubMetadata = epubMetadataExtractor.extractMetadata(bookFile); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java index d33908378..5a6a98892 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java @@ -23,6 +23,7 @@ import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.time.Instant; +import java.util.List; import static com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils.truncate; @@ -68,6 +69,11 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce } } + @Override + public List getSupportedTypes() { + return List.of(BookFileType.PDF); + } + private void extractAndSetMetadata(BookEntity bookEntity) { try { BookMetadata extracted = pdfMetadataExtractor.extractMetadata(new File(FileUtils.getBookFullPath(bookEntity))); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/FileAsBookProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/FileAsBookProcessor.java new file mode 100644 index 000000000..1cd534131 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/FileAsBookProcessor.java @@ -0,0 +1,55 @@ +package com.adityachandel.booklore.service.library; + +import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.model.enums.BookFileExtension; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.websocket.Topic; +import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; +import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification; + +@AllArgsConstructor +@Component +@Slf4j +public class FileAsBookProcessor implements LibraryFileProcessor { + + private final NotificationService notificationService; + private final BookFileProcessorRegistry processorRegistry; + + @Override + @Transactional + public void processLibraryFiles(List libraryFiles, LibraryEntity libraryEntity) { + for (LibraryFile libraryFile : libraryFiles) { + log.info("Processing file: {}", libraryFile.getFileName()); + Book book = processLibraryFile(libraryFile); + if (book != null) { + notificationService.sendMessage(Topic.BOOK_ADD, book); + notificationService.sendMessage(Topic.LOG, createLogNotification("Book added: " + book.getFileName())); + log.info("Processed file: {}", libraryFile.getFileName()); + } + } + } + + @Transactional + protected Book processLibraryFile(LibraryFile libraryFile) { + BookFileType type = libraryFile.getBookFileType(); + if (type == null) { + log.warn("Unsupported file type for file: {}", libraryFile.getFileName()); + return null; + } + + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type); + return processor.processFile(libraryFile); + } + +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessor.java new file mode 100644 index 000000000..ee7fbdb17 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessor.java @@ -0,0 +1,10 @@ +package com.adityachandel.booklore.service.library; + +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.LibraryEntity; + +import java.util.List; + +public interface LibraryFileProcessor { + void processLibraryFiles(List libraryFiles, LibraryEntity libraryEntity); +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessorRegistry.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessorRegistry.java new file mode 100644 index 000000000..2463c1043 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryFileProcessorRegistry.java @@ -0,0 +1,17 @@ +package com.adityachandel.booklore.service.library; + +import com.adityachandel.booklore.model.entity.LibraryEntity; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Component; + +// Removed unused imports +@AllArgsConstructor +@Component +public class LibraryFileProcessorRegistry { + + private final FileAsBookProcessor fileAsBookProcessor; + + public LibraryFileProcessor getProcessor(LibraryEntity library) { + return fileAsBookProcessor; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java index 7f8c028ec..a5f7a5cce 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryProcessingService.java @@ -1,7 +1,6 @@ package com.adityachandel.booklore.service.library; import com.adityachandel.booklore.exception.ApiError; -import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.settings.LibraryFile; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; @@ -11,9 +10,6 @@ import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.service.NotificationService; -import com.adityachandel.booklore.service.fileprocessor.CbxProcessor; -import com.adityachandel.booklore.service.fileprocessor.EpubProcessor; -import com.adityachandel.booklore.service.fileprocessor.PdfProcessor; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileUtils; import lombok.AllArgsConstructor; @@ -38,18 +34,17 @@ public class LibraryProcessingService { private final LibraryRepository libraryRepository; private final NotificationService notificationService; - private final PdfProcessor pdfProcessor; - private final EpubProcessor epubProcessor; - private final CbxProcessor cbxProcessor; private final BookRepository bookRepository; private final FileService fileService; + private final LibraryFileProcessorRegistry fileProcessorRegistry; @Transactional public void processLibrary(long libraryId) throws IOException { LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing library: " + libraryEntity.getName())); List libraryFiles = getLibraryFiles(libraryEntity); - processLibraryFiles(libraryFiles); + LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity); + processor.processLibraryFiles(libraryFiles, libraryEntity); notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing library: " + libraryEntity.getName())); } @@ -57,29 +52,36 @@ public class LibraryProcessingService { public void rescanLibrary(long libraryId) throws IOException { LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName())); - deleteRemovedBooks(detectDeletedBookIds(libraryEntity)); - processLibraryFiles(detectNewBookPaths(libraryEntity)); + List libraryFiles = getLibraryFiles(libraryEntity); + deleteRemovedBooks(detectDeletedBookIds(libraryFiles, libraryEntity)); + LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity); + processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity); notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName())); } - public List detectDeletedBookIds(LibraryEntity libraryEntity) throws IOException { - Set currentFileNames = getLibraryFiles(libraryEntity).stream() - .map(LibraryFile::getFileName) + public void processLibraryFiles(List libraryFiles, LibraryEntity libraryEntity) { + LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity); + processor.processLibraryFiles(libraryFiles, libraryEntity); + } + + public static List detectDeletedBookIds(List libraryFiles, LibraryEntity libraryEntity) { + Set currentFullPaths = libraryFiles.stream() + .map(LibraryFile::getFullPath) .collect(Collectors.toSet()); return libraryEntity.getBookEntities().stream() .filter(book -> (book.getDeleted() == null || !book.getDeleted())) - .filter(book -> !currentFileNames.contains(book.getFileName())) + .filter(book -> !currentFullPaths.contains(book.getFullFilePath())) .map(BookEntity::getId) .collect(Collectors.toList()); } - public List detectNewBookPaths(LibraryEntity libraryEntity) throws IOException { - Set existingFileNames = libraryEntity.getBookEntities().stream() - .map(BookEntity::getFileName) + public static List detectNewBookPaths(List libraryFiles, LibraryEntity libraryEntity) { + Set existingFullPaths = libraryEntity.getBookEntities().stream() + .map(BookEntity::getFullFilePath) .collect(Collectors.toSet()); - return getLibraryFiles(libraryEntity).stream() - .filter(file -> !existingFileNames.contains(file.getFileName())) + return libraryFiles.stream() + .filter(file -> !existingFullPaths.contains(file.getFullPath())) .collect(Collectors.toList()); } @@ -118,27 +120,6 @@ public class LibraryProcessingService { } } - @Transactional - public void processLibraryFiles(List libraryFiles) { - for (LibraryFile libraryFile : libraryFiles) { - log.info("Processing file: {}", libraryFile.getFileName()); - Book book = processLibraryFile(libraryFile); - if (book != null) { - notificationService.sendMessage(Topic.BOOK_ADD, book); - notificationService.sendMessage(Topic.LOG, createLogNotification("Book added: " + book.getFileName())); - log.info("Processed file: {}", libraryFile.getFileName()); - } - } - } - - @Transactional - protected Book processLibraryFile(LibraryFile libraryFile) { - return switch (libraryFile.getBookFileType()) { - case PDF -> pdfProcessor.processFile(libraryFile); - case EPUB -> epubProcessor.processFile(libraryFile); - case CBX -> cbxProcessor.processFile(libraryFile); - }; - } private List getLibraryFiles(LibraryEntity libraryEntity) throws IOException { List allFiles = new ArrayList<>(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java index 22bb6340c..d65ca38e5 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java @@ -13,6 +13,7 @@ import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest; import com.adityachandel.booklore.model.dto.request.ToggleAllLockRequest; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; +import com.adityachandel.booklore.model.enums.BookFileExtension; import com.adityachandel.booklore.model.enums.Lock; import com.adityachandel.booklore.model.enums.MetadataProvider; import com.adityachandel.booklore.model.websocket.Topic; @@ -21,9 +22,8 @@ import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.BookQueryService; import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.appsettings.AppSettingService; -import com.adityachandel.booklore.service.fileprocessor.CbxProcessor; -import com.adityachandel.booklore.service.fileprocessor.EpubProcessor; -import com.adityachandel.booklore.service.fileprocessor.PdfProcessor; +import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; +import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupRestore; import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupRestoreFactory; import com.adityachandel.booklore.service.metadata.parser.BookParser; @@ -61,9 +61,7 @@ public class BookMetadataService { private final AppSettingService appSettingService; private final BookMetadataRepository bookMetadataRepository; private final FileService fileService; - private final PdfProcessor pdfProcessor; - private final EpubProcessor epubProcessor; - private final CbxProcessor cbxProcessor; + private final BookFileProcessorRegistry processorRegistry; private final BookQueryService bookQueryService; private final Map parserMap; private final MetadataBackupRestoreFactory metadataBackupRestoreFactory; @@ -196,12 +194,10 @@ public class BookMetadataService { String title = book.getMetadata().getTitle(); String message = progress + "Regenerating cover for: " + title; notificationService.sendMessage(Topic.LOG, createLogNotification(message)); - switch (book.getBookType()) { - case PDF -> pdfProcessor.generateCover(book); - case EPUB -> epubProcessor.generateCover(book); - case CBX -> cbxProcessor.generateCover(book); - default -> throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(book.getBookType()); - } + + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getBookType()); + processor.generateCover(book); + log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java index 853752730..6038d16c0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/upload/FileUploadService.java @@ -12,9 +12,8 @@ import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.appsettings.AppSettingService; -import com.adityachandel.booklore.service.fileprocessor.CbxProcessor; -import com.adityachandel.booklore.service.fileprocessor.EpubProcessor; -import com.adityachandel.booklore.service.fileprocessor.PdfProcessor; +import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; +import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor; import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor; import com.adityachandel.booklore.service.monitoring.MonitoringService; @@ -46,9 +45,7 @@ import java.util.Objects; public class FileUploadService { private final LibraryRepository libraryRepository; - private final PdfProcessor pdfProcessor; - private final EpubProcessor epubProcessor; - private final CbxProcessor cbxProcessor; + private final BookFileProcessorRegistry processorRegistry; private final NotificationService notificationService; private final AppSettingService appSettingService; private final PdfMetadataExtractor pdfMetadataExtractor; @@ -84,7 +81,7 @@ public class FileUploadService { try { file.transferTo(tempPath); - + setTemporaryFileOwnership(tempPath); BookFileExtension fileExt = BookFileExtension.fromFileName(file.getOriginalFilename()).orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension")); @@ -167,22 +164,19 @@ public class FileUploadService { } } - private Book processFile(String fileName, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile, BookFileType fileType) { + private Book processFile(String fileName, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile, BookFileType type) { String subPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), storageFile.toPath()); LibraryFile libraryFile = LibraryFile.builder() .libraryEntity(libraryEntity) .libraryPathEntity(libraryPathEntity) .fileSubPath(subPath) - .bookFileType(fileType) + .bookFileType(type) .fileName(fileName) .build(); - return switch (fileType) { - case PDF -> pdfProcessor.processFile(libraryFile); - case EPUB -> epubProcessor.processFile(libraryFile); - case CBX -> cbxProcessor.processFile(libraryFile); - }; + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type); + return processor.processFile(libraryFile); } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java index 023ddc127..57401aef5 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/watcher/BookFileTransactionalHandler.java @@ -62,7 +62,7 @@ public class BookFileTransactionalHandler { .orElseThrow(() -> new IllegalArgumentException("Unsupported book file type: " + fileName))) .build(); - libraryProcessingService.processLibraryFiles(List.of(libraryFile)); + libraryProcessingService.processLibraryFiles(List.of(libraryFile), libraryEntity); notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath)); log.info("[CREATE] Completed processing for file '{}'", filePath); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/BookDropServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/BookDropServiceTest.java index a9c480284..007a860b0 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/BookDropServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/BookDropServiceTest.java @@ -6,12 +6,11 @@ import com.adityachandel.booklore.repository.BookdropFileRepository; import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.service.bookdrop.BookDropService; import com.adityachandel.booklore.service.bookdrop.BookdropNotificationService; -import com.adityachandel.booklore.service.fileprocessor.CbxProcessor; -import com.adityachandel.booklore.service.fileprocessor.EpubProcessor; -import com.adityachandel.booklore.service.fileprocessor.PdfProcessor; +import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; import com.adityachandel.booklore.service.metadata.MetadataRefreshService; import com.adityachandel.booklore.service.bookdrop.BookdropMonitoringService; import com.adityachandel.booklore.service.monitoring.MonitoringService; +import com.adityachandel.booklore.service.NotificationService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.io.PathResource; @@ -35,9 +34,6 @@ class BookDropServiceTest { private NotificationService notificationService; private MetadataRefreshService metadataRefreshService; private BookdropNotificationService bookdropNotificationService; - private PdfProcessor pdfProcessor; - private EpubProcessor epubProcessor; - private CbxProcessor cbxProcessor; private AppProperties appProperties; private BookDropService bookDropService; @@ -52,9 +48,7 @@ class BookDropServiceTest { notificationService = mock(NotificationService.class); metadataRefreshService = mock(MetadataRefreshService.class); bookdropNotificationService = mock(BookdropNotificationService.class); - pdfProcessor = mock(PdfProcessor.class); - epubProcessor = mock(EpubProcessor.class); - cbxProcessor = mock(CbxProcessor.class); + BookFileProcessorRegistry processorRegistry = mock(BookFileProcessorRegistry.class); appProperties = mock(AppProperties.class); bookDropService = new BookDropService( @@ -62,7 +56,7 @@ class BookDropServiceTest { monitoringService, bookdropMonitoringService, notificationService, metadataRefreshService, bookdropNotificationService, - pdfProcessor, epubProcessor, cbxProcessor, + processorRegistry, appProperties ); } @@ -110,7 +104,7 @@ class BookDropServiceTest { Resource resource = bookDropService.getBookdropCover(bookdropId); assertThat(resource).isInstanceOf(PathResource.class); - assertThat(((PathResource) resource).getFile().getName()).isEqualTo(bookdropId + ".jpg"); + assertThat(resource.getFilename()).isEqualTo(bookdropId + ".jpg"); coverFile.delete(); } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FileAsBookProcessorTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FileAsBookProcessorTest.java new file mode 100644 index 000000000..be80067ce --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/library/FileAsBookProcessorTest.java @@ -0,0 +1,362 @@ +package com.adityachandel.booklore.service.library; + +import com.adityachandel.booklore.model.dto.Book; +import com.adityachandel.booklore.model.dto.settings.LibraryFile; +import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.websocket.LogNotification; +import com.adityachandel.booklore.model.websocket.Topic; +import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; +import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.*; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +class FileAsBookProcessorTest { + + @Mock + private NotificationService notificationService; + + @Mock + private BookFileProcessorRegistry processorRegistry; + + @Mock + private BookFileProcessor bookFileProcessor; + + @InjectMocks + private FileAsBookProcessor fileAsBookProcessor; + + @Captor + private ArgumentCaptor bookCaptor; + + private AutoCloseable mocks; + + @BeforeEach + void setUp() { + mocks = MockitoAnnotations.openMocks(this); + } + + @AfterEach + void tearDown() throws Exception { + if (mocks != null) { + mocks.close(); + } + } + + @Test + void processLibraryFiles_shouldProcessAllValidFiles() { + // Given + LibraryEntity libraryEntity = new LibraryEntity(); + LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setPath("/library/path"); + List libraryFiles = new ArrayList<>(); + + 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(); + + libraryFiles.add(file1); + libraryFiles.add(file2); + + Book book1 = Book.builder() + .fileName("book1.epub") + .title("Book 1") + .bookType(BookFileType.EPUB) + .build(); + + Book book2 = Book.builder() + .fileName("book2.pdf") + .title("Book 2") + .bookType(BookFileType.PDF) + .build(); + + when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor); + when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor); + when(bookFileProcessor.processFile(file1)).thenReturn(book1); + when(bookFileProcessor.processFile(file2)).thenReturn(book2); + + // When + fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); + + // Then + verify(notificationService, times(2)).sendMessage(eq(Topic.BOOK_ADD), bookCaptor.capture()); + verify(notificationService, times(2)).sendMessage(eq(Topic.LOG), any(LogNotification.class)); + + List capturedBooks = bookCaptor.getAllValues(); + assertThat(capturedBooks).hasSize(2); + assertThat(capturedBooks).containsExactly(book1, book2); + } + + @Test + void processLibraryFiles_shouldSkipFilesWithUnsupportedExtensions() { + // Given + LibraryEntity libraryEntity = new LibraryEntity(); + LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setPath("/library/path"); + List libraryFiles = new ArrayList<>(); + + LibraryFile validFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileName("book.epub") + .fileSubPath("books") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile invalidFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileName("document.txt") + .fileSubPath("docs") + .bookFileType(null) + .build(); + + libraryFiles.add(validFile); + libraryFiles.add(invalidFile); + + Book book = Book.builder() + .fileName("book.epub") + .title("Valid Book") + .bookType(BookFileType.EPUB) + .build(); + + when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor); + when(bookFileProcessor.processFile(validFile)).thenReturn(book); + + // When + fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); + + // Then + verify(notificationService, times(1)).sendMessage(eq(Topic.BOOK_ADD), eq(book)); + verify(notificationService, times(1)).sendMessage(eq(Topic.LOG), any(LogNotification.class)); + verify(processorRegistry, times(1)).getProcessorOrThrow(any()); + } + + @Test + void processLibraryFiles_shouldHandleEmptyList() { + // Given + LibraryEntity libraryEntity = new LibraryEntity(); + List libraryFiles = new ArrayList<>(); + + // When + fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); + + // Then + verify(notificationService, never()).sendMessage(any(Topic.class), any()); + verify(processorRegistry, never()).getProcessorOrThrow(any()); + } + + @Test + void processLibraryFile_shouldReturnNullForUnsupportedFileType() { + // Given + LibraryEntity libraryEntity = new LibraryEntity(); + LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setPath("/library/path"); + + LibraryFile libraryFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileName("document.txt") + .fileSubPath("docs") + .bookFileType(null) + .build(); + + // When + Book result = fileAsBookProcessor.processLibraryFile(libraryFile); + + // Then + assertThat(result).isNull(); + verify(processorRegistry, never()).getProcessorOrThrow(any()); + } + + @Test + void processLibraryFile_shouldProcessSupportedFileTypes() { + // Given + LibraryEntity libraryEntity = new LibraryEntity(); + LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setPath("/library/path"); + + LibraryFile libraryFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileName("book.epub") + .fileSubPath("books") + .bookFileType(BookFileType.EPUB) + .build(); + + Book expectedBook = Book.builder() + .fileName("book.epub") + .title("Test Book") + .bookType(BookFileType.EPUB) + .build(); + + when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor); + when(bookFileProcessor.processFile(libraryFile)).thenReturn(expectedBook); + + // When + Book result = fileAsBookProcessor.processLibraryFile(libraryFile); + + // Then + assertThat(result).isEqualTo(expectedBook); + verify(processorRegistry).getProcessorOrThrow(BookFileType.EPUB); + verify(bookFileProcessor).processFile(libraryFile); + } + + @Test + void processLibraryFile_shouldHandleNullReturnFromProcessor() { + // Given + LibraryEntity libraryEntity = new LibraryEntity(); + LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setPath("/library/path"); + + LibraryFile libraryFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileName("book.pdf") + .fileSubPath("books") + .bookFileType(BookFileType.PDF) + .build(); + + when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor); + when(bookFileProcessor.processFile(libraryFile)).thenReturn(null); + + // When + Book result = fileAsBookProcessor.processLibraryFile(libraryFile); + + // Then + assertThat(result).isNull(); + } + + @Test + void processLibraryFiles_shouldNotSendNotificationWhenProcessorReturnsNull() { + // Given + LibraryEntity libraryEntity = new LibraryEntity(); + LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setPath("/library/path"); + List libraryFiles = new ArrayList<>(); + + LibraryFile file = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileName("book.epub") + .fileSubPath("books") + .bookFileType(BookFileType.EPUB) + .build(); + + libraryFiles.add(file); + + when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor); + when(bookFileProcessor.processFile(file)).thenReturn(null); + + // When + fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); + + // Then + verify(notificationService, never()).sendMessage(any(Topic.class), any()); + } + + @Test + void processLibraryFiles_shouldProcessAllSupportedFileExtensions() { + // Given + LibraryEntity libraryEntity = new LibraryEntity(); + LibraryPathEntity libraryPathEntity = new LibraryPathEntity(); + libraryPathEntity.setPath("/library/path"); + List libraryFiles = new ArrayList<>(); + + LibraryFile epubFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileName("book.epub") + .fileSubPath("books") + .bookFileType(BookFileType.EPUB) + .build(); + + LibraryFile pdfFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileName("book.pdf") + .fileSubPath("books") + .bookFileType(BookFileType.PDF) + .build(); + + LibraryFile cbzFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileName("comic.cbz") + .fileSubPath("comics") + .bookFileType(BookFileType.CBX) + .build(); + + LibraryFile cbrFile = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(libraryPathEntity) + .fileName("comic.cbr") + .fileSubPath("comics") + .bookFileType(BookFileType.CBX) + .build(); + + libraryFiles.add(epubFile); + libraryFiles.add(pdfFile); + libraryFiles.add(cbzFile); + libraryFiles.add(cbrFile); + + Book epubBook = Book.builder() + .fileName("book.epub") + .bookType(BookFileType.EPUB) + .build(); + + Book pdfBook = Book.builder() + .fileName("book.pdf") + .bookType(BookFileType.PDF) + .build(); + + Book cbzBook = Book.builder() + .fileName("comic.cbz") + .bookType(BookFileType.CBX) + .build(); + + Book cbrBook = Book.builder() + .fileName("comic.cbr") + .bookType(BookFileType.CBX) + .build(); + + when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor); + when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor); + when(processorRegistry.getProcessorOrThrow(BookFileType.CBX)).thenReturn(bookFileProcessor); + + when(bookFileProcessor.processFile(epubFile)).thenReturn(epubBook); + when(bookFileProcessor.processFile(pdfFile)).thenReturn(pdfBook); + when(bookFileProcessor.processFile(cbzFile)).thenReturn(cbzBook); + when(bookFileProcessor.processFile(cbrFile)).thenReturn(cbrBook); + + // When + fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); + + // Then + verify(notificationService, times(4)).sendMessage(eq(Topic.BOOK_ADD), any(Book.class)); + verify(notificationService, times(4)).sendMessage(eq(Topic.LOG), any(LogNotification.class)); + } +} \ No newline at end of file