Fix database lockout caused by duplicate files in library (#1102)

This commit is contained in:
Aditya Chandel
2025-09-06 21:22:59 -06:00
committed by GitHub
parent c8e78d3bc8
commit 074d8d6e69
36 changed files with 1766 additions and 359 deletions
@@ -0,0 +1,15 @@
package com.adityachandel.booklore.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
@Builder
@Getter
@AllArgsConstructor
public class DuplicateFileInfo {
private final Long bookId;
private final String fileName;
private final String fullPath;
private final String hash;
}
@@ -0,0 +1,19 @@
package com.adityachandel.booklore.model;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.enums.FileProcessStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
@Builder
@Getter
@ToString
@AllArgsConstructor
public class FileProcessResult {
private final Book book;
private final FileProcessStatus status;
@Builder.Default
private final DuplicateFileInfo duplicate = null;
}
@@ -0,0 +1,20 @@
package com.adityachandel.booklore.model.dto;
import lombok.*;
import java.time.Instant;
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@Builder
public class DuplicateFileNotification {
private long libraryId;
private String libraryName;
private long fileId;
private String fileName;
private String fullPath;
private String hash;
private Instant timestamp;
}
@@ -21,6 +21,9 @@ public class LibraryFile {
private BookFileType bookFileType;
public Path getFullPath() {
if (fileSubPath == null || fileSubPath.isEmpty()) {
return Paths.get(libraryPathEntity.getPath(), fileName);
}
return Paths.get(libraryPathEntity.getPath(), fileSubPath, fileName);
}
}
@@ -0,0 +1,7 @@
package com.adityachandel.booklore.model.enums;
public enum FileProcessStatus {
NEW,
DUPLICATE,
UPDATED
}
@@ -12,6 +12,7 @@ public enum Topic {
BOOK_METADATA_BATCH_UPDATE("/queue/book-metadata-batch-update"),
BOOK_METADATA_BATCH_PROGRESS("/queue/book-metadata-batch-progress"),
BOOKDROP_FILE("/queue/bookdrop-file"),
DUPLICATE_FILE("/queue/duplicate-file"),
TASK("/queue/task"),
LOG("/queue/log");
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.bookdrop;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookdropFileMapper;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.BookdropFile;
@@ -180,7 +181,7 @@ public class BookDropService {
results.getTotalFiles());
return results;
} finally {
bookdropMonitoringService.resumeMonitoring();
}
@@ -283,15 +284,15 @@ public class BookDropService {
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
Book processedBook = processFile(targetFile.getName(), library, path, targetFile,
FileProcessResult fileProcessResult = processFile(targetFile.getName(), library, path, targetFile,
BookFileExtension.fromFileName(bookdropFile.getFileName())
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
.getType());
BookEntity bookEntity = bookRepository.findById(processedBook.getId())
BookEntity bookEntity = bookRepository.findById(fileProcessResult.getBook().getId())
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
notificationService.sendMessage(Topic.BOOK_ADD, processedBook);
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getStatus());
metadataRefreshService.updateBookMetadata(bookEntity, metadata, metadata.getThumbnailUrl() != null, false);
bookdropFileRepository.deleteById(bookdropFile.getId());
bookdropNotificationService.sendBookdropFileSummaryNotification();
@@ -333,7 +334,7 @@ public class BookDropService {
.build();
}
private Book processFile(String fileName, LibraryEntity library, LibraryPathEntity path, File file, BookFileType type) {
private FileProcessResult processFile(String fileName, LibraryEntity library, LibraryPathEntity path, File file, BookFileType type) {
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(library)
.libraryPathEntity(path)
@@ -21,13 +21,12 @@ public class BookEventBroadcaster {
public void broadcastBookAddEvent(Book book) {
Long libraryId = book.getLibraryId();
userService.getBookLoreUsers().stream()
.filter(u -> u.getPermissions().isAdmin() || u.getAssignedLibraries().stream()
.anyMatch(lib -> lib.getId().equals(libraryId)))
.forEach(u -> {
String username = u.getUsername();
messagingTemplate.convertAndSendToUser(username, Topic.BOOK_ADD.getPath(), book);
messagingTemplate.convertAndSendToUser(username, Topic.LOG.getPath(), createLogNotification("Book added: " + book.getFileName()));
log.debug("Sent BOOK_ADD and LOG notifications for '{}' to user '{}'", book.getFileName(), username);
});
.filter(u -> u.getPermissions().isAdmin() || u.getAssignedLibraries().stream()
.anyMatch(lib -> lib.getId().equals(libraryId)))
.forEach(u -> {
String username = u.getUsername();
messagingTemplate.convertAndSendToUser(username, Topic.BOOK_ADD.getPath(), book);
messagingTemplate.convertAndSendToUser(username, Topic.LOG.getPath(), createLogNotification("Book added: " + book.getFileName()));
});
}
}
@@ -1,20 +1,26 @@
package com.adityachandel.booklore.service.fileprocessor;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.DuplicateFileInfo;
import com.adityachandel.booklore.model.FileProcessResult;
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.FileProcessStatus;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookCreatorService;
import com.adityachandel.booklore.service.FileFingerprint;
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.util.FileService;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;
@Slf4j
@@ -26,8 +32,16 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
protected final BookMapper bookMapper;
protected final MetadataMatchService metadataMatchService;
protected final FileService fileService;
@PersistenceContext
private EntityManager entityManager;
protected AbstractFileProcessor(BookRepository bookRepository, BookAdditionalFileRepository bookAdditionalFileRepository, BookCreatorService bookCreatorService, BookMapper bookMapper, FileService fileService, MetadataMatchService metadataMatchService) {
protected AbstractFileProcessor(BookRepository bookRepository,
BookAdditionalFileRepository bookAdditionalFileRepository,
BookCreatorService bookCreatorService,
BookMapper bookMapper,
FileService fileService,
MetadataMatchService metadataMatchService) {
this.bookRepository = bookRepository;
this.bookAdditionalFileRepository = bookAdditionalFileRepository;
this.bookCreatorService = bookCreatorService;
@@ -38,34 +52,96 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public Book processFile(LibraryFile libraryFile) {
public FileProcessResult processFile(LibraryFile libraryFile) {
Path path = libraryFile.getFullPath();
String fileName = path.getFileName().toString();
String hash = FileFingerprint.generateHash(path);
Optional<Book> duplicate = fileService.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, bookRepository, bookAdditionalFileRepository, bookMapper);
if (duplicate.isPresent()) {
return handleDuplicate(duplicate.get(), libraryFile);
return handleDuplicate(duplicate.get(), libraryFile, hash);
}
Long libraryId = libraryFile.getLibraryEntity().getId();
return bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
.map(bookMapper::toBook)
.orElseGet(() -> createAndMapBook(libraryFile, hash));
.map(b -> new FileProcessResult(b, FileProcessStatus.DUPLICATE, createDuplicateInfo(b, libraryFile, hash)))
.orElseGet(() -> {
Book book = createAndMapBook(libraryFile, hash);
return new FileProcessResult(book, FileProcessStatus.NEW, null);
});
}
private Book handleDuplicate(Book bookDto, LibraryFile libraryFile) {
bookRepository.findById(bookDto.getId())
.ifPresent(entity -> {
entity.setFileSubPath(libraryFile.getFileSubPath());
entity.setFileName(libraryFile.getFileName());
entity.setLibraryPath(libraryFile.getLibraryPathEntity());
log.info("Duplicate file handled: bookId={} fileName='{}' libraryId={} subPath='{}'",
entity.getId(),
libraryFile.getFileName(),
libraryFile.getLibraryEntity().getId(),
libraryFile.getFileSubPath());
});
return bookDto;
private FileProcessResult handleDuplicate(Book bookDto, LibraryFile libraryFile, String hash) {
return bookRepository.findById(bookDto.getId())
.map(entity -> {
boolean sameHash = Objects.equals(entity.getCurrentHash(), hash);
boolean sameFileName = Objects.equals(entity.getFileName(), libraryFile.getFileName());
boolean sameSubPath = Objects.equals(entity.getFileSubPath(), libraryFile.getFileSubPath());
boolean sameLibraryPath = Objects.equals(entity.getLibraryPath(), libraryFile.getLibraryPathEntity());
if (sameHash && sameFileName && sameSubPath && sameLibraryPath) {
return new FileProcessResult(
bookDto,
FileProcessStatus.DUPLICATE,
createDuplicateInfo(bookDto, libraryFile, hash)
);
}
boolean folderChanged = !sameSubPath;
boolean updated = false;
if (!sameSubPath) {
entity.setFileSubPath(libraryFile.getFileSubPath());
updated = true;
}
if (!sameFileName) {
entity.setFileName(libraryFile.getFileName());
updated = true;
}
if (!sameLibraryPath) {
entity.setLibraryPath(libraryFile.getLibraryPathEntity());
updated = true;
}
entity.setCurrentHash(hash);
/*if (folderChanged) {
log.info("Duplicate file found in different folder: bookId={} oldSubPath='{}' newSubPath='{}'",
entity.getId(),
bookDto.getFileSubPath(),
libraryFile.getFileSubPath());
}*/
DuplicateFileInfo dupeInfo = createDuplicateInfo(bookMapper.toBook(entity), libraryFile, hash);
if (updated) {
/*log.info("Duplicate file updated: bookId={} fileName='{}' libraryId={} subPath='{}'",
entity.getId(),
entity.getFileName(),
entity.getLibraryPath().getLibrary().getId(),
entity.getFileSubPath());*/
entityManager.flush();
entityManager.detach(entity);
return new FileProcessResult(bookMapper.toBook(entity), FileProcessStatus.UPDATED, dupeInfo);
} else {
entityManager.detach(entity);
return new FileProcessResult(bookMapper.toBook(entity), FileProcessStatus.DUPLICATE, dupeInfo);
}
})
.orElse(new FileProcessResult(bookDto, FileProcessStatus.DUPLICATE, null));
}
private DuplicateFileInfo createDuplicateInfo(Book book, LibraryFile libraryFile, String hash) {
return new DuplicateFileInfo(
book.getId(),
libraryFile.getFileName(),
libraryFile.getFullPath().toString(),
hash
);
}
private Book createAndMapBook(LibraryFile libraryFile, String hash) {
@@ -77,4 +153,4 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
}
protected abstract BookEntity processNewFile(LibraryFile libraryFile);
}
}
@@ -1,6 +1,6 @@
package com.adityachandel.booklore.service.fileprocessor;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
@@ -9,6 +9,8 @@ import java.util.List;
public interface BookFileProcessor {
List<BookFileType> getSupportedTypes();
Book processFile(LibraryFile libraryFile);
FileProcessResult processFile(LibraryFile libraryFile);
boolean generateCover(BookEntity bookEntity);
}
@@ -0,0 +1,157 @@
package com.adityachandel.booklore.service.library;
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.enums.AdditionalFileType;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.util.FileService;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
@RequiredArgsConstructor
@Slf4j
public class BookDeletionService {
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final FileService fileService;
private final NotificationService notificationService;
@PersistenceContext
private final EntityManager entityManager;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void deleteRemovedAdditionalFiles(List<Long> additionalFileIds) {
if (additionalFileIds.isEmpty()) {
return;
}
List<BookAdditionalFileEntity> additionalFiles = bookAdditionalFileRepository.findAllById(additionalFileIds);
bookAdditionalFileRepository.deleteAll(additionalFiles);
entityManager.flush();
entityManager.clear();
log.info("Deleted {} additional files from database", additionalFileIds.size());
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void processDeletedLibraryFiles(List<Long> deletedBookIds, List<LibraryFile> libraryFiles) {
if (deletedBookIds.isEmpty()) {
return;
}
List<BookEntity> books = bookRepository.findAllById(deletedBookIds);
List<Long> booksToDelete = new ArrayList<>();
for (BookEntity book : books) {
if (!tryPromoteAlternativeFormatToBook(book, libraryFiles)) {
booksToDelete.add(book.getId());
}
}
entityManager.flush();
entityManager.clear();
if (!booksToDelete.isEmpty()) {
deleteRemovedBooks(booksToDelete);
}
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void deleteRemovedBooks(List<Long> bookIds) {
List<BookEntity> books = bookRepository.findAllById(bookIds);
for (BookEntity book : books) {
try {
deleteDirectoryRecursively(Path.of(fileService.getImagesFolder(book.getId())));
Path backupDir = Path.of(fileService.getBookMetadataBackupPath(book.getId()));
if (Files.exists(backupDir)) {
deleteDirectoryRecursively(backupDir);
}
} catch (Exception e) {
log.warn("Failed to clean up files for book ID {}: {}", book.getId(), e.getMessage());
}
}
bookRepository.deleteAll(books);
entityManager.flush();
entityManager.clear();
notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
if (bookIds.size() > 1) log.info("Books removed: {}", bookIds);
}
private boolean tryPromoteAlternativeFormatToBook(BookEntity book, List<LibraryFile> libraryFiles) {
List<BookAdditionalFileEntity> existingAlternativeFormats = findExistingAlternativeFormats(book, libraryFiles);
if (existingAlternativeFormats.isEmpty()) {
return false;
}
BookAdditionalFileEntity promotedFormat = existingAlternativeFormats.getFirst();
promoteAlternativeFormatToBook(book, promotedFormat);
bookAdditionalFileRepository.delete(promotedFormat);
log.info("Promoted alternative format {} to main book for book ID {}", promotedFormat.getFileName(), book.getId());
return true;
}
private List<BookAdditionalFileEntity> findExistingAlternativeFormats(BookEntity book, List<LibraryFile> libraryFiles) {
Set<String> currentFileNames = libraryFiles.stream()
.map(LibraryFile::getFileName)
.collect(Collectors.toSet());
if (book.getAdditionalFiles() == null) {
return Collections.emptyList();
}
return book.getAdditionalFiles().stream()
.filter(additionalFile -> AdditionalFileType.ALTERNATIVE_FORMAT.equals(additionalFile.getAdditionalFileType()))
.filter(additionalFile -> currentFileNames.contains(additionalFile.getFileName()))
.filter(additionalFile -> BookFileExtension.fromFileName(additionalFile.getFileName()).isPresent())
.collect(Collectors.toList());
}
private void promoteAlternativeFormatToBook(BookEntity book, BookAdditionalFileEntity alternativeFormat) {
book.setFileName(alternativeFormat.getFileName());
book.setFileSubPath(alternativeFormat.getFileSubPath());
BookFileExtension.fromFileName(alternativeFormat.getFileName())
.ifPresent(ext -> book.setBookType(ext.getType()));
book.setFileSizeKb(alternativeFormat.getFileSizeKb());
book.setCurrentHash(alternativeFormat.getCurrentHash());
book.setInitialHash(alternativeFormat.getInitialHash());
bookRepository.save(book);
}
private void deleteDirectoryRecursively(Path path) throws IOException {
if (Files.exists(path)) {
try (Stream<Path> walk = Files.walk(path)) {
walk.sorted(Comparator.reverseOrder()).forEach(p -> {
try {
Files.deleteIfExists(p);
} catch (IOException e) {
log.warn("Failed to delete file or directory: {}", p, e);
}
});
}
}
}
}
@@ -0,0 +1,61 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.NotificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Slf4j
public class BookRestorationService {
private final BookRepository bookRepository;
private final BookMapper bookMapper;
private final NotificationService notificationService;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void restoreDeletedBooks(List<LibraryFile> libraryFiles) {
if (libraryFiles.isEmpty()) return;
LibraryEntity libraryEntity = libraryFiles.getFirst().getLibraryEntity();
Set<Path> currentPaths = libraryFiles.stream()
.map(LibraryFile::getFullPath)
.collect(Collectors.toSet());
List<BookEntity> toRestore = libraryEntity.getBookEntities().stream()
.filter(book -> Boolean.TRUE.equals(book.getDeleted()))
.filter(book -> currentPaths.contains(book.getFullFilePath()))
.collect(Collectors.toList());
if (toRestore.isEmpty()) return;
toRestore.forEach(book -> {
book.setDeleted(false);
book.setDeletedAt(null);
book.setAddedOn(Instant.now());
notificationService.sendMessage(Topic.BOOK_ADD, bookMapper.toBookWithDescription(book, false));
});
bookRepository.saveAll(toRestore);
List<Long> restoredIds = toRestore.stream()
.map(BookEntity::getId)
.toList();
log.info("Restored {} books in library: {}", restoredIds.size(), libraryEntity.getName());
}
}
@@ -1,10 +1,13 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.DuplicateFileInfo;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.DuplicateFileNotification;
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.enums.FileProcessStatus;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
@@ -15,12 +18,9 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.List;
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
@AllArgsConstructor
@Component
@Slf4j
@@ -28,6 +28,7 @@ public class FileAsBookProcessor implements LibraryFileProcessor {
private final BookEventBroadcaster bookEventBroadcaster;
private final BookFileProcessorRegistry processorRegistry;
private final NotificationService notificationService;
@Override
public LibraryScanMode getScanMode() {
@@ -39,16 +40,40 @@ public class FileAsBookProcessor implements LibraryFileProcessor {
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
for (LibraryFile libraryFile : libraryFiles) {
log.info("Processing file: {}", libraryFile.getFileName());
Book book = processLibraryFile(libraryFile);
if (book != null) {
bookEventBroadcaster.broadcastBookAddEvent(book);
log.info("Processed file: {}", libraryFile.getFileName());
FileProcessResult result = processLibraryFile(libraryFile);
if (result != null) {
if (result.getDuplicate() != null) {
DuplicateFileInfo dupe = result.getDuplicate();
DuplicateFileNotification notification = DuplicateFileNotification.builder()
.libraryId(libraryEntity.getId())
.libraryName(libraryEntity.getName())
.fileId(dupe.getBookId())
.fileName(dupe.getFileName())
.fullPath(dupe.getFullPath())
.hash(dupe.getHash())
.timestamp(Instant.now())
.build();
log.info("Duplicate file detected: {}", notification);
notificationService.sendMessage(Topic.DUPLICATE_FILE, notification);
}
if (result.getStatus() != FileProcessStatus.DUPLICATE) {
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
log.info("Processed file: {}", libraryFile.getFileName());
}
}
}
log.info("Finished processing library '{}'", libraryEntity.getName());
}
@Transactional
protected Book processLibraryFile(LibraryFile libraryFile) {
protected FileProcessResult processLibraryFile(LibraryFile libraryFile) {
BookFileType type = libraryFile.getBookFileType();
if (type == null) {
log.warn("Unsupported file type for file: {}", libraryFile.getFileName());
@@ -1,6 +1,6 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
@@ -47,20 +47,17 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
@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())
@@ -91,7 +88,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
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());
@@ -113,7 +109,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
}
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())
@@ -157,7 +152,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
}
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()) {
@@ -170,20 +164,17 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
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);
FileProcessResult result = processor.processFile(bookFile);
if (book != null) {
bookEventBroadcaster.broadcastBookAddEvent(book);
if (result.getBook() != null) {
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
// Find the created book entity
BookEntity bookEntity = bookRepository.getReferenceById(book.getId());
BookEntity bookEntity = bookRepository.getReferenceById(result.getBook().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());
log.warn("Found duplicate book with different path: {} vs {}", bookEntity.getFullFilePath(), bookFile.getFullPath());
}
return Optional.of(new CreateBookResult(bookEntity, bookFile));
@@ -206,7 +197,7 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
.min(Comparator.comparingInt(f -> {
BookFileType bookFileType = f.getBookFileType();
return bookFileType == defaultBookFormat
? -1 // Prefer the default format
? -1
: bookFileType.ordinal();
}));
}
@@ -222,7 +213,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
}
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());
@@ -232,7 +222,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
return;
}
// Create a new additional file
String hash = FileFingerprint.generateHash(file.getFullPath());
BookAdditionalFileEntity additionalFile = BookAdditionalFileEntity.builder()
.book(bookEntity)
@@ -251,7 +240,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
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);
@@ -1,21 +1,19 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookMapper;
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.websocket.Topic;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -25,7 +23,6 @@ import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -39,11 +36,12 @@ public class LibraryProcessingService {
private final LibraryRepository libraryRepository;
private final NotificationService notificationService;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final FileService fileService;
private final BookMapper bookMapper;
private final LibraryFileProcessorRegistry fileProcessorRegistry;
private final BookRestorationService bookRestorationService;
private final BookDeletionService bookDeletionService;
@PersistenceContext
private final EntityManager entityManager;
@Transactional
public void processLibrary(long libraryId) throws IOException {
@@ -64,48 +62,19 @@ public class LibraryProcessingService {
List<Long> additionalFileIds = detectDeletedAdditionalFiles(libraryFiles, libraryEntity);
if (!additionalFileIds.isEmpty()) {
log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName());
deleteRemovedAdditionalFiles(additionalFileIds);
bookDeletionService.deleteRemovedAdditionalFiles(additionalFileIds);
}
List<Long> bookIds = detectDeletedBookIds(libraryFiles, libraryEntity);
if (!bookIds.isEmpty()) {
log.info("Detected {} removed books in library: {}", bookIds.size(), libraryEntity.getName());
processDeletedLibraryFiles(bookIds, libraryFiles);
bookDeletionService.processDeletedLibraryFiles(bookIds, libraryFiles);
}
restoreDeletedBooks(libraryFiles);
bookRestorationService.restoreDeletedBooks(libraryFiles);
entityManager.clear();
processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity);
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
}
private void restoreDeletedBooks(List<LibraryFile> libraryFiles) {
if (libraryFiles.isEmpty()) return;
LibraryEntity libraryEntity = libraryFiles.get(0).getLibraryEntity();
Set<Path> currentPaths = libraryFiles.stream()
.map(LibraryFile::getFullPath)
.collect(Collectors.toSet());
List<BookEntity> toRestore = libraryEntity.getBookEntities().stream()
.filter(book -> Boolean.TRUE.equals(book.getDeleted()))
.filter(book -> currentPaths.contains(book.getFullFilePath()))
.collect(Collectors.toList());
if (toRestore.isEmpty()) return;
toRestore.forEach(book -> {
book.setDeleted(false);
book.setDeletedAt(null);
book.setAddedOn(Instant.now());
notificationService.sendMessage(Topic.BOOK_ADD, bookMapper.toBookWithDescription(book, false));
});
bookRepository.saveAll(toRestore);
List<Long> restoredIds = toRestore.stream()
.map(BookEntity::getId)
.toList();
log.info("Restored {} books in library: {}", restoredIds.size(), libraryEntity.getName());
}
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
processor.processLibraryFiles(libraryFiles, libraryEntity);
@@ -157,119 +126,6 @@ public class LibraryProcessingService {
.collect(Collectors.toList());
}
@Transactional
protected void deleteRemovedAdditionalFiles(List<Long> additionalFileIds) {
if (additionalFileIds.isEmpty()) {
return;
}
List<BookAdditionalFileEntity> additionalFiles = bookAdditionalFileRepository.findAllById(additionalFileIds);
bookAdditionalFileRepository.deleteAll(additionalFiles);
log.info("Deleted {} additional files from database", additionalFileIds.size());
}
@Transactional
protected void processDeletedLibraryFiles(List<Long> deletedBookIds, List<LibraryFile> libraryFiles) {
if (deletedBookIds.isEmpty()) {
return;
}
List<BookEntity> books = bookRepository.findAllById(deletedBookIds);
List<Long> booksToDelete = new ArrayList<>();
for (BookEntity book : books) {
if (!tryPromoteAlternativeFormatToBook(book, libraryFiles)) {
booksToDelete.add(book.getId());
}
}
if (!booksToDelete.isEmpty()) {
deleteRemovedBooks(booksToDelete);
}
}
protected boolean tryPromoteAlternativeFormatToBook(BookEntity book, List<LibraryFile> libraryFiles) {
// Find existing alternative formats for this book
List<BookAdditionalFileEntity> existingAlternativeFormats = findExistingAlternativeFormats(book, libraryFiles);
if (existingAlternativeFormats.isEmpty()) {
return false; // No alternative formats to promote
}
// Promote the first alternative format to become the main book
BookAdditionalFileEntity promotedFormat = existingAlternativeFormats.getFirst();
promoteAlternativeFormatToBook(book, promotedFormat);
// Remove the promoted format from additional files
bookAdditionalFileRepository.delete(promotedFormat);
log.info("Promoted alternative format {} to main book for book ID {}", promotedFormat.getFileName(), book.getId());
return true;
}
private List<BookAdditionalFileEntity> findExistingAlternativeFormats(BookEntity book, List<LibraryFile> libraryFiles) {
Set<String> currentFileNames = libraryFiles.stream()
.map(LibraryFile::getFileName)
.collect(Collectors.toSet());
if (book.getAdditionalFiles() == null) {
return Collections.emptyList();
}
return book.getAdditionalFiles().stream()
.filter(additionalFile -> AdditionalFileType.ALTERNATIVE_FORMAT.equals(additionalFile.getAdditionalFileType()))
.filter(additionalFile -> currentFileNames.contains(additionalFile.getFileName()))
.filter(additionalFile -> BookFileExtension.fromFileName(additionalFile.getFileName()).isPresent())
.collect(Collectors.toList());
}
private void promoteAlternativeFormatToBook(BookEntity book, BookAdditionalFileEntity alternativeFormat) {
book.setFileName(alternativeFormat.getFileName());
book.setFileSubPath(alternativeFormat.getFileSubPath());
BookFileExtension.fromFileName(alternativeFormat.getFileName())
.ifPresent(ext -> book.setBookType(ext.getType()));
book.setFileSizeKb(alternativeFormat.getFileSizeKb());
book.setCurrentHash(alternativeFormat.getCurrentHash());
book.setInitialHash(alternativeFormat.getInitialHash());
bookRepository.save(book);
}
@Transactional
protected void deleteRemovedBooks(List<Long> bookIds) {
List<BookEntity> books = bookRepository.findAllById(bookIds);
for (BookEntity book : books) {
try {
deleteDirectoryRecursively(Path.of(fileService.getImagesFolder(book.getId())));
Path backupDir = Path.of(fileService.getBookMetadataBackupPath(book.getId()));
if (Files.exists(backupDir)) {
deleteDirectoryRecursively(backupDir);
}
} catch (Exception e) {
log.warn("Failed to clean up files for book ID {}: {}", book.getId(), e.getMessage());
}
}
bookRepository.deleteAll(books);
notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
if (bookIds.size() > 1) log.info("Books removed: {}", bookIds);
}
private void deleteDirectoryRecursively(Path path) throws IOException {
if (Files.exists(path)) {
try (Stream<Path> walk = Files.walk(path)) {
walk.sorted(Comparator.reverseOrder()).forEach(p -> {
try {
Files.deleteIfExists(p);
} catch (IOException e) {
log.warn("Failed to delete file or directory: {}", p, e);
}
});
}
}
}
private List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
List<LibraryFile> allFiles = new ArrayList<>();
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.upload;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.AdditionalFileMapper;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.dto.AdditionalFile;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
@@ -14,6 +15,7 @@ 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.FileProcessStatus;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
@@ -82,7 +84,7 @@ public class FileUploadService {
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
Path tempPath = Files.createTempFile("upload-", Objects.requireNonNull(file.getOriginalFilename()));
Book book;
FileProcessResult result;
boolean wePaused = false;
if (!monitoringService.isPaused()) {
@@ -113,10 +115,12 @@ public class FileUploadService {
log.info("File uploaded to final location: {}", finalPath);
book = processFile(finalFile.getName(), libraryEntity, libraryPathEntity, finalFile, fileExt.getType());
notificationService.sendMessage(Topic.BOOK_ADD, book);
result = processFile(finalFile.getName(), libraryEntity, libraryPathEntity, finalFile, fileExt.getType());
if (result != null && result.getStatus() != FileProcessStatus.DUPLICATE) {
notificationService.sendMessage(Topic.BOOK_ADD, result.getBook());
}
return book;
return result.getBook();
} catch (IOException e) {
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
@@ -281,7 +285,7 @@ public class FileUploadService {
}
}
private Book processFile(String fileName, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile, BookFileType type) {
private FileProcessResult processFile(String fileName, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile, BookFileType type) {
String subPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), storageFile.toPath());
LibraryFile libraryFile = LibraryFile.builder()