Refactor file mover to ensure faster transfers and more reliable handling (#1406)
This commit is contained in:
+1
-1
@@ -18,7 +18,7 @@ public class FileMoveController {
|
||||
|
||||
@PostMapping("/move")
|
||||
public ResponseEntity<?> moveFiles(@RequestBody FileMoveRequest request) {
|
||||
fileMoveService.moveFiles(request);
|
||||
fileMoveService.bulkMoveFiles(request);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
public class FileMoveResult {
|
||||
private boolean moved;
|
||||
private String newFileName;
|
||||
private String newFileSubPath;
|
||||
}
|
||||
+1
@@ -14,5 +14,6 @@ public class FileMoveRequest {
|
||||
public static class Move {
|
||||
private Long bookId;
|
||||
private Long targetLibraryId;
|
||||
private Long targetLibraryPathId;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ public class LibraryEntity {
|
||||
@Convert(converter = SortConverter.class)
|
||||
private Sort sort;
|
||||
|
||||
@OneToMany(mappedBy = "library", cascade = CascadeType.MERGE, orphanRemoval = true)
|
||||
@OneToMany(mappedBy = "library", orphanRemoval = true)
|
||||
private List<BookEntity> bookEntities;
|
||||
|
||||
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
|
||||
|
||||
@@ -7,6 +7,7 @@ import lombok.Getter;
|
||||
@AllArgsConstructor
|
||||
public enum Topic {
|
||||
BOOK_ADD("/queue/book-add"),
|
||||
BOOK_UPDATE("/queue/book-update"),
|
||||
BOOKS_REMOVE("/queue/books-remove"),
|
||||
BOOK_METADATA_UPDATE("/queue/book-metadata-update"),
|
||||
BOOK_METADATA_BATCH_UPDATE("/queue/book-metadata-batch-update"),
|
||||
|
||||
+16
-29
@@ -1,11 +1,13 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.*;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.security.core.parameters.P;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.time.Instant;
|
||||
@@ -112,39 +114,24 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
""")
|
||||
Page<BookEntity> searchByMetadata(@Param("text") String text, Pageable pageable);
|
||||
|
||||
@Query(value = """
|
||||
SELECT DISTINCT b FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||
AND b.library.id IN :libraryIds
|
||||
AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
""",
|
||||
countQuery = """
|
||||
SELECT COUNT(DISTINCT b.id) FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||
AND b.library.id IN :libraryIds
|
||||
AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
""")
|
||||
Page<BookEntity> searchByMetadataAndLibraryIds(@Param("text") String text, @Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
|
||||
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query("DELETE FROM BookEntity b WHERE b.deletedAt IS NOT NULL AND b.deletedAt < :cutoff")
|
||||
int deleteAllByDeletedAtBefore(Instant cutoff);
|
||||
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query("UPDATE BookEntity b SET b.library.id = :libraryId WHERE b.id = :bookId")
|
||||
void updateLibraryId(@Param("bookId") Long bookId, @Param("libraryId") Long libraryId);
|
||||
@Query("""
|
||||
UPDATE BookEntity b
|
||||
SET b.fileSubPath = :fileSubPath,
|
||||
b.fileName = :fileName,
|
||||
b.library.id = :libraryId,
|
||||
b.libraryPath = :libraryPath
|
||||
WHERE b.id = :bookId
|
||||
""")
|
||||
void updateFileAndLibrary(
|
||||
@Param("bookId") Long bookId,
|
||||
@Param("fileSubPath") String fileSubPath,
|
||||
@Param("fileName") String fileName,
|
||||
@Param("libraryId") Long libraryId,
|
||||
@Param("libraryPath") LibraryPathEntity libraryPath);
|
||||
}
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package com.adityachandel.booklore.service.file;
|
||||
|
||||
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.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import com.adityachandel.booklore.util.PathPatternResolver;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class FileMoveHelper {
|
||||
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public void moveFile(Path source, Path target) throws IOException {
|
||||
if (target.getParent() != null) {
|
||||
Files.createDirectories(target.getParent());
|
||||
}
|
||||
log.info("Moving file from {} to {}", source, target);
|
||||
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
public String extractSubPath(Path filePath, LibraryPathEntity libraryPathEntity) {
|
||||
Path libraryRoot = Paths.get(libraryPathEntity.getPath()).toAbsolutePath().normalize();
|
||||
Path parentDir = filePath.getParent().toAbsolutePath().normalize();
|
||||
Path relativeSubPath = libraryRoot.relativize(parentDir);
|
||||
return relativeSubPath.toString().replace('\\', '/');
|
||||
}
|
||||
|
||||
public void unregisterLibrary(Long libraryId) {
|
||||
monitoringRegistrationService.unregisterLibrary(libraryId);
|
||||
}
|
||||
|
||||
public void registerLibraryPaths(Long libraryId, Path libraryRoot) {
|
||||
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
|
||||
}
|
||||
|
||||
public String getFileNamingPattern(LibraryEntity library) {
|
||||
String pattern = library.getFileNamingPattern();
|
||||
if (pattern == null || pattern.trim().isEmpty()) {
|
||||
try {
|
||||
pattern = appSettingService.getAppSettings().getUploadPattern();
|
||||
log.debug("Using default pattern for library {} as no custom pattern is set", library.getName());
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to get default upload pattern for library {}: {}", library.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
if (pattern == null || pattern.trim().isEmpty()) {
|
||||
pattern = "{currentFilename}";
|
||||
log.info("No file naming pattern available for library {}. Using fallback pattern: {currentFilename}", library.getName());
|
||||
}
|
||||
if (pattern.endsWith("/") || pattern.endsWith("\\")) {
|
||||
pattern += "{currentFilename}";
|
||||
}
|
||||
return pattern;
|
||||
}
|
||||
|
||||
public Path generateNewFilePath(BookEntity book, LibraryPathEntity libraryPathEntity, String pattern) {
|
||||
String newRelativePathStr = PathPatternResolver.resolvePattern(book, pattern);
|
||||
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
|
||||
newRelativePathStr = newRelativePathStr.substring(1);
|
||||
}
|
||||
String path = libraryPathEntity.getPath();
|
||||
return Paths.get(path, newRelativePathStr);
|
||||
}
|
||||
|
||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
|
||||
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
||||
currentDir = currentDir.toAbsolutePath().normalize();
|
||||
Set<Path> normalizedRoots = new HashSet<>();
|
||||
for (Path root : libraryRoots) {
|
||||
normalizedRoots.add(root.toAbsolutePath().normalize());
|
||||
}
|
||||
while (currentDir != null) {
|
||||
if (isLibraryRoot(currentDir, normalizedRoots)) {
|
||||
break;
|
||||
}
|
||||
File[] files = currentDir.toFile().listFiles();
|
||||
if (files == null) {
|
||||
log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir);
|
||||
break;
|
||||
}
|
||||
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
|
||||
deleteIgnoredFilesAndDirectory(files, currentDir);
|
||||
currentDir = currentDir.getParent();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isLibraryRoot(Path currentDir, Set<Path> normalizedRoots) {
|
||||
for (Path root : normalizedRoots) {
|
||||
try {
|
||||
if (Files.isSameFile(root, currentDir)) {
|
||||
return true;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to compare paths: {} and {}", root, currentDir);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean hasOnlyIgnoredFiles(File[] files, Set<String> ignoredFilenames) {
|
||||
for (File file : files) {
|
||||
if (!ignoredFilenames.contains(file.getName())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void deleteIgnoredFilesAndDirectory(File[] files, Path currentDir) {
|
||||
for (File file : files) {
|
||||
try {
|
||||
Files.delete(file.toPath());
|
||||
log.info("Deleted ignored file: {}", file.getAbsolutePath());
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete ignored file: {}", file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
try {
|
||||
Files.delete(currentDir);
|
||||
log.info("Deleted empty directory: {}", currentDir);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete directory: {}", currentDir, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+122
-149
@@ -1,182 +1,155 @@
|
||||
package com.adityachandel.booklore.service.file;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.mapper.LibraryMapper;
|
||||
import com.adityachandel.booklore.model.dto.FileMoveResult;
|
||||
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
|
||||
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.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.util.PathPatternResolver;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.model.enums.PermissionType.ADMIN;
|
||||
import static com.adityachandel.booklore.model.enums.PermissionType.MANIPULATE_LIBRARY;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
@Slf4j
|
||||
public class FileMoveService {
|
||||
|
||||
private static final int BATCH_SIZE = 100;
|
||||
|
||||
private final BookQueryService bookQueryService;
|
||||
private final BookRepository bookRepository;
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final FileMoveHelper fileMoveHelper;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
private final LibraryMapper libraryMapper;
|
||||
private final BookMapper bookMapper;
|
||||
private final NotificationService notificationService;
|
||||
private final UnifiedFileMoveService unifiedFileMoveService;
|
||||
private final EntityManager entityManager;
|
||||
|
||||
|
||||
@Transactional
|
||||
public void moveFiles(FileMoveRequest request) {
|
||||
List<Long> bookIds = request.getBookIds().stream().toList();
|
||||
List<FileMoveRequest.Move> moves = request.getMoves() != null ? request.getMoves() : List.of();
|
||||
public void bulkMoveFiles(FileMoveRequest request) {
|
||||
List<FileMoveRequest.Move> moves = request.getMoves();
|
||||
Set<Long> targetLibraryIds = moves.stream().map(FileMoveRequest.Move::getTargetLibraryId).collect(Collectors.toSet());
|
||||
Set<Long> sourceLibraryIds = new HashSet<>();
|
||||
monitoringRegistrationService.unregisterLibraries(targetLibraryIds);
|
||||
|
||||
log.info("Moving {} books with {} specific moves in batches of {}", bookIds.size(), moves.size(), BATCH_SIZE);
|
||||
for (FileMoveRequest.Move move : moves) {
|
||||
Long bookId = move.getBookId();
|
||||
Long targetLibraryId = move.getTargetLibraryId();
|
||||
Long targetLibraryPathId = move.getTargetLibraryPathId();
|
||||
|
||||
Map<Long, Long> bookToTargetLibraryMap = moves.stream()
|
||||
.collect(Collectors.toMap(
|
||||
FileMoveRequest.Move::getBookId,
|
||||
FileMoveRequest.Move::getTargetLibraryId
|
||||
));
|
||||
|
||||
Map<Long, List<Book>> libraryRemovals = new HashMap<>();
|
||||
Map<Long, List<Book>> libraryAdditions = new HashMap<>();
|
||||
List<Book> allUpdatedBooks = new ArrayList<>();
|
||||
int totalProcessed = 0;
|
||||
int offset = 0;
|
||||
|
||||
while (offset < bookIds.size()) {
|
||||
log.info("Processing batch {}/{}", (offset / BATCH_SIZE) + 1, (bookIds.size() + BATCH_SIZE - 1) / BATCH_SIZE);
|
||||
|
||||
List<Long> batchBookIds = bookIds.subList(offset, Math.min(offset + BATCH_SIZE, bookIds.size()));
|
||||
Set<Long> batchBookIdSet = new HashSet<>(batchBookIds);
|
||||
|
||||
List<BookEntity> batchBooks = bookQueryService.findWithMetadataByIdsWithPagination(batchBookIdSet, offset, BATCH_SIZE);
|
||||
|
||||
if (batchBooks.isEmpty()) {
|
||||
log.info("No more books at offset {}", offset);
|
||||
break;
|
||||
}
|
||||
|
||||
List<Book> batchUpdatedBooks = processBookChunk(batchBooks, bookToTargetLibraryMap, libraryRemovals, libraryAdditions);
|
||||
allUpdatedBooks.addAll(batchUpdatedBooks);
|
||||
|
||||
totalProcessed += batchBooks.size();
|
||||
offset += BATCH_SIZE;
|
||||
|
||||
log.info("Processed {}/{} books", totalProcessed, bookIds.size());
|
||||
}
|
||||
|
||||
log.info("Move completed: {} books processed, {} updated", totalProcessed, allUpdatedBooks.size());
|
||||
sendUpdateNotifications(allUpdatedBooks);
|
||||
sendCrossLibraryMoveNotifications(libraryRemovals, libraryAdditions);
|
||||
|
||||
}
|
||||
|
||||
public String generatePathFromPattern(BookEntity book, String pattern) {
|
||||
return PathPatternResolver.resolvePattern(book, pattern);
|
||||
}
|
||||
|
||||
private List<Book> processBookChunk(List<BookEntity> books, Map<Long, Long> bookToTargetLibraryMap, Map<Long, List<Book>> libraryRemovals, Map<Long, List<Book>> libraryAdditions) {
|
||||
List<Book> updatedBooks = new ArrayList<>();
|
||||
|
||||
Map<Long, Long> originalLibraryIds = new HashMap<>();
|
||||
for (BookEntity book : books) {
|
||||
if (book.getLibraryPath() != null && book.getLibraryPath().getLibrary() != null) {
|
||||
originalLibraryIds.put(book.getId(), book.getLibraryPath().getLibrary().getId());
|
||||
}
|
||||
}
|
||||
|
||||
unifiedFileMoveService.moveBatchBookFiles(books, bookToTargetLibraryMap, new UnifiedFileMoveService.BatchMoveCallback() {
|
||||
@Override
|
||||
public void onBookMoved(BookEntity book) {
|
||||
Long targetLibraryId = bookToTargetLibraryMap.get(book.getId());
|
||||
Long originalSourceLibraryId = originalLibraryIds.get(book.getId());
|
||||
|
||||
log.debug("Processing moved book {}: targetLibraryId={}, originalSourceLibraryId={}", book.getId(), targetLibraryId, originalSourceLibraryId);
|
||||
|
||||
if (targetLibraryId != null && originalSourceLibraryId != null && !targetLibraryId.equals(originalSourceLibraryId)) {
|
||||
log.info("Cross-library move detected for book {}: {} -> {}", book.getId(), originalSourceLibraryId, targetLibraryId);
|
||||
|
||||
Book bookDtoForRemoval = bookMapper.toBookWithDescription(book, false);
|
||||
bookDtoForRemoval.setLibraryId(originalSourceLibraryId);
|
||||
libraryRemovals.computeIfAbsent(originalSourceLibraryId, k -> new ArrayList<>()).add(bookDtoForRemoval);
|
||||
log.debug("Added book {} to removal list for library {}", book.getId(), originalSourceLibraryId);
|
||||
|
||||
bookRepository.updateLibraryId(book.getId(), targetLibraryId);
|
||||
log.debug("Updated library_id for book {} to {}", book.getId(), targetLibraryId);
|
||||
|
||||
BookEntity savedBook = bookRepository.saveAndFlush(book);
|
||||
|
||||
Book updatedBookDto = bookMapper.toBookWithDescription(savedBook, false);
|
||||
updatedBookDto.setLibraryId(targetLibraryId);
|
||||
libraryAdditions.computeIfAbsent(targetLibraryId, k -> new ArrayList<>()).add(updatedBookDto);
|
||||
log.debug("Added book {} to addition list for library {} with libraryId {}", book.getId(), targetLibraryId, updatedBookDto.getLibraryId());
|
||||
|
||||
updatedBooks.add(updatedBookDto);
|
||||
} else {
|
||||
log.debug("Same library move for book {} or no target specified. Target: {}, Original: {}", book.getId(), targetLibraryId, originalSourceLibraryId);
|
||||
BookEntity savedBook = bookRepository.save(book);
|
||||
updatedBooks.add(bookMapper.toBook(savedBook));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBookMoveFailed(BookEntity book, Exception error) {
|
||||
log.error("Move failed for book {}: {}", book.getId(), error.getMessage(), error);
|
||||
throw new RuntimeException("File move failed for book id " + book.getId(), error);
|
||||
}
|
||||
});
|
||||
|
||||
log.info("Processed {} books, {} library removals tracked, {} library additions tracked", updatedBooks.size(), libraryRemovals.size(), libraryAdditions.size());
|
||||
|
||||
return updatedBooks;
|
||||
}
|
||||
|
||||
private void sendUpdateNotifications(List<Book> updatedBooks) {
|
||||
if (!updatedBooks.isEmpty()) {
|
||||
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_UPDATE, updatedBooks);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendCrossLibraryMoveNotifications(Map<Long, List<Book>> libraryRemovals, Map<Long, List<Book>> libraryAdditions) {
|
||||
log.info("Sending cross-library move notifications: {} removals, {} additions",
|
||||
libraryRemovals.size(), libraryAdditions.size());
|
||||
|
||||
for (Map.Entry<Long, List<Book>> entry : libraryRemovals.entrySet()) {
|
||||
List<Long> removedBookIds = entry.getValue().stream()
|
||||
.map(Book::getId)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
log.info("Notifying removal of {} books from library {}: {}", removedBookIds.size(), entry.getKey(), removedBookIds);
|
||||
try {
|
||||
notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, removedBookIds, Set.of(ADMIN, MANIPULATE_LIBRARY));
|
||||
log.info("Successfully sent removal notification for library {}", entry.getKey());
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to send removal notification for library {}: {}", entry.getKey(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
for (Map.Entry<Long, List<Book>> entry : libraryAdditions.entrySet()) {
|
||||
List<Book> addedBooks = entry.getValue();
|
||||
|
||||
log.info("Notifying addition of {} books to library {}", addedBooks.size(), entry.getKey());
|
||||
try {
|
||||
for (Book book : addedBooks) {
|
||||
log.debug("Sending BOOK_ADD notification for book {} to library {}", book.getId(), entry.getKey());
|
||||
notificationService.sendMessageToPermissions(Topic.BOOK_ADD, book, Set.of(ADMIN, MANIPULATE_LIBRARY));
|
||||
Optional<BookEntity> optionalBook = bookRepository.findById(bookId);
|
||||
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(targetLibraryId);
|
||||
if (optionalBook.isEmpty() || optionalLibrary.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
log.info("Successfully sent {} addition notifications for library {}", addedBooks.size(), entry.getKey());
|
||||
BookEntity bookEntity = optionalBook.get();
|
||||
LibraryEntity targetLibrary = optionalLibrary.get();
|
||||
|
||||
Optional<LibraryPathEntity> optionalLibraryPathEntity = targetLibrary.getLibraryPaths().stream().filter(l -> Objects.equals(l.getId(), targetLibraryPathId)).findFirst();
|
||||
if (optionalLibraryPathEntity.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
LibraryPathEntity libraryPathEntity = optionalLibraryPathEntity.get();
|
||||
|
||||
LibraryEntity sourceLibrary = bookEntity.getLibrary();
|
||||
if (sourceLibrary.getId().equals(targetLibrary.getId())) {
|
||||
continue;
|
||||
}
|
||||
if (!sourceLibraryIds.contains(sourceLibrary.getId())) {
|
||||
monitoringRegistrationService.unregisterLibraries(Collections.singleton(sourceLibrary.getId()));
|
||||
sourceLibraryIds.add(sourceLibrary.getId());
|
||||
}
|
||||
Path currentFilePath = bookEntity.getFullFilePath();
|
||||
String pattern = fileMoveHelper.getFileNamingPattern(targetLibrary);
|
||||
Path newFilePath = fileMoveHelper.generateNewFilePath(bookEntity, libraryPathEntity, pattern);
|
||||
if (currentFilePath.equals(newFilePath)) {
|
||||
continue;
|
||||
}
|
||||
fileMoveHelper.moveFile(currentFilePath, newFilePath);
|
||||
|
||||
String newFileName = newFilePath.getFileName().toString();
|
||||
String newFileSubPath = fileMoveHelper.extractSubPath(newFilePath, libraryPathEntity);
|
||||
bookRepository.updateFileAndLibrary(bookEntity.getId(), newFileSubPath, newFileName, targetLibrary.getId(), libraryPathEntity);
|
||||
|
||||
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot));
|
||||
|
||||
entityManager.clear();
|
||||
|
||||
BookEntity fresh = bookRepository.findById(bookId).orElseThrow();
|
||||
|
||||
notificationService.sendMessage(Topic.BOOK_UPDATE, bookMapper.toBookWithDescription(fresh, false));
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to send addition notifications for library {}: {}", entry.getKey(), e.getMessage(), e);
|
||||
log.error("Error moving file for book ID {}: {}", bookId, e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
for (Long libraryId : targetLibraryIds) {
|
||||
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
|
||||
optionalLibrary.ifPresent(library -> {
|
||||
monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library));
|
||||
});
|
||||
}
|
||||
for (Long libraryId : sourceLibraryIds) {
|
||||
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
|
||||
optionalLibrary.ifPresent(library -> {
|
||||
monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public FileMoveResult moveSingleFile(BookEntity bookEntity) {
|
||||
|
||||
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
|
||||
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
|
||||
try {
|
||||
String pattern = fileMoveHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary());
|
||||
Path currentFilePath = bookEntity.getFullFilePath();
|
||||
Path expectedFilePath = fileMoveHelper.generateNewFilePath(bookEntity, bookEntity.getLibraryPath(), pattern);
|
||||
|
||||
if (currentFilePath.equals(expectedFilePath)) {
|
||||
return FileMoveResult.builder().moved(false).build();
|
||||
}
|
||||
|
||||
log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath);
|
||||
|
||||
fileMoveHelper.unregisterLibrary(libraryId);
|
||||
|
||||
fileMoveHelper.moveFile(currentFilePath, expectedFilePath);
|
||||
|
||||
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot));
|
||||
|
||||
String newFileName = expectedFilePath.getFileName().toString();
|
||||
String newFileSubPath = fileMoveHelper.extractSubPath(expectedFilePath, bookEntity.getLibraryPath());
|
||||
|
||||
return FileMoveResult.builder()
|
||||
.moved(true)
|
||||
.newFileName(newFileName)
|
||||
.newFileSubPath(newFileSubPath)
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
|
||||
} finally {
|
||||
fileMoveHelper.registerLibraryPaths(libraryId, libraryRoot);
|
||||
}
|
||||
|
||||
return FileMoveResult.builder().moved(false).build();
|
||||
}
|
||||
}
|
||||
|
||||
+3
-368
@@ -1,12 +1,7 @@
|
||||
package com.adityachandel.booklore.service.file;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
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.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryPathRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.util.PathPatternResolver;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -14,51 +9,17 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class FileMovingHelper {
|
||||
|
||||
private final BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
private final LibraryPathRepository libraryPathRepository;
|
||||
|
||||
/**
|
||||
* Generates the new file path based on the library's file naming pattern
|
||||
*/
|
||||
public Path generateNewFilePath(BookEntity book, String pattern) {
|
||||
String newRelativePathStr = PathPatternResolver.resolvePattern(book, pattern);
|
||||
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
|
||||
newRelativePathStr = newRelativePathStr.substring(1);
|
||||
}
|
||||
|
||||
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
return libraryRoot.resolve(newRelativePathStr).normalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the new file path based on metadata and file naming pattern
|
||||
*/
|
||||
public Path generateNewFilePath(String libraryRootPath, BookMetadata metadata, String pattern, String fileName) {
|
||||
String relativePath = PathPatternResolver.resolvePattern(metadata, pattern, FilenameUtils.getName(fileName));
|
||||
return Paths.get(libraryRootPath, relativePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the file naming pattern for a library, falling back to default if not set,
|
||||
* and finally to {currentFilename} if no patterns are available
|
||||
*/
|
||||
public String getFileNamingPattern(LibraryEntity library) {
|
||||
String pattern = library.getFileNamingPattern();
|
||||
if (pattern == null || pattern.trim().isEmpty()) {
|
||||
@@ -73,340 +34,14 @@ public class FileMovingHelper {
|
||||
pattern = "{currentFilename}";
|
||||
log.info("No file naming pattern available for library {}. Using fallback pattern: {currentFilename}", library.getName());
|
||||
}
|
||||
|
||||
// Ensure pattern ends with filename placeholder if it ends with separator
|
||||
if (pattern.endsWith("/") || pattern.endsWith("\\")) {
|
||||
pattern += "{currentFilename}";
|
||||
}
|
||||
|
||||
return pattern;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a book has all required path components for file operations
|
||||
*/
|
||||
public boolean hasRequiredPathComponents(BookEntity book) {
|
||||
if (book.getLibraryPath() == null || book.getLibraryPath().getPath() == null ||
|
||||
book.getFileSubPath() == null || book.getFileName() == null) {
|
||||
log.error("Missing required path components for book id {}. Skipping.", book.getId());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a book file if the current path differs from the expected pattern
|
||||
*/
|
||||
public boolean moveBookFileIfNeeded(BookEntity book, String pattern) throws IOException {
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
Path newFilePath = generateNewFilePath(book, pattern);
|
||||
|
||||
if (oldFilePath.equals(newFilePath)) {
|
||||
log.debug("Source and destination paths are identical for book id {}. Skipping.", book.getId());
|
||||
return false;
|
||||
}
|
||||
|
||||
moveBookFileAndUpdatePaths(book, oldFilePath, newFilePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a file from source to target path, creating directories as needed
|
||||
*/
|
||||
public void moveFile(Path source, Path target) throws IOException {
|
||||
if (target.getParent() != null) {
|
||||
Files.createDirectories(target.getParent());
|
||||
}
|
||||
|
||||
log.info("Moving file from {} to {}", source, target);
|
||||
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates book entity paths after a file move
|
||||
*/
|
||||
public void updateBookPaths(BookEntity book, Path newFilePath) {
|
||||
String newFileName = newFilePath.getFileName().toString();
|
||||
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent());
|
||||
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
|
||||
|
||||
book.setFileSubPath(newFileSubPath);
|
||||
book.setFileName(newFileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves additional files for a book based on the file naming pattern
|
||||
*/
|
||||
public void moveAdditionalFiles(BookEntity book, String pattern) throws IOException {
|
||||
Map<String, Integer> fileNameCounter = new HashMap<>();
|
||||
|
||||
for (BookAdditionalFileEntity additionalFile : book.getAdditionalFiles()) {
|
||||
moveAdditionalFile(book, additionalFile, pattern, fileNameCounter);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes empty parent directories up to library roots
|
||||
*/
|
||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
|
||||
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
||||
currentDir = currentDir.toAbsolutePath().normalize();
|
||||
|
||||
Set<Path> normalizedRoots = new HashSet<>();
|
||||
for (Path root : libraryRoots) {
|
||||
normalizedRoots.add(root.toAbsolutePath().normalize());
|
||||
}
|
||||
|
||||
while (currentDir != null) {
|
||||
if (isLibraryRoot(currentDir, normalizedRoots)) {
|
||||
log.debug("Reached library root: {}. Stopping cleanup.", currentDir);
|
||||
break;
|
||||
}
|
||||
|
||||
File[] files = currentDir.toFile().listFiles();
|
||||
if (files == null) {
|
||||
log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir);
|
||||
break;
|
||||
}
|
||||
|
||||
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
|
||||
deleteIgnoredFilesAndDirectory(files, currentDir);
|
||||
currentDir = currentDir.getParent();
|
||||
} else {
|
||||
log.debug("Directory {} contains important files. Stopping cleanup.", currentDir);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a book file to a different library with the target library's naming pattern
|
||||
*/
|
||||
public boolean moveBookFileToLibrary(BookEntity book, LibraryEntity targetLibrary) throws IOException {
|
||||
if (!hasRequiredPathComponents(book)) {
|
||||
log.error("Missing required path components for book id {}. Cannot move to different library.", book.getId());
|
||||
return false;
|
||||
}
|
||||
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
String pattern = getFileNamingPattern(targetLibrary);
|
||||
|
||||
// Generate new file path in target library
|
||||
Path newFilePath = generateNewFilePathForLibrary(book, targetLibrary, pattern);
|
||||
|
||||
if (oldFilePath.equals(newFilePath)) {
|
||||
log.debug("Source and destination paths are identical for book id {}. Skipping cross-library move.", book.getId());
|
||||
return false;
|
||||
}
|
||||
|
||||
moveBookFileAndUpdatePathsForLibrary(book, oldFilePath, newFilePath, targetLibrary);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the new file path for a book in a different library
|
||||
*/
|
||||
public Path generateNewFilePathForLibrary(BookEntity book, LibraryEntity targetLibrary, String pattern) {
|
||||
String newRelativePathStr = PathPatternResolver.resolvePattern(book, pattern);
|
||||
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
|
||||
newRelativePathStr = newRelativePathStr.substring(1);
|
||||
}
|
||||
|
||||
Path targetLibraryRoot = getLibraryRootPath(targetLibrary);
|
||||
return targetLibraryRoot.resolve(newRelativePathStr).normalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the root path for a library (uses the first library path)
|
||||
*/
|
||||
private Path getLibraryRootPath(LibraryEntity library) {
|
||||
if (library.getLibraryPaths() == null || library.getLibraryPaths().isEmpty()) {
|
||||
throw new RuntimeException("Library " + library.getName() + " has no paths configured");
|
||||
}
|
||||
return Paths.get(library.getLibraryPaths().getFirst().getPath()).toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
private void moveBookFileAndUpdatePaths(BookEntity book, Path oldFilePath, Path newFilePath) throws IOException {
|
||||
moveFile(oldFilePath, newFilePath);
|
||||
updateBookPaths(book, newFilePath);
|
||||
|
||||
// Clean up empty directories
|
||||
try {
|
||||
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot));
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to clean up empty directories after moving book ID {}: {}", book.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void moveBookFileAndUpdatePathsForLibrary(BookEntity book, Path oldFilePath, Path newFilePath, LibraryEntity targetLibrary) throws IOException {
|
||||
moveFile(oldFilePath, newFilePath);
|
||||
updateBookPathsForLibrary(book, newFilePath, targetLibrary);
|
||||
|
||||
// Clean up empty directories in source library
|
||||
// IMPORTANT: We need to collect ALL library roots to avoid deleting any library root directory
|
||||
try {
|
||||
Set<Path> allLibraryRoots = getAllLibraryRoots();
|
||||
deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), allLibraryRoots);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to clean up empty directories after moving book ID {}: {}", book.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all library root paths from all libraries to ensure we never delete any library root
|
||||
*/
|
||||
private Set<Path> getAllLibraryRoots() {
|
||||
Set<Path> allRoots = new HashSet<>();
|
||||
try {
|
||||
// Get all libraries and collect their root paths
|
||||
libraryPathRepository.findAll().forEach(libraryPath -> {
|
||||
try {
|
||||
Path rootPath = Paths.get(libraryPath.getPath()).toAbsolutePath().normalize();
|
||||
allRoots.add(rootPath);
|
||||
log.debug("Added library root to protection list: {}", rootPath);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to process library path {}: {}", libraryPath.getPath(), e.getMessage());
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to collect all library roots: {}", e.getMessage());
|
||||
}
|
||||
return allRoots;
|
||||
}
|
||||
|
||||
private void updateBookPathsForLibrary(BookEntity book, Path newFilePath, LibraryEntity targetLibrary) {
|
||||
String newFileName = newFilePath.getFileName().toString();
|
||||
Path targetLibraryRoot = getLibraryRootPath(targetLibrary);
|
||||
Path newRelativeSubPath = targetLibraryRoot.relativize(newFilePath.getParent());
|
||||
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
|
||||
|
||||
// Find or create the appropriate LibraryPathEntity for the target library
|
||||
String targetLibraryPath = targetLibrary.getLibraryPaths().getFirst().getPath();
|
||||
LibraryPathEntity targetLibraryPathEntity = libraryPathRepository
|
||||
.findByLibraryIdAndPath(targetLibrary.getId(), targetLibraryPath)
|
||||
.orElseThrow(() -> new RuntimeException("LibraryPath not found for library " + targetLibrary.getId() + " and path " + targetLibraryPath));
|
||||
|
||||
// Update only the path-related fields, avoid touching library entity relationships
|
||||
// that might trigger cascade operations
|
||||
book.setLibraryPath(targetLibraryPathEntity); // This should update library_path_id
|
||||
book.setFileSubPath(newFileSubPath);
|
||||
book.setFileName(newFileName);
|
||||
|
||||
// DO NOT set book.setLibrary(targetLibrary) to avoid cascade issues
|
||||
log.debug("Updated book {} path references: libraryPathId={}, newPath={}",
|
||||
book.getId(), targetLibraryPathEntity.getId(), newFilePath);
|
||||
}
|
||||
|
||||
private void moveAdditionalFile(BookEntity book, BookAdditionalFileEntity additionalFile, String pattern, Map<String, Integer> fileNameCounter) throws IOException {
|
||||
Path oldAdditionalFilePath = additionalFile.getFullFilePath();
|
||||
if (!Files.exists(oldAdditionalFilePath)) {
|
||||
log.warn("Additional file does not exist for book id {}: {}", book.getId(), oldAdditionalFilePath);
|
||||
return;
|
||||
}
|
||||
|
||||
Path newAdditionalFilePath = generateAdditionalFilePath(book, additionalFile, pattern);
|
||||
newAdditionalFilePath = ensureUniqueFilePath(newAdditionalFilePath, fileNameCounter);
|
||||
|
||||
if (oldAdditionalFilePath.equals(newAdditionalFilePath)) {
|
||||
log.debug("Source and destination paths are identical for additional file id {}. Skipping.", additionalFile.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
moveFile(oldAdditionalFilePath, newAdditionalFilePath);
|
||||
|
||||
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
updateAdditionalFilePaths(additionalFile, newAdditionalFilePath, libraryRoot);
|
||||
bookAdditionalFileRepository.save(additionalFile);
|
||||
|
||||
log.info("Updated additional file id {} with new path", additionalFile.getId());
|
||||
}
|
||||
|
||||
private Path generateAdditionalFilePath(BookEntity book, BookAdditionalFileEntity additionalFile, String pattern) {
|
||||
String newRelativePathStr = PathPatternResolver.resolvePattern(book.getMetadata(), pattern, additionalFile.getFileName());
|
||||
// Fall back to the filename when resolver returns null/empty to avoid NPEs in callers/tests
|
||||
if (newRelativePathStr == null || newRelativePathStr.trim().isEmpty()) {
|
||||
newRelativePathStr = additionalFile.getFileName() != null ? additionalFile.getFileName() : "";
|
||||
}
|
||||
if (!newRelativePathStr.isEmpty() && (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\"))) {
|
||||
newRelativePathStr = newRelativePathStr.substring(1);
|
||||
}
|
||||
|
||||
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
return libraryRoot.resolve(newRelativePathStr).normalize();
|
||||
}
|
||||
|
||||
private Path ensureUniqueFilePath(Path filePath, Map<String, Integer> fileNameCounter) {
|
||||
String fileName = filePath.getFileName().toString();
|
||||
String baseName = fileName;
|
||||
String extension = "";
|
||||
|
||||
int lastDot = fileName.lastIndexOf(".");
|
||||
if (lastDot >= 0 && lastDot < fileName.length() - 1) {
|
||||
baseName = fileName.substring(0, lastDot);
|
||||
extension = fileName.substring(lastDot);
|
||||
}
|
||||
|
||||
String fileKey = filePath.toString().toLowerCase();
|
||||
Integer count = fileNameCounter.get(fileKey);
|
||||
|
||||
if (count == null) {
|
||||
fileNameCounter.put(fileKey, 1);
|
||||
return filePath;
|
||||
} else {
|
||||
count++;
|
||||
fileNameCounter.put(fileKey, count);
|
||||
String newFileName = baseName + "_" + count + extension;
|
||||
return filePath.getParent().resolve(newFileName);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateAdditionalFilePaths(BookAdditionalFileEntity additionalFile, Path newFilePath, Path libraryRoot) {
|
||||
String newFileName = newFilePath.getFileName().toString();
|
||||
Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent());
|
||||
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
|
||||
|
||||
additionalFile.setFileSubPath(newFileSubPath);
|
||||
additionalFile.setFileName(newFileName);
|
||||
}
|
||||
|
||||
private boolean isLibraryRoot(Path currentDir, Set<Path> normalizedRoots) {
|
||||
for (Path root : normalizedRoots) {
|
||||
try {
|
||||
if (Files.isSameFile(root, currentDir)) {
|
||||
return true;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to compare paths: {} and {}", root, currentDir);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean hasOnlyIgnoredFiles(File[] files, Set<String> ignoredFilenames) {
|
||||
for (File file : files) {
|
||||
if (!ignoredFilenames.contains(file.getName())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void deleteIgnoredFilesAndDirectory(File[] files, Path currentDir) {
|
||||
for (File file : files) {
|
||||
try {
|
||||
Files.delete(file.toPath());
|
||||
log.info("Deleted ignored file: {}", file.getAbsolutePath());
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete ignored file: {}", file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
try {
|
||||
Files.delete(currentDir);
|
||||
log.info("Deleted empty directory: {}", currentDir);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete directory: {}", currentDir, e);
|
||||
}
|
||||
public Path generateNewFilePath(String libraryRootPath, BookMetadata metadata, String pattern, String fileName) {
|
||||
String relativePath = PathPatternResolver.resolvePattern(metadata, pattern, FilenameUtils.getName(fileName));
|
||||
return Paths.get(libraryRootPath, relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
-147
@@ -1,147 +0,0 @@
|
||||
package com.adityachandel.booklore.service.file;
|
||||
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Service responsible for executing file operations while temporarily disabling monitoring
|
||||
* on specific paths to prevent event loops and race conditions during file system operations.
|
||||
*
|
||||
* This service provides targeted path protection by unregistering only the directories
|
||||
* involved in the operation rather than pausing all monitoring, ensuring minimal
|
||||
* disruption to the monitoring system.
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class MonitoredFileOperationService {
|
||||
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
|
||||
/**
|
||||
* Executes a file operation with targeted path protection to prevent monitoring conflicts.
|
||||
*
|
||||
* This method temporarily unregisters monitoring for only the specific directories involved
|
||||
* in the operation (source and target) rather than pausing all monitoring. This approach
|
||||
* minimizes the impact on the monitoring system while preventing event loops that could
|
||||
* occur when the monitoring service detects changes from our own file operations.
|
||||
*
|
||||
* The process follows these steps:
|
||||
* 1. Identify source and target directories
|
||||
* 2. Temporarily unregister monitoring for these specific paths
|
||||
* 3. Execute the file operation
|
||||
* 4. Wait for filesystem operations to settle
|
||||
* 5. Re-register paths and scan for new directory structures
|
||||
*
|
||||
* @param sourcePath the source file path for the operation
|
||||
* @param targetPath the target file path for the operation
|
||||
* @param libraryId the library ID used for re-registration of monitoring
|
||||
* @param operation the file operation to execute (supplied as a lambda)
|
||||
* @param <T> the return type of the operation
|
||||
*/
|
||||
public <T> void executeWithMonitoringSuspended(Path sourcePath, Path targetPath, Long libraryId, Supplier<T> operation) {
|
||||
// Extract parent directories since we monitor directories, not individual files
|
||||
Path sourceDir = sourcePath.getParent();
|
||||
Path targetDir = targetPath.getParent();
|
||||
|
||||
// Track which paths we unregister so we can restore them later
|
||||
Set<Path> unregisteredPaths = new HashSet<>();
|
||||
|
||||
try {
|
||||
// Unregister source directory to prevent detection of file removal events
|
||||
if (monitoringRegistrationService.isPathMonitored(sourceDir)) {
|
||||
monitoringRegistrationService.unregisterSpecificPath(sourceDir);
|
||||
unregisteredPaths.add(sourceDir);
|
||||
log.debug("Temporarily unregistered source directory to prevent monitoring conflicts: {}", sourceDir);
|
||||
}
|
||||
|
||||
// Unregister target directory if it's different from source and already exists
|
||||
// This prevents detection of file creation events during the operation
|
||||
if (!sourceDir.equals(targetDir) && Files.exists(targetDir) && monitoringRegistrationService.isPathMonitored(targetDir)) {
|
||||
monitoringRegistrationService.unregisterSpecificPath(targetDir);
|
||||
unregisteredPaths.add(targetDir);
|
||||
log.debug("Temporarily unregistered target directory to prevent monitoring conflicts: {}", targetDir);
|
||||
}
|
||||
|
||||
log.debug("Protected {} directory paths from monitoring during file operation", unregisteredPaths.size());
|
||||
|
||||
// Execute the actual file operation (move, copy, delete, etc.)
|
||||
T result = operation.get();
|
||||
|
||||
// Allow filesystem operations to complete and settle before re-enabling monitoring
|
||||
// This prevents race conditions where monitoring might restart before the operation is fully complete
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("Thread interrupted while waiting for filesystem operations to settle");
|
||||
}
|
||||
|
||||
} finally {
|
||||
// Always restore monitoring, even if the operation failed
|
||||
reregisterPathsAfterMove(unregisteredPaths, libraryId, targetDir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores monitoring registration for paths after a file operation and discovers new directories.
|
||||
*
|
||||
* This method handles the cleanup phase by:
|
||||
* 1. Re-registering previously monitored paths that still exist
|
||||
* 2. Registering new directory structures created by the operation
|
||||
* 3. Ensuring comprehensive monitoring coverage after the operation
|
||||
*
|
||||
* @param unregisteredPaths the set of paths that were temporarily unregistered
|
||||
* @param libraryId the library ID to use for new registrations
|
||||
* @param targetDir the target directory where new structures might have been created
|
||||
*/
|
||||
private void reregisterPathsAfterMove(Set<Path> unregisteredPaths, Long libraryId, Path targetDir) {
|
||||
// Restore monitoring for original paths that still exist after the operation
|
||||
for (Path path : unregisteredPaths) {
|
||||
if (Files.exists(path) && Files.isDirectory(path)) {
|
||||
monitoringRegistrationService.registerSpecificPath(path, libraryId);
|
||||
log.debug("Restored monitoring for existing path: {}", path);
|
||||
} else {
|
||||
log.info("Path no longer exists after operation, skipping re-registration: {}", path);
|
||||
}
|
||||
}
|
||||
|
||||
// Register monitoring for new directory structures created at the target location
|
||||
if (Files.exists(targetDir) && Files.isDirectory(targetDir)) {
|
||||
// Register the target directory itself if it wasn't previously monitored
|
||||
if (!monitoringRegistrationService.isPathMonitored(targetDir)) {
|
||||
monitoringRegistrationService.registerSpecificPath(targetDir, libraryId);
|
||||
log.debug("Registered new target directory for monitoring: {}", targetDir);
|
||||
}
|
||||
|
||||
// Discover and register any new subdirectories created during the operation
|
||||
// This ensures complete monitoring coverage for complex directory structures
|
||||
try (Stream<Path> stream = Files.walk(targetDir)) {
|
||||
stream.filter(Files::isDirectory)
|
||||
.filter(Files::exists)
|
||||
.filter(path -> !path.equals(targetDir)) // Skip the parent directory itself
|
||||
.forEach(path -> {
|
||||
if (!monitoringRegistrationService.isPathMonitored(path)) {
|
||||
monitoringRegistrationService.registerSpecificPath(path, libraryId);
|
||||
log.info("Registered new subdirectory for monitoring: {}", path);
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to scan and register new subdirectories at: {}", targetDir, e);
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("Completed restoration of monitoring after file operation");
|
||||
}
|
||||
}
|
||||
|
||||
-264
@@ -1,264 +0,0 @@
|
||||
package com.adityachandel.booklore.service.file;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class UnifiedFileMoveService {
|
||||
|
||||
private final FileMovingHelper fileMovingHelper;
|
||||
private final MonitoredFileOperationService monitoredFileOperationService;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
private final LibraryRepository libraryRepository;
|
||||
|
||||
/**
|
||||
* Moves a single book file to match the library's file naming pattern.
|
||||
* Used for metadata updates where one file needs to be moved.
|
||||
*/
|
||||
public void moveSingleBookFile(BookEntity bookEntity) {
|
||||
if (bookEntity.getLibraryPath() == null || bookEntity.getLibraryPath().getLibrary() == null) {
|
||||
log.debug("Book ID {} has no library associated. Skipping file move.", bookEntity.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
String pattern = fileMovingHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary());
|
||||
|
||||
if (!fileMovingHelper.hasRequiredPathComponents(bookEntity)) {
|
||||
log.debug("Missing required path components for book ID {}. Skipping file move.", bookEntity.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
Path currentFilePath = bookEntity.getFullFilePath();
|
||||
Path expectedFilePath = fileMovingHelper.generateNewFilePath(bookEntity, pattern);
|
||||
|
||||
// Check if current path differs from expected pattern
|
||||
if (currentFilePath.equals(expectedFilePath)) {
|
||||
log.debug("File for book ID {} is already in the correct location according to library pattern. No move needed.", bookEntity.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("File for book ID {} needs to be moved from {} to {} to match library pattern",
|
||||
bookEntity.getId(), currentFilePath, expectedFilePath);
|
||||
|
||||
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
|
||||
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath())
|
||||
.toAbsolutePath().normalize();
|
||||
|
||||
// unregister the entire library to suppress all watch events during the move
|
||||
monitoringRegistrationService.unregisterLibrary(libraryId);
|
||||
|
||||
try {
|
||||
monitoredFileOperationService.executeWithMonitoringSuspended(
|
||||
currentFilePath, expectedFilePath, libraryId, () -> {
|
||||
try {
|
||||
boolean moved = fileMovingHelper.moveBookFileIfNeeded(bookEntity, pattern);
|
||||
if (moved) {
|
||||
log.info("Successfully moved file for book ID {} from {} to {}",
|
||||
bookEntity.getId(), currentFilePath, bookEntity.getFullFilePath());
|
||||
}
|
||||
return moved;
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
|
||||
throw new RuntimeException("File move failed", e);
|
||||
}
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
// re-register all folders under the library after the move
|
||||
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves multiple book files in batches with cross-library support and library-level monitoring protection.
|
||||
* Used for bulk file operations where many files need to be moved, potentially across libraries.
|
||||
*/
|
||||
public void moveBatchBookFiles(List<BookEntity> books, Map<Long, Long> bookToTargetLibraryMap, BatchMoveCallback callback) {
|
||||
if (books.isEmpty()) {
|
||||
log.debug("No books to move");
|
||||
return;
|
||||
}
|
||||
|
||||
Set<Long> allLibraryIds = new HashSet<>();
|
||||
Map<Long, Set<Path>> libraryToRootsMap = new HashMap<>();
|
||||
|
||||
// Collect library information for monitoring protection
|
||||
for (BookEntity book : books) {
|
||||
if (book.getMetadata() == null) continue;
|
||||
if (!fileMovingHelper.hasRequiredPathComponents(book)) continue;
|
||||
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
if (!Files.exists(oldFilePath)) continue;
|
||||
|
||||
// Source library
|
||||
Long sourceLibraryId = book.getLibraryPath().getLibrary().getId();
|
||||
Path sourceLibraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
libraryToRootsMap.computeIfAbsent(sourceLibraryId, k -> new HashSet<>()).add(sourceLibraryRoot);
|
||||
allLibraryIds.add(sourceLibraryId);
|
||||
|
||||
// Target library (if different)
|
||||
Long targetLibraryId = bookToTargetLibraryMap.get(book.getId());
|
||||
if (targetLibraryId != null && !targetLibraryId.equals(sourceLibraryId)) {
|
||||
LibraryEntity targetLibrary = libraryRepository.findById(targetLibraryId).orElse(null);
|
||||
if (targetLibrary != null && targetLibrary.getLibraryPaths() != null && !targetLibrary.getLibraryPaths().isEmpty()) {
|
||||
Path targetLibraryRoot = Paths.get(targetLibrary.getLibraryPaths().getFirst().getPath()).toAbsolutePath().normalize();
|
||||
libraryToRootsMap.computeIfAbsent(targetLibraryId, k -> new HashSet<>()).add(targetLibraryRoot);
|
||||
allLibraryIds.add(targetLibraryId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Unregister all affected libraries for batch operation
|
||||
unregisterLibrariesBatch(libraryToRootsMap);
|
||||
|
||||
try {
|
||||
// Small delay to let any pending file watcher events settle
|
||||
try {
|
||||
Thread.sleep(500);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("Interrupted during pre-move delay");
|
||||
}
|
||||
|
||||
// Process each book
|
||||
for (BookEntity book : books) {
|
||||
if (book.getMetadata() == null) continue;
|
||||
if (!fileMovingHelper.hasRequiredPathComponents(book)) continue;
|
||||
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
if (!Files.exists(oldFilePath)) {
|
||||
log.warn("File not found for book {}: {}", book.getId(), oldFilePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
log.debug("Moving book {}: '{}'", book.getId(), book.getMetadata().getTitle());
|
||||
|
||||
try {
|
||||
Long targetLibraryId = bookToTargetLibraryMap.get(book.getId());
|
||||
boolean moved = false;
|
||||
|
||||
if (targetLibraryId != null && !targetLibraryId.equals(book.getLibraryPath().getLibrary().getId())) {
|
||||
// Cross-library move
|
||||
LibraryEntity targetLibrary = libraryRepository.findById(targetLibraryId).orElse(null);
|
||||
if (targetLibrary != null) {
|
||||
moved = fileMovingHelper.moveBookFileToLibrary(book, targetLibrary);
|
||||
if (moved) {
|
||||
log.debug("Book {} moved to library {} successfully", book.getId(), targetLibraryId);
|
||||
}
|
||||
} else {
|
||||
log.error("Target library {} not found for book {}", targetLibraryId, book.getId());
|
||||
callback.onBookMoveFailed(book, new RuntimeException("Target library not found"));
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// Same library move (existing functionality)
|
||||
String pattern = fileMovingHelper.getFileNamingPattern(book.getLibraryPath().getLibrary());
|
||||
moved = fileMovingHelper.moveBookFileIfNeeded(book, pattern);
|
||||
if (moved) {
|
||||
log.debug("Book {} moved within library successfully", book.getId());
|
||||
}
|
||||
}
|
||||
|
||||
if (moved) {
|
||||
callback.onBookMoved(book);
|
||||
|
||||
// Move additional files if any
|
||||
if (book.getAdditionalFiles() != null && !book.getAdditionalFiles().isEmpty()) {
|
||||
String pattern = fileMovingHelper.getFileNamingPattern(book.getLibraryPath().getLibrary());
|
||||
fileMovingHelper.moveAdditionalFiles(book, pattern);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Move failed for book {}: {}", book.getId(), e.getMessage(), e);
|
||||
callback.onBookMoveFailed(book, e);
|
||||
}
|
||||
}
|
||||
|
||||
// Longer delay to let filesystem operations settle before re-registering monitoring
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("Interrupted during batch move delay");
|
||||
}
|
||||
|
||||
} finally {
|
||||
// Re-register all affected libraries
|
||||
registerLibrariesBatch(libraryToRootsMap);
|
||||
}
|
||||
}
|
||||
|
||||
// Overloaded method for backward compatibility with same-library moves
|
||||
public void moveBatchBookFiles(List<BookEntity> books, BatchMoveCallback callback) {
|
||||
moveBatchBookFiles(books, new HashMap<>(), callback);
|
||||
}
|
||||
|
||||
private void unregisterLibrariesBatch(Map<Long, Set<Path>> libraryToRootsMap) {
|
||||
log.debug("Unregistering {} libraries for batch move", libraryToRootsMap.size());
|
||||
|
||||
for (Map.Entry<Long, Set<Path>> entry : libraryToRootsMap.entrySet()) {
|
||||
Long libraryId = entry.getKey();
|
||||
try {
|
||||
monitoringRegistrationService.unregisterLibrary(libraryId);
|
||||
log.debug("Unregistered library {}", libraryId);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to unregister library {}: {}", libraryId, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void registerLibrariesBatch(Map<Long, Set<Path>> libraryToRootsMap) {
|
||||
log.debug("Re-registering {} libraries after batch move", libraryToRootsMap.size());
|
||||
|
||||
for (Map.Entry<Long, Set<Path>> entry : libraryToRootsMap.entrySet()) {
|
||||
Long libraryId = entry.getKey();
|
||||
Set<Path> libraryRoots = entry.getValue();
|
||||
|
||||
// Verify library still exists before re-registering
|
||||
try {
|
||||
LibraryEntity library = libraryRepository.findById(libraryId).orElse(null);
|
||||
if (library == null) {
|
||||
log.warn("Library {} no longer exists, skipping re-registration", libraryId);
|
||||
continue;
|
||||
}
|
||||
|
||||
for (Path libraryRoot : libraryRoots) {
|
||||
if (Files.exists(libraryRoot) && Files.isDirectory(libraryRoot)) {
|
||||
try {
|
||||
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
|
||||
log.debug("Re-registered library {} at {}", libraryId, libraryRoot);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to re-register library {} at {}: {}", libraryId, libraryRoot, e.getMessage());
|
||||
}
|
||||
} else {
|
||||
log.debug("Library root {} no longer exists or is not a directory, skipping re-registration", libraryRoot);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error verifying library {} during re-registration: {}", libraryId, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback interface for batch move operations
|
||||
*/
|
||||
public interface BatchMoveCallback {
|
||||
void onBookMoved(BookEntity book);
|
||||
|
||||
void onBookMoveFailed(BookEntity book, Exception error);
|
||||
}
|
||||
}
|
||||
+10
-26
@@ -4,6 +4,7 @@ import com.adityachandel.booklore.model.MetadataClearFlags;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateContext;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.FileMoveResult;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
@@ -15,7 +16,7 @@ import com.adityachandel.booklore.repository.MoodRepository;
|
||||
import com.adityachandel.booklore.repository.TagRepository;
|
||||
import com.adityachandel.booklore.service.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.file.UnifiedFileMoveService;
|
||||
import com.adityachandel.booklore.service.file.FileMoveService;
|
||||
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.MetadataChangeDetector;
|
||||
@@ -52,7 +53,7 @@ public class BookMetadataUpdater {
|
||||
private final AppSettingService appSettingService;
|
||||
private final MetadataWriterFactory metadataWriterFactory;
|
||||
private final BookReviewUpdateService bookReviewUpdateService;
|
||||
private final UnifiedFileMoveService unifiedFileMoveService;
|
||||
private final FileMoveService fileMoveService;
|
||||
|
||||
@Transactional
|
||||
public void setBookMetadata(MetadataUpdateContext context) {
|
||||
@@ -117,34 +118,13 @@ public class BookMetadataUpdater {
|
||||
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
|
||||
try {
|
||||
String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null;
|
||||
|
||||
if ((StringUtils.hasText(thumbnailUrl) && isLocalOrPrivateUrl(thumbnailUrl) || Boolean.TRUE.equals(metadata.getCoverLocked()))) {
|
||||
log.debug("Blocked local/private thumbnail URL: {}", thumbnailUrl);
|
||||
thumbnailUrl = null;
|
||||
}
|
||||
|
||||
File file = new File(bookEntity.getFullFilePath().toUri());
|
||||
writer.writeMetadataToFile(file, metadata, thumbnailUrl, clearFlags);
|
||||
|
||||
String newHash;
|
||||
|
||||
// Special handling: If original file was .cbr or .cb7 and now .cbz exists, update to .cbz
|
||||
File resultingFile = file;
|
||||
if (!file.exists()) {
|
||||
// Replace last extension .cbr or .cb7 (case-insensitive) with .cbz
|
||||
String cbzName = file.getName().replaceFirst("(?i)\\.(cbr|cb7)$", ".cbz");
|
||||
File cbzFile = new File(file.getParentFile(), cbzName);
|
||||
if (cbzFile.exists()) {
|
||||
bookEntity.setFileName(cbzName);
|
||||
resultingFile = cbzFile;
|
||||
}
|
||||
bookEntity.setFileSizeKb(resultingFile.length() / 1024);
|
||||
log.info("Converted to CBZ: {} -> {}", file.getAbsolutePath(), resultingFile.getAbsolutePath());
|
||||
newHash = FileFingerprint.generateHash(resultingFile.toPath());
|
||||
} else {
|
||||
newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
|
||||
}
|
||||
|
||||
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
|
||||
bookEntity.setCurrentHash(newHash);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage());
|
||||
@@ -156,14 +136,18 @@ public class BookMetadataUpdater {
|
||||
boolean moveFilesToLibraryPattern = settings.isMoveFilesToLibraryPattern();
|
||||
if (moveFilesToLibraryPattern) {
|
||||
try {
|
||||
unifiedFileMoveService.moveSingleBookFile(bookEntity);
|
||||
BookEntity book = metadata.getBook();
|
||||
FileMoveResult result = fileMoveService.moveSingleFile(book);
|
||||
if (result.isMoved()) {
|
||||
book.setFileName(result.getNewFileName());
|
||||
book.setFileSubPath(result.getNewFileSubPath());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to move files for book ID {} after metadata update: {}", bookId, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void updateBasicFields(BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, MetadataReplaceMode replaceMode) {
|
||||
handleFieldUpdate(e.getTitleLocked(), clear.isTitle(), m.getTitle(), v -> e.setTitle(nullIfBlank(v)), e::getTitle, replaceMode);
|
||||
handleFieldUpdate(e.getSubtitleLocked(), clear.isSubtitle(), m.getSubtitle(), v -> e.setSubtitle(nullIfBlank(v)), e::getSubtitle, replaceMode);
|
||||
|
||||
+13
-13
@@ -1,20 +1,13 @@
|
||||
package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.FileMoveResult;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||
import com.adityachandel.booklore.model.entity.MoodEntity;
|
||||
import com.adityachandel.booklore.model.entity.TagEntity;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.MergeMetadataType;
|
||||
import com.adityachandel.booklore.repository.AuthorRepository;
|
||||
import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.CategoryRepository;
|
||||
import com.adityachandel.booklore.repository.MoodRepository;
|
||||
import com.adityachandel.booklore.repository.TagRepository;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.file.UnifiedFileMoveService;
|
||||
import com.adityachandel.booklore.service.file.FileMoveService;
|
||||
import com.adityachandel.booklore.service.metadata.writer.MetadataWriter;
|
||||
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -38,7 +31,8 @@ public class MetadataManagementService {
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
private final MetadataWriterFactory metadataWriterFactory;
|
||||
private final UnifiedFileMoveService unifiedFileMoveService;
|
||||
private final FileMoveService fileMoveService;
|
||||
private final BookRepository bookRepository;
|
||||
|
||||
|
||||
@Transactional
|
||||
@@ -70,7 +64,13 @@ public class MetadataManagementService {
|
||||
});
|
||||
|
||||
if (moveFile) {
|
||||
unifiedFileMoveService.moveSingleBookFile(metadata.getBook());
|
||||
BookEntity book = metadata.getBook();
|
||||
FileMoveResult result = fileMoveService.moveSingleFile(book);
|
||||
if (result.isMoved()) {
|
||||
book.setFileName(result.getNewFileName());
|
||||
book.setFileSubPath(result.getNewFileSubPath());
|
||||
bookRepository.saveAndFlush(book);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -282,7 +282,7 @@ public class MetadataRefreshService {
|
||||
.build())
|
||||
.updateThumbnail(replaceCover)
|
||||
.mergeCategories(mergeCategories)
|
||||
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
|
||||
.replaceMode(MetadataReplaceMode.REPLACE_MISSING)
|
||||
.build();
|
||||
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
+21
-33
@@ -1,11 +1,14 @@
|
||||
package com.adityachandel.booklore.service.monitoring;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Library;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -14,55 +17,26 @@ public class MonitoringRegistrationService {
|
||||
|
||||
private final MonitoringService monitoringService;
|
||||
|
||||
|
||||
/**
|
||||
* Checks if a specific path is currently being monitored.
|
||||
*
|
||||
* @param path the path to check
|
||||
* @return true if the path is monitored
|
||||
*/
|
||||
public boolean isPathMonitored(Path path) {
|
||||
return monitoringService.isPathMonitored(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters a specific path from monitoring without affecting other paths.
|
||||
* This is more efficient than pausing all monitoring for single path operations.
|
||||
*
|
||||
* @param path the path to unregister
|
||||
*/
|
||||
public void unregisterSpecificPath(Path path) {
|
||||
monitoringService.unregisterPath(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a specific path for monitoring.
|
||||
*
|
||||
* @param path the path to register
|
||||
* @param libraryId the library ID associated with this path
|
||||
*/
|
||||
public void registerSpecificPath(Path path, Long libraryId) {
|
||||
monitoringService.registerPath(path, libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters an entire library from monitoring.
|
||||
* This is more efficient for batch operations than unregistering individual paths.
|
||||
*
|
||||
* @param libraryId the library ID to unregister
|
||||
*/
|
||||
public void registerLibrary(Library library) {
|
||||
monitoringService.registerLibrary(library);
|
||||
}
|
||||
|
||||
public void unregisterLibrary(Long libraryId) {
|
||||
monitoringService.unregisterLibrary(libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-registers an entire library for monitoring after batch operations.
|
||||
* Since MonitoringService.registerLibrary() requires a Library object,
|
||||
* this method will register individual paths under the library instead.
|
||||
*
|
||||
* @param libraryId the library ID to register
|
||||
* @param libraryRoot the root path of the library
|
||||
*/
|
||||
public void registerLibraryPaths(Long libraryId, Path libraryRoot) {
|
||||
if (!Files.exists(libraryRoot) || !Files.isDirectory(libraryRoot)) {
|
||||
return;
|
||||
@@ -78,4 +52,18 @@ public class MonitoringRegistrationService {
|
||||
log.error("Failed to register library paths for libraryId {} at {}", libraryId, libraryRoot, e);
|
||||
}
|
||||
}
|
||||
|
||||
public void registerLibraries(Map<Long, Path> libraries) {
|
||||
if (libraries == null || libraries.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
libraries.forEach(this::registerLibraryPaths);
|
||||
}
|
||||
|
||||
public void unregisterLibraries(Collection<Long> libraryIds) {
|
||||
if (libraryIds == null || libraryIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
libraryIds.forEach(this::unregisterLibrary);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user