Book additional files support library (3/3) (#872)
* feat(api/model): add new entity BookAdditionalFileEntity * feat(api/db): add book additional file repository * feat(api/db): add migration * test(api/db): add book additional file repository test * test(api/db): add book additional file repository tests for hash uniqueness * feat(api/domain): add support to additional file model * feat(api): add additional files controller * refactor(api): move addAdditionalFile to FileUploadService as uploadAdditionalFile method * feat(service): search book by additional file * feat(services): process deleted additional files with ability to promote alternative formats to book instead of deleting them * refactor(util): use common code to resolve patter for entity and domain object * feat(service): move additional files * test(service): test move additional files along with book itself * feat(ui/domain): add alternativeFormats and supplementaryFiles to book model * feat(ui/domain): add download additional file method to book service * refactor(api/domain): extract FileInfo interface with common fields Allow to share the same interface thet is implemented by AdditionFile and Book * feat(ui): show multiple download options * feat(ui/domain): add delete additional file method to book service * feat(ui): add delete additional file ui * feat(ui): add additional-file-uploader.component * feat(ui/domain): add uploadAdditionalFile to the service * feat(ui): add Upload File menu item * feat(ui): show supplementary files in download menu item * feat(ui): show supplementary files in delete file menu item * feat(ui): book card allow to select single file to download or delete * feat(api/domain): add scan mode and default book format to the library * feat(ui): select scan mode and default book format * feat(api): create/update library settings * refactor(services): get processor based on scan mode * feat(services): read all files if processor supports supplimentary files * fix(services): detectNewBookPaths should check additional files as well * feat(services): implement folder as book file processor * test(service): add tests for FolderAsBookFileProcessor * feat(services): allow follow links for search library files * test(library): add tests for folder as book file processor * refactor(library): use Path instead of String for directory path * feat(library): sort directories before processing * feat(library): reuse library file book type * fix(library): do not add additional format if it is used in another book * test(library): test same hashes files * refactor(library): simplify FolderAsBookFileProcessor * test(library): add test with deep folder structure * test(library): add additional files to existing book --------- Co-authored-by: Aditya Chandel <8075870+adityachandelgit@users.noreply.github.com>
This commit is contained in:
co-authored by
Aditya Chandel
parent
f725ececf5
commit
694ee11540
@@ -1,5 +1,7 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -17,5 +19,7 @@ public class Library {
|
||||
private String fileNamingPattern;
|
||||
private boolean watch;
|
||||
private List<LibraryPath> paths;
|
||||
private LibraryScanMode scanMode;
|
||||
private BookFileType defaultBookFormat;
|
||||
}
|
||||
|
||||
|
||||
+4
@@ -1,6 +1,8 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.LibraryPath;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
@@ -20,4 +22,6 @@ public class CreateLibraryRequest {
|
||||
@NotEmpty
|
||||
private List<LibraryPath> paths;
|
||||
private boolean watch;
|
||||
private LibraryScanMode scanMode;
|
||||
private BookFileType defaultBookFormat;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.convertor.SortConverter;
|
||||
import com.adityachandel.booklore.model.dto.Sort;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@@ -40,4 +42,12 @@ public class LibraryEntity {
|
||||
|
||||
@Column(name = "file_naming_pattern")
|
||||
private String fileNamingPattern;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "scan_mode", nullable = false)
|
||||
private LibraryScanMode scanMode = LibraryScanMode.FILE_AS_BOOK;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "default_book_format")
|
||||
private BookFileType defaultBookFormat;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum LibraryScanMode {
|
||||
FILE_AS_BOOK,
|
||||
FOLDER_AS_BOOK
|
||||
}
|
||||
+8
-1
@@ -18,14 +18,21 @@ import java.util.List;
|
||||
|
||||
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
@Slf4j
|
||||
public class FileAsBookProcessor implements LibraryFileProcessor {
|
||||
|
||||
|
||||
private final NotificationService notificationService;
|
||||
private final BookFileProcessorRegistry processorRegistry;
|
||||
|
||||
@Override
|
||||
public LibraryScanMode getScanMode() {
|
||||
return LibraryScanMode.FILE_AS_BOOK;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
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.BookAdditionalFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.AdditionalFileType;
|
||||
import com.adityachandel.booklore.model.enums.BookFileExtension;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
@Slf4j
|
||||
public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
private final NotificationService notificationService;
|
||||
private final BookFileProcessorRegistry bookFileProcessorRegistry;
|
||||
|
||||
@Override
|
||||
public LibraryScanMode getScanMode() {
|
||||
return LibraryScanMode.FOLDER_AS_BOOK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsSupplementaryFiles() {
|
||||
// This processor supports supplementary files, as it processes all files in the folder.
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
// Group files by their directory path
|
||||
Map<Path, List<LibraryFile>> filesByDirectory = libraryFiles.stream()
|
||||
.collect(Collectors.groupingBy(libraryFile -> libraryFile.getFullPath().getParent()));
|
||||
|
||||
log.info("Processing {} directories with {} total files for library: {}",
|
||||
filesByDirectory.size(), libraryFiles.size(), libraryEntity.getName());
|
||||
|
||||
// Process each directory
|
||||
var sortedDirectories = filesByDirectory.entrySet()
|
||||
.stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.toList();
|
||||
for (Map.Entry<Path, List<LibraryFile>> entry : sortedDirectories) {
|
||||
Path directoryPath = entry.getKey();
|
||||
List<LibraryFile> filesInDirectory = entry.getValue();
|
||||
|
||||
log.debug("Processing directory: {} with {} files", directoryPath, filesInDirectory.size());
|
||||
processDirectory(directoryPath, filesInDirectory, libraryEntity);
|
||||
}
|
||||
}
|
||||
|
||||
private void processDirectory(Path directoryPath, List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
|
||||
var bookCreationResult = getOrCreateBookInDirectory(directoryPath, filesInDirectory, libraryEntity);
|
||||
if (bookCreationResult.bookEntity.isEmpty()) {
|
||||
log.warn("No book created for directory: {}", directoryPath);
|
||||
return;
|
||||
}
|
||||
|
||||
processAdditionalFiles(bookCreationResult.bookEntity.get(), bookCreationResult.remainingFiles);
|
||||
}
|
||||
|
||||
private GetOrCreateBookResult getOrCreateBookInDirectory(Path directoryPath, List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
|
||||
var existingBook = findExistingBookInDirectory(directoryPath, libraryEntity);
|
||||
if (existingBook.isPresent()) {
|
||||
log.debug("Found existing book in directory {}: {}", directoryPath, existingBook.get().getFileName());
|
||||
return new GetOrCreateBookResult(existingBook, filesInDirectory);
|
||||
}
|
||||
|
||||
// No existing book, check parent directories
|
||||
Optional<BookEntity> parentBook = findBookInParentDirectories(directoryPath, libraryEntity);
|
||||
if (parentBook.isPresent()) {
|
||||
log.debug("Found parent book for directory {}: {}", directoryPath, parentBook.get().getFileName());
|
||||
return new GetOrCreateBookResult(parentBook, filesInDirectory);
|
||||
}
|
||||
|
||||
log.debug("No existing book found, creating new book from directory: {}", directoryPath);
|
||||
Optional<CreateBookResult> newBook = createNewBookFromDirectory(directoryPath, filesInDirectory, libraryEntity);
|
||||
if (newBook.isPresent()) {
|
||||
log.info("Created new book: {}", newBook.get().bookEntity.getFileName());
|
||||
var remainingFiles = filesInDirectory.stream()
|
||||
.filter(file -> !file.equals(newBook.get().libraryFile))
|
||||
.toList();
|
||||
return new GetOrCreateBookResult(Optional.of(newBook.get().bookEntity), remainingFiles);
|
||||
} else {
|
||||
log.warn("Failed to create book from directory: {}", directoryPath);
|
||||
return new GetOrCreateBookResult(Optional.empty(), filesInDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<BookEntity> findExistingBookInDirectory(Path directoryPath, LibraryEntity libraryEntity) {
|
||||
// Find books in all library paths for this library
|
||||
return libraryEntity.getLibraryPaths().stream()
|
||||
.flatMap(libPath -> {
|
||||
String filesSearchPath = Path.of(libPath.getPath())
|
||||
.relativize(directoryPath)
|
||||
.toString()
|
||||
.replace("\\", "/");
|
||||
return bookRepository
|
||||
.findAllByLibraryPathIdAndFileSubPathStartingWith(libPath.getId(), filesSearchPath)
|
||||
.stream();
|
||||
})
|
||||
.filter(book -> book.getFullFilePath().getParent().equals(directoryPath))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private Optional<BookEntity> findBookInParentDirectories(Path directoryPath, LibraryEntity libraryEntity) {
|
||||
Path parent = directoryPath.getParent();
|
||||
LibraryPathEntity directoryLibraryPathEntity = libraryEntity.getLibraryPaths().stream()
|
||||
.filter(libPath -> directoryPath.startsWith(libPath.getPath()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException("No library path found for directory: " + directoryPath));
|
||||
Path directoryLibraryPath = Path.of(directoryLibraryPathEntity.getPath());
|
||||
|
||||
while (parent != null) {
|
||||
final String parentPath = directoryLibraryPath
|
||||
.relativize(parent)
|
||||
.toString()
|
||||
.replace("\\", "/");
|
||||
|
||||
Optional<BookEntity> parentBook =
|
||||
bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(
|
||||
directoryLibraryPathEntity.getId(), parentPath).stream()
|
||||
.filter(book -> book.getFileSubPath().equals(parentPath))
|
||||
.findFirst();
|
||||
if (parentBook.isPresent()) {
|
||||
return parentBook;
|
||||
}
|
||||
parent = parent.getParent();
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private Optional<CreateBookResult> createNewBookFromDirectory(Path directoryPath, List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
|
||||
// Find the best candidate for the main book file
|
||||
Optional<LibraryFile> mainBookFile = findBestMainBookFile(filesInDirectory, libraryEntity);
|
||||
|
||||
if (mainBookFile.isEmpty()) {
|
||||
log.debug("No suitable book file found in directory: {}", directoryPath);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
LibraryFile bookFile = mainBookFile.get();
|
||||
|
||||
try {
|
||||
log.info("Creating new book from file: {}", bookFile.getFileName());
|
||||
|
||||
// Create the main book
|
||||
BookFileProcessor processor = bookFileProcessorRegistry.getProcessorOrThrow(bookFile.getBookFileType());
|
||||
Book book = processor.processFile(bookFile);
|
||||
|
||||
if (book != null) {
|
||||
// Send notifications
|
||||
notificationService.sendMessage(
|
||||
com.adityachandel.booklore.model.websocket.Topic.BOOK_ADD,
|
||||
book
|
||||
);
|
||||
notificationService.sendMessage(
|
||||
com.adityachandel.booklore.model.websocket.Topic.LOG,
|
||||
com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification(
|
||||
"Book added: " + book.getFileName()
|
||||
)
|
||||
);
|
||||
|
||||
// Find the created book entity
|
||||
BookEntity bookEntity = bookRepository.getReferenceById(book.getId());
|
||||
if (bookEntity.getFullFilePath().equals(bookFile.getFullPath())) {
|
||||
log.info("Successfully created new book: {}", bookEntity.getFileName());
|
||||
} else {
|
||||
log.warn("Found duplicate book with different path: {} vs {}",
|
||||
bookEntity.getFullFilePath(), bookFile.getFullPath());
|
||||
}
|
||||
|
||||
return Optional.of(new CreateBookResult(bookEntity, bookFile));
|
||||
} else {
|
||||
log.warn("Book processor returned null for file: {}", bookFile.getFileName());
|
||||
|
||||
notificationService.sendMessage(
|
||||
com.adityachandel.booklore.model.websocket.Topic.LOG,
|
||||
com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification(
|
||||
"Failed to create book from file: " + bookFile.getFileName()
|
||||
)
|
||||
);
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error processing book file {}: {}", bookFile.getFileName(), e.getMessage(), e);
|
||||
|
||||
notificationService.sendMessage(
|
||||
com.adityachandel.booklore.model.websocket.Topic.LOG,
|
||||
com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification(
|
||||
"Error processing book file: " + bookFile.getFileName() + " - " + e.getMessage()
|
||||
)
|
||||
);
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<LibraryFile> findBestMainBookFile(List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
|
||||
var defaultBookFormat = libraryEntity.getDefaultBookFormat();
|
||||
return filesInDirectory.stream()
|
||||
.filter(f -> f.getBookFileType() != null)
|
||||
.min(Comparator.comparingInt(f -> {
|
||||
BookFileType bookFileType = f.getBookFileType();
|
||||
return bookFileType == defaultBookFormat
|
||||
? -1 // Prefer the default format
|
||||
: bookFileType.ordinal();
|
||||
}));
|
||||
}
|
||||
|
||||
private void processAdditionalFiles(BookEntity existingBook, List<LibraryFile> filesInDirectory) {
|
||||
for (LibraryFile file : filesInDirectory) {
|
||||
Optional<BookFileExtension> extension = BookFileExtension.fromFileName(file.getFileName());
|
||||
AdditionalFileType fileType = extension.isPresent() ?
|
||||
AdditionalFileType.ALTERNATIVE_FORMAT : AdditionalFileType.SUPPLEMENTARY;
|
||||
|
||||
createAdditionalFileIfNotExists(existingBook, file, fileType);
|
||||
}
|
||||
}
|
||||
|
||||
private void createAdditionalFileIfNotExists(BookEntity bookEntity, LibraryFile file, AdditionalFileType fileType) {
|
||||
// Check if an additional file already exists
|
||||
Optional<BookAdditionalFileEntity> existingFile = bookAdditionalFileRepository
|
||||
.findByLibraryPath_IdAndFileSubPathAndFileName(
|
||||
file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName());
|
||||
|
||||
if (existingFile.isPresent()) {
|
||||
log.debug("Additional file already exists: {}", file.getFileName());
|
||||
return;
|
||||
}
|
||||
|
||||
// Create a new additional file
|
||||
String hash = FileFingerprint.generateHash(file.getFullPath());
|
||||
BookAdditionalFileEntity additionalFile = BookAdditionalFileEntity.builder()
|
||||
.book(bookEntity)
|
||||
.fileName(file.getFileName())
|
||||
.fileSubPath(file.getFileSubPath())
|
||||
.additionalFileType(fileType)
|
||||
.fileSizeKb(FileUtils.getFileSizeInKb(file.getFullPath()))
|
||||
.initialHash(hash)
|
||||
.currentHash(hash)
|
||||
.addedOn(java.time.Instant.now())
|
||||
.build();
|
||||
|
||||
try {
|
||||
log.debug("Creating additional file: {} (type: {})", file.getFileName(), fileType);
|
||||
bookAdditionalFileRepository.save(additionalFile);
|
||||
|
||||
log.debug("Successfully created additional file: {}", file.getFileName());
|
||||
} catch (Exception e) {
|
||||
// Remove an additional file from the book entity if its creation fails
|
||||
bookEntity.getAdditionalFiles().removeIf(a -> a.equals(additionalFile));
|
||||
|
||||
log.error("Error creating additional file {}: {}", file.getFileName(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public record GetOrCreateBookResult(Optional<BookEntity> bookEntity, List<LibraryFile> remainingFiles) {}
|
||||
|
||||
public record CreateBookResult(BookEntity bookEntity, LibraryFile libraryFile) {}
|
||||
|
||||
}
|
||||
+12
@@ -5,6 +5,18 @@ import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
|
||||
public interface LibraryFileProcessor {
|
||||
LibraryScanMode getScanMode();
|
||||
void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity);
|
||||
|
||||
/**
|
||||
* Indicates whether this processor supports supplementary files (any file type)
|
||||
* in addition to book files.
|
||||
* @return true if supplementary files are supported, false otherwise
|
||||
*/
|
||||
default boolean supportsSupplementaryFiles() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+14
-6
@@ -1,17 +1,25 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import lombok.AllArgsConstructor;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
// Removed unused imports
|
||||
@AllArgsConstructor
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class LibraryFileProcessorRegistry {
|
||||
|
||||
private final FileAsBookProcessor fileAsBookProcessor;
|
||||
private final Map<LibraryScanMode, LibraryFileProcessor> processorMap;
|
||||
|
||||
public LibraryFileProcessor getProcessor(LibraryEntity library) {
|
||||
return fileAsBookProcessor;
|
||||
public LibraryFileProcessorRegistry(List<LibraryFileProcessor> processors) {
|
||||
this.processorMap = processors.stream()
|
||||
.collect(Collectors.toMap(LibraryFileProcessor::getScanMode, Function.identity()));
|
||||
}
|
||||
|
||||
public LibraryFileProcessor getProcessor(LibraryEntity libraryEntity) {
|
||||
return processorMap.get(libraryEntity.getScanMode());
|
||||
}
|
||||
}
|
||||
|
||||
+36
-19
@@ -23,6 +23,7 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileVisitOption;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
@@ -49,8 +50,8 @@ public class LibraryProcessingService {
|
||||
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<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity);
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity, processor);
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing library: " + libraryEntity.getName()));
|
||||
}
|
||||
@@ -59,7 +60,8 @@ 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()));
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity);
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity, processor);
|
||||
List<Long> additionalFileIds = detectDeletedAdditionalFiles(libraryFiles, libraryEntity);
|
||||
if (!additionalFileIds.isEmpty()) {
|
||||
log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName());
|
||||
@@ -71,7 +73,6 @@ public class LibraryProcessingService {
|
||||
processDeletedLibraryFiles(bookIds, libraryFiles);
|
||||
}
|
||||
restoreDeletedBooks(libraryFiles);
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity);
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
|
||||
}
|
||||
@@ -111,7 +112,7 @@ public class LibraryProcessingService {
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
}
|
||||
|
||||
public static List<Long> detectDeletedBookIds(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
protected static List<Long> detectDeletedBookIds(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
Set<Path> currentFullPaths = libraryFiles.stream()
|
||||
.map(LibraryFile::getFullPath)
|
||||
.collect(Collectors.toSet());
|
||||
@@ -123,16 +124,25 @@ public class LibraryProcessingService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
protected List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
Set<Path> existingFullPaths = libraryEntity.getBookEntities().stream()
|
||||
.map(BookEntity::getFullFilePath)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// Also collect paths from additional files using repository method
|
||||
Set<Path> additionalFilePaths = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId()).stream()
|
||||
.map(BookAdditionalFileEntity::getFullFilePath)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// Combine both sets of existing paths
|
||||
existingFullPaths.addAll(additionalFilePaths);
|
||||
|
||||
return libraryFiles.stream()
|
||||
.filter(file -> !existingFullPaths.contains(file.getFullPath()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Long> detectDeletedAdditionalFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
protected List<Long> detectDeletedAdditionalFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
// Create a set of current file names for quick lookup
|
||||
Set<String> currentFileNames = libraryFiles.stream()
|
||||
.map(LibraryFile::getFileName)
|
||||
@@ -264,29 +274,36 @@ public class LibraryProcessingService {
|
||||
}
|
||||
|
||||
|
||||
private List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
|
||||
private List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
List<LibraryFile> allFiles = new ArrayList<>();
|
||||
for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
|
||||
allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity));
|
||||
allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity, processor));
|
||||
}
|
||||
return allFiles;
|
||||
}
|
||||
|
||||
private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException {
|
||||
private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
Path libraryPath = Path.of(pathEntity.getPath());
|
||||
try (Stream<Path> stream = Files.walk(libraryPath)) {
|
||||
boolean supportsSupplementaryFiles = processor.supportsSupplementaryFiles();
|
||||
|
||||
try (Stream<Path> stream = Files.walk(libraryPath, FileVisitOption.FOLLOW_LINKS)) {
|
||||
return stream.filter(Files::isRegularFile)
|
||||
.map(fullPath -> {
|
||||
String fileName = fullPath.getFileName().toString();
|
||||
return BookFileExtension.fromFileName(fileName)
|
||||
.map(ext -> LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), fullPath))
|
||||
.fileName(fileName)
|
||||
.bookFileType(ext.getType())
|
||||
.build())
|
||||
.orElse(null);
|
||||
Optional<BookFileExtension> bookExtension = BookFileExtension.fromFileName(fileName);
|
||||
|
||||
if (bookExtension.isEmpty() && !supportsSupplementaryFiles) {
|
||||
// Skip files that are not recognized book files and supplementary files are not supported
|
||||
return null;
|
||||
}
|
||||
|
||||
return LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), fullPath))
|
||||
.fileName(fileName)
|
||||
.bookFileType(bookExtension.map(BookFileExtension::getType).orElse(null))
|
||||
.build();
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.filter(file -> !file.getFileName().startsWith("."))
|
||||
|
||||
+7
@@ -13,6 +13,7 @@ import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryPathRepository;
|
||||
@@ -72,6 +73,10 @@ public class LibraryService {
|
||||
library.setName(request.getName());
|
||||
library.setIcon(request.getIcon());
|
||||
library.setWatch(request.isWatch());
|
||||
if (request.getScanMode() != null) {
|
||||
library.setScanMode(request.getScanMode());
|
||||
}
|
||||
library.setDefaultBookFormat(request.getDefaultBookFormat());
|
||||
|
||||
Set<String> currentPaths = library.getLibraryPaths().stream()
|
||||
.map(LibraryPathEntity::getPath)
|
||||
@@ -148,6 +153,8 @@ public class LibraryService {
|
||||
)
|
||||
.icon(request.getIcon())
|
||||
.watch(request.isWatch())
|
||||
.scanMode(request.getScanMode() != null ? request.getScanMode() : LibraryScanMode.FILE_AS_BOOK)
|
||||
.defaultBookFormat(request.getDefaultBookFormat())
|
||||
.build();
|
||||
|
||||
libraryEntity = libraryRepository.save(libraryEntity);
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE library
|
||||
ADD COLUMN IF NOT EXISTS scan_mode VARCHAR(20) NOT NULL DEFAULT 'FILE_AS_BOOK',
|
||||
ADD COLUMN IF NOT EXISTS default_book_format VARCHAR(10) NULL;
|
||||
Reference in New Issue
Block a user