Add auto-move option on metadata update and simplify file monitoring (#1137)

- Introduce option to automatically move books when their metadata is updated
- Simplify the file monitoring workflow for improved reliability and clarity
This commit is contained in:
Aditya Chandel
2025-09-12 11:59:36 -06:00
committed by GitHub
parent 7adc2b3f57
commit 6ea2eb58bc
47 changed files with 3749 additions and 2942 deletions
@@ -22,11 +22,12 @@ public class FileUploadController {
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canUpload()")
@PostMapping(value = "/upload", consumes = "multipart/form-data")
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) throws IOException {
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) throws IOException {
if (file.isEmpty()) {
throw new IllegalArgumentException("Uploaded file is missing.");
}
return ResponseEntity.ok(fileUploadService.uploadFile(file, libraryId, pathId));
fileUploadService.uploadFile(file, libraryId, pathId);
return ResponseEntity.noContent().build();
}
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canUpload()")
@@ -14,4 +14,5 @@ public class MetadataPersistenceSettings {
private boolean convertCbrCb7ToCbz;
private boolean backupMetadata;
private boolean backupCover;
private boolean moveFilesToLibraryPattern;
}
@@ -22,6 +22,8 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
Optional<BookEntity> findByCurrentHash(String currentHash);
Optional<BookEntity> findByCurrentHashAndDeletedTrue(String currentHash);
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
Set<Long> findBookIdsByLibraryId(@Param("libraryId") long libraryId);
@@ -47,6 +49,10 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds);
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findWithMetadataByIdsWithPagination(@Param("bookIds") Set<Long> bookIds, Pageable pageable);
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByLibraryId(@Param("libraryId") Long libraryId);
@@ -32,3 +32,4 @@ public interface BookdropFileRepository extends JpaRepository<BookdropFileEntity
@Query("SELECT f.id FROM BookdropFileEntity f WHERE f.id NOT IN :excludedIds")
List<Long> findAllExcludingIdsFlat(@Param("excludedIds") List<Long> excludedIds);
}
@@ -1,15 +1,11 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.AdditionalFileMapper;
import com.adityachandel.booklore.model.dto.AdditionalFile;
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.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
@@ -19,19 +15,11 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
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.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Slf4j
@@ -41,7 +29,7 @@ public class AdditionalFileService {
private final BookAdditionalFileRepository additionalFileRepository;
private final AdditionalFileMapper additionalFileMapper;
private final MonitoringProtectionService monitoringProtectionService;
private final MonitoringRegistrationService monitoringRegistrationService;
public List<AdditionalFile> getAdditionalFilesByBookId(Long bookId) {
List<BookAdditionalFileEntity> entities = additionalFileRepository.findByBookId(bookId);
@@ -61,21 +49,18 @@ public class AdditionalFileService {
}
BookAdditionalFileEntity file = fileOpt.get();
monitoringProtectionService.executeWithProtection(() -> {
try {
// Delete physical file
Files.deleteIfExists(file.getFullFilePath());
log.info("Deleted additional file: {}", file.getFullFilePath());
// Delete database record
additionalFileRepository.delete(file);
} catch (IOException e) {
log.warn("Failed to delete physical file: {}", file.getFullFilePath(), e);
// Still delete the database record even if file deletion fails
additionalFileRepository.delete(file);
}
}, "additional file deletion");
try {
monitoringRegistrationService.unregisterSpecificPath(file.getFullFilePath().getParent());
Files.deleteIfExists(file.getFullFilePath());
log.info("Deleted additional file: {}", file.getFullFilePath());
additionalFileRepository.delete(file);
} catch (IOException e) {
log.warn("Failed to delete physical file: {}", file.getFullFilePath(), e);
additionalFileRepository.delete(file);
}
}
public ResponseEntity<Resource> downloadAdditionalFile(Long fileId) throws IOException {
@@ -98,5 +83,4 @@ public class AdditionalFileService {
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
.body(resource);
}
}
@@ -5,6 +5,8 @@ import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.BookRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
@@ -114,6 +116,11 @@ public class BookQueryService {
return bookRepository.findAllWithMetadataByIds(bookIds);
}
public List<BookEntity> findWithMetadataByIdsWithPagination(Set<Long> bookIds, int offset, int limit) {
Pageable pageable = PageRequest.of(offset / limit, limit);
return bookRepository.findWithMetadataByIdsWithPagination(bookIds, pageable);
}
public List<BookEntity> getAllFullBookEntities() {
return bookRepository.findAllFullBooks();
}
@@ -15,7 +15,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
@@ -59,7 +59,7 @@ public class BookService {
private final BookQueryService bookQueryService;
private final UserProgressService userProgressService;
private final BookDownloadService bookDownloadService;
private final MonitoringProtectionService monitoringProtectionService;
private final MonitoringRegistrationService monitoringRegistrationService;
private void setBookProgress(Book book, UserBookProgressEntity progress) {
@@ -468,8 +468,7 @@ public class BookService {
if (Files.exists(coverPath)) {
return new UrlResource(coverPath.toUri());
} else {
Path defaultCover = Paths.get("static/images/missing-cover.jpg");
return new UrlResource(defaultCover.toUri());
return new ClassPathResource("static/images/missing-cover.jpg");
}
} catch (MalformedURLException e) {
throw new RuntimeException("Failed to load book cover for bookId=" + bookId, e);
@@ -504,35 +503,33 @@ public class BookService {
public ResponseEntity<BookDeletionResponse> deleteBooks(Set<Long> ids) {
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(ids);
List<Long> failedFileDeletions = new ArrayList<>();
for (BookEntity book : books) {
Path fullFilePath = book.getFullFilePath();
try {
if (Files.exists(fullFilePath)) {
monitoringRegistrationService.unregisterSpecificPath(fullFilePath.getParent());
Files.delete(fullFilePath);
log.info("Deleted book file: {}", fullFilePath);
return monitoringProtectionService.executeWithProtection(() -> {
for (BookEntity book : books) {
Path fullFilePath = book.getFullFilePath();
try {
if (Files.exists(fullFilePath)) {
Files.delete(fullFilePath);
log.info("Deleted book file: {}", fullFilePath);
Set<Path> libraryRoots = book.getLibrary().getLibraryPaths().stream()
.map(LibraryPathEntity::getPath)
.map(Paths::get)
.map(Path::normalize)
.collect(Collectors.toSet());
Set<Path> libraryRoots = book.getLibrary().getLibraryPaths().stream()
.map(LibraryPathEntity::getPath)
.map(Paths::get)
.map(Path::normalize)
.collect(Collectors.toSet());
deleteEmptyParentDirsUpToLibraryFolders(fullFilePath.getParent(), libraryRoots);
}
} catch (IOException e) {
log.warn("Failed to delete book file: {}", fullFilePath, e);
failedFileDeletions.add(book.getId());
deleteEmptyParentDirsUpToLibraryFolders(fullFilePath.getParent(), libraryRoots);
}
} catch (IOException e) {
log.warn("Failed to delete book file: {}", fullFilePath, e);
failedFileDeletions.add(book.getId());
}
}
bookRepository.deleteAll(books);
BookDeletionResponse response = new BookDeletionResponse(ids, failedFileDeletions);
return failedFileDeletions.isEmpty()
? ResponseEntity.ok(response)
: ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response);
}, "book deletion");
bookRepository.deleteAll(books);
BookDeletionResponse response = new BookDeletionResponse(ids, failedFileDeletions);
return failedFileDeletions.isEmpty()
? ResponseEntity.ok(response)
: ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response);
}
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
@@ -186,6 +186,7 @@ public class SettingPersistenceHelper {
.convertCbrCb7ToCbz(false)
.backupMetadata(false)
.backupCover(false)
.moveFilesToLibraryPattern(false)
.build();
}
@@ -4,7 +4,6 @@ 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;
import com.adityachandel.booklore.model.dto.BookdropFileNotification;
@@ -23,17 +22,14 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.BookdropFileRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.file.FileMovingHelper;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.util.PathPatternResolver;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
@@ -45,6 +41,7 @@ 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.time.Instant;
import java.util.Comparator;
import java.util.List;
@@ -63,7 +60,6 @@ public class BookDropService {
private final BookdropFileRepository bookdropFileRepository;
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final MonitoringProtectionService monitoringProtectionService;
private final BookdropMonitoringService bookdropMonitoringService;
private final NotificationService notificationService;
private final MetadataRefreshService metadataRefreshService;
@@ -72,7 +68,9 @@ public class BookDropService {
private final AppProperties appProperties;
private final BookdropFileMapper mapper;
private final ObjectMapper objectMapper;
AppSettingService appSettingService;
private final FileMovingHelper fileMovingHelper;
private static final int CHUNK_SIZE = 100;
public BookdropFileNotification getFileNotificationSummary() {
long pendingCount = bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW);
@@ -88,140 +86,169 @@ public class BookDropService {
}
}
public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) {
return monitoringProtectionService.executeWithProtection(() -> {
try {
bookdropMonitoringService.pauseMonitoring();
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
.processedAt(Instant.now())
.build();
Long defaultLibraryId = request.getDefaultLibraryId();
Long defaultPathId = request.getDefaultPathId();
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.collect(Collectors.toMap(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId, Function.identity()));
final int CHUNK_SIZE = 100;
AtomicInteger failedCount = new AtomicInteger();
AtomicInteger totalFilesProcessed = new AtomicInteger();
log.info("Starting finalizeImport: selectAll={}, provided file count={}, defaultLibraryId={}, defaultPathId={}",
request.getSelectAll(), metadataById.size(), defaultLibraryId, defaultPathId);
if (Boolean.TRUE.equals(request.getSelectAll())) {
List<Long> excludedIds = Optional.ofNullable(request.getExcludedIds()).orElse(List.of());
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds);
log.info("SelectAll: Total files to finalize (after exclusions): {}, Excluded IDs: {}", allIds.size(), excludedIds);
for (int i = 0; i < allIds.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, allIds.size());
List<Long> chunk = allIds.subList(i, end);
log.info("Processing chunk {}/{} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) allIds.size() / CHUNK_SIZE), chunk.size(), chunk);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunk);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
for (Long id : chunk) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.warn("File ID {} missing in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
} else {
List<Long> ids = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.map(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId)
.toList();
log.info("Processing {} manually selected files in chunks of {}. File IDs: {}", ids.size(), CHUNK_SIZE, ids);
for (int i = 0; i < ids.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, ids.size());
List<Long> chunkIds = ids.subList(i, end);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunkIds);
log.info("Processing chunk {} of {} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) ids.size() / CHUNK_SIZE), chunkFiles.size(), chunkIds);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream()
.collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
for (Long id : chunkIds) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.error("File ID {} not found in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
}
results.setTotalFiles(totalFilesProcessed.get());
results.setFailed(failedCount.get());
results.setSuccessfullyImported(totalFilesProcessed.get() - failedCount.get());
log.info("Finalization complete. Success: {}, Failed: {}, Total processed: {}",
results.getSuccessfullyImported(),
results.getFailed(),
results.getTotalFiles());
return results;
} finally {
bookdropMonitoringService.resumeMonitoring();
}
}, "bookdrop finalize import");
public Resource getBookdropCover(long bookdropId) {
String coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropId + ".jpg").toString();
File coverFile = new File(coverPath);
if (coverFile.exists() && coverFile.isFile()) {
return new PathResource(coverFile.toPath());
} else {
return null;
}
}
private void processFile(
BookdropFileEntity fileEntity,
BookdropFinalizeRequest.BookdropFinalizeFile fileReq,
Long defaultLibraryId,
Long defaultPathId,
BookdropFinalizeResult results,
AtomicInteger failedCount
) {
public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) {
try {
Long libraryId;
Long pathId;
BookMetadata metadata;
bookdropMonitoringService.pauseMonitoring();
return processFinalizationRequest(request);
} finally {
bookdropMonitoringService.resumeMonitoring();
log.info("Bookdrop monitoring resumed");
}
}
if (fileReq != null) {
libraryId = fileReq.getLibraryId() != null ? fileReq.getLibraryId() : defaultLibraryId;
pathId = fileReq.getPathId() != null ? fileReq.getPathId() : defaultPathId;
metadata = fileReq.getMetadata();
log.debug("Processing fileId={}, fileName={} with provided metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
} else {
if (defaultLibraryId == null || defaultPathId == null) {
log.warn("Missing default metadata for fileId={}", fileEntity.getId());
throw ApiError.GENERIC_BAD_REQUEST.createException("Missing metadata and defaults for fileId=" + fileEntity.getId());
}
public void discardSelectedFiles(boolean selectAll, List<Long> excludedIds, List<Long> selectedIds) {
bookdropMonitoringService.pauseMonitoring();
Path bookdropPath = Path.of(appProperties.getBookdropFolder());
metadata = fileEntity.getFetchedMetadata() != null
? objectMapper.readValue(fileEntity.getFetchedMetadata(), BookMetadata.class)
: objectMapper.readValue(fileEntity.getOriginalMetadata(), BookMetadata.class);
AtomicInteger deletedFiles = new AtomicInteger();
AtomicInteger deletedDirs = new AtomicInteger();
AtomicInteger deletedCovers = new AtomicInteger();
libraryId = defaultLibraryId;
pathId = defaultPathId;
log.debug("Processing fileId={}, fileName={} with default metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
try {
if (!Files.exists(bookdropPath)) {
log.info("Bookdrop folder does not exist: {}", bookdropPath);
return;
}
BookdropFileResult result = moveFile(libraryId, pathId, metadata, fileEntity);
List<BookdropFileEntity> filesToDelete = getFilesToDelete(selectAll, excludedIds, selectedIds);
deleteFilesAndCovers(filesToDelete, deletedFiles, deletedCovers);
deleteEmptyDirectories(bookdropPath, deletedDirs);
bookdropFileRepository.deleteAllById(filesToDelete.stream().map(BookdropFileEntity::getId).toList());
log.info("Deleted {} bookdrop DB entries", filesToDelete.size());
bookdropNotificationService.sendBookdropFileSummaryNotification();
log.info("Bookdrop cleanup summary: deleted {} files, {} folders, {} DB entries, {} covers",
deletedFiles.get(), deletedDirs.get(), filesToDelete.size(), deletedCovers.get());
} finally {
bookdropMonitoringService.resumeMonitoring();
log.info("Bookdrop monitoring resumed after cleanup (library monitoring unaffected)");
}
}
private BookdropFinalizeResult processFinalizationRequest(BookdropFinalizeRequest request) {
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
.processedAt(Instant.now())
.build();
Long defaultLibraryId = request.getDefaultLibraryId();
Long defaultPathId = request.getDefaultPathId();
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById = getMetadataMap(request);
AtomicInteger failedCount = new AtomicInteger();
AtomicInteger totalFilesProcessed = new AtomicInteger();
log.info("Starting finalizeImport: selectAll={}, provided file count={}, defaultLibraryId={}, defaultPathId={}", request.getSelectAll(), metadataById.size(), defaultLibraryId, defaultPathId);
if (Boolean.TRUE.equals(request.getSelectAll())) {
processAllFiles(request, metadataById, defaultLibraryId, defaultPathId, results, failedCount, totalFilesProcessed);
} else {
processSelectedFiles(request, metadataById, defaultLibraryId, defaultPathId, results, failedCount, totalFilesProcessed);
}
updateFinalResults(results, totalFilesProcessed, failedCount);
return results;
}
private Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> getMetadataMap(BookdropFinalizeRequest request) {
return Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.collect(Collectors.toMap(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId, Function.identity()));
}
private void processAllFiles(BookdropFinalizeRequest request,
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById,
Long defaultLibraryId,
Long defaultPathId,
BookdropFinalizeResult results,
AtomicInteger failedCount,
AtomicInteger totalFilesProcessed) {
List<Long> excludedIds = Optional.ofNullable(request.getExcludedIds()).orElse(List.of());
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds);
log.info("SelectAll: Total files to finalize (after exclusions): {}, Excluded IDs: {}", allIds.size(), excludedIds);
processFileChunks(allIds, metadataById, defaultLibraryId, defaultPathId, results, failedCount, totalFilesProcessed);
}
private void processSelectedFiles(BookdropFinalizeRequest request,
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById,
Long defaultLibraryId,
Long defaultPathId,
BookdropFinalizeResult results,
AtomicInteger failedCount,
AtomicInteger totalFilesProcessed) {
List<Long> ids = Optional.ofNullable(request.getFiles())
.orElse(List.of())
.stream()
.map(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId)
.toList();
log.info("Processing {} manually selected files in chunks of {}. File IDs: {}", ids.size(), CHUNK_SIZE, ids);
processFileChunks(ids, metadataById, defaultLibraryId, defaultPathId, results, failedCount, totalFilesProcessed);
}
private void processFileChunks(List<Long> ids,
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById,
Long defaultLibraryId,
Long defaultPathId,
BookdropFinalizeResult results,
AtomicInteger failedCount,
AtomicInteger totalFilesProcessed) {
for (int i = 0; i < ids.size(); i += CHUNK_SIZE) {
int end = Math.min(i + CHUNK_SIZE, ids.size());
List<Long> chunk = ids.subList(i, end);
log.info("Processing chunk {}/{} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) ids.size() / CHUNK_SIZE), chunk.size(), chunk);
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunk);
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
for (Long id : chunk) {
BookdropFileEntity file = fileMap.get(id);
if (file == null) {
log.warn("File ID {} missing in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
}
private void updateFinalResults(BookdropFinalizeResult results, AtomicInteger totalFilesProcessed, AtomicInteger failedCount) {
results.setTotalFiles(totalFilesProcessed.get());
results.setFailed(failedCount.get());
results.setSuccessfullyImported(totalFilesProcessed.get() - failedCount.get());
log.info("Finalization complete. Success: {}, Failed: {}, Total processed: {}",
results.getSuccessfullyImported(),
results.getFailed(),
results.getTotalFiles());
}
private void processFile(BookdropFileEntity fileEntity,
BookdropFinalizeRequest.BookdropFinalizeFile fileReq,
Long defaultLibraryId,
Long defaultPathId,
BookdropFinalizeResult results,
AtomicInteger failedCount) {
try {
FileProcessingContext context = prepareFileProcessingContext(fileEntity, fileReq, defaultLibraryId, defaultPathId);
BookdropFileResult result = moveFile(context.libraryId, context.pathId, context.metadata, fileEntity);
results.getResults().add(result);
if (!result.isSuccess()) {
@@ -239,7 +266,38 @@ public class BookDropService {
}
}
private BookdropFileResult moveFile(long libraryId, long pathId, BookMetadata metadata, BookdropFileEntity bookdropFile) throws Exception {
private FileProcessingContext prepareFileProcessingContext(BookdropFileEntity fileEntity,
BookdropFinalizeRequest.BookdropFinalizeFile fileReq,
Long defaultLibraryId,
Long defaultPathId) throws Exception {
Long libraryId;
Long pathId;
BookMetadata metadata;
if (fileReq != null) {
libraryId = fileReq.getLibraryId() != null ? fileReq.getLibraryId() : defaultLibraryId;
pathId = fileReq.getPathId() != null ? fileReq.getPathId() : defaultPathId;
metadata = fileReq.getMetadata();
log.debug("Processing fileId={}, fileName={} with provided metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
} else {
if (defaultLibraryId == null || defaultPathId == null) {
log.warn("Missing default metadata for fileId={}", fileEntity.getId());
throw ApiError.GENERIC_BAD_REQUEST.createException("Missing metadata and defaults for fileId=" + fileEntity.getId());
}
metadata = fileEntity.getFetchedMetadata() != null
? objectMapper.readValue(fileEntity.getFetchedMetadata(), BookMetadata.class)
: objectMapper.readValue(fileEntity.getOriginalMetadata(), BookMetadata.class);
libraryId = defaultLibraryId;
pathId = defaultPathId;
log.debug("Processing fileId={}, fileName={} with default metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
}
return new FileProcessingContext(libraryId, pathId, metadata);
}
private BookdropFileResult moveFile(long libraryId, long pathId, BookMetadata metadata, BookdropFileEntity bookdropFile) {
LibraryEntity library = libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
@@ -248,22 +306,12 @@ public class BookDropService {
.findFirst()
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
String filePattern = library.getFileNamingPattern();
if (filePattern == null || filePattern.isBlank()) {
filePattern = appSettingService.getAppSettings().getUploadPattern();
}
if (filePattern.endsWith("/") || filePattern.endsWith("\\")) {
filePattern += "{currentFilename}";
}
String relativePath = PathPatternResolver.resolvePattern(metadata, filePattern, FilenameUtils.getName(bookdropFile.getFilePath()));
String filePattern = fileMovingHelper.getFileNamingPattern(library);
Path source = Path.of(bookdropFile.getFilePath());
Path target = Paths.get(path.getPath(), relativePath);
Path target = fileMovingHelper.generateNewFilePath(path.getPath(), metadata, filePattern, bookdropFile.getFilePath());
File targetFile = target.toFile();
log.debug("Preparing to move file id={}, name={}, source={}, target={}, library={}, path={}",
bookdropFile.getId(), bookdropFile.getFileName(), source, target, library.getName(), path.getPath());
log.debug("Preparing to move file id={}, name={}, source={}, target={}, library={}, path={}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, library.getName(), path.getPath());
if (!Files.exists(source)) {
bookdropFileRepository.deleteById(bookdropFile.getId());
@@ -277,64 +325,93 @@ public class BookDropService {
return failureResult(targetFile.getName(), "File already exists in the library '" + library.getName() + "'");
}
return monitoringProtectionService.executeWithProtection(() -> {
try {
Files.createDirectories(target.getParent());
Files.move(source, target);
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
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(fileProcessResult.getBook().getId())
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getStatus());
metadataRefreshService.updateBookMetadata(bookEntity, metadata, metadata.getThumbnailUrl() != null, false);
bookdropFileRepository.deleteById(bookdropFile.getId());
bookdropNotificationService.sendBookdropFileSummaryNotification();
File cachedCover = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFile.getId() + ".jpg").toFile();
if (cachedCover.exists()) {
boolean deleted = cachedCover.delete();
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
}
log.info("File import completed: id={}, name={}, library={}, path={}", bookdropFile.getId(), targetFile.getName(), library.getName(), path.getPath());
return BookdropFileResult.builder()
.fileName(targetFile.getName())
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
.success(true)
.build();
} catch (Exception e) {
log.error("Failed to move file id={}, name={} from '{}' to '{}': {}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, e.getMessage(), e);
try {
if (Files.exists(target)) {
Files.deleteIfExists(target);
log.info("Cleaned up partially created target file: {}", target);
}
} catch (Exception cleanupException) {
log.warn("Failed to cleanup target file after move error: {}", target, cleanupException);
}
return failureResult(bookdropFile.getFileName(), "Failed to move file: " + e.getMessage());
}
}, "bookdrop file move");
return performFileMove(bookdropFile, source, target, library, path, metadata);
}
private BookdropFileResult failureResult(String fileName, String message) {
private BookdropFileResult performFileMove(BookdropFileEntity bookdropFile, Path source, Path target,
LibraryEntity library, LibraryPathEntity path, BookMetadata metadata) {
Path tempPath = null;
try {
tempPath = Files.createTempFile("bookdrop-finalize-", bookdropFile.getFileName());
Files.copy(source, tempPath, StandardCopyOption.REPLACE_EXISTING);
Files.createDirectories(target.getParent());
Files.move(tempPath, target, StandardCopyOption.REPLACE_EXISTING);
Files.deleteIfExists(source);
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
return processMovedFile(bookdropFile, target.toFile(), library, path, metadata);
} catch (Exception e) {
log.error("Failed to move file id={}, name={} from '{}' to '{}': {}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, e.getMessage(), e);
cleanupFailedMove(target);
return failureResult(bookdropFile.getFileName(), "Failed to move file: " + e.getMessage());
} finally {
cleanupTempFile(tempPath);
}
}
private BookdropFileResult processMovedFile(BookdropFileEntity bookdropFile,
File targetFile,
LibraryEntity library,
LibraryPathEntity path,
BookMetadata metadata) throws Exception {
FileProcessResult fileProcessResult = processFileInLibrary(targetFile.getName(), library, path, targetFile,
BookFileExtension.fromFileName(bookdropFile.getFileName())
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
.getType());
BookEntity bookEntity = bookRepository.findById(fileProcessResult.getBook().getId())
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook());
metadataRefreshService.updateBookMetadata(bookEntity, metadata, metadata.getThumbnailUrl() != null, false);
cleanupBookdropData(bookdropFile);
log.info("File import completed: id={}, name={}, library={}, path={}", bookdropFile.getId(), targetFile.getName(), library.getName(), path.getPath());
return BookdropFileResult.builder()
.fileName(fileName)
.message(message)
.success(false)
.fileName(targetFile.getName())
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
.success(true)
.build();
}
private FileProcessResult processFile(String fileName, LibraryEntity library, LibraryPathEntity path, File file, BookFileType type) {
private void cleanupBookdropData(BookdropFileEntity bookdropFile) {
bookdropFileRepository.deleteById(bookdropFile.getId());
bookdropNotificationService.sendBookdropFileSummaryNotification();
File cachedCover = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFile.getId() + ".jpg").toFile();
if (cachedCover.exists()) {
boolean deleted = cachedCover.delete();
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
}
}
private void cleanupFailedMove(Path target) {
try {
if (Files.exists(target)) {
Files.deleteIfExists(target);
log.info("Cleaned up partially created target file: {}", target);
}
} catch (Exception cleanupException) {
log.warn("Failed to cleanup target file after move error: {}", target, cleanupException);
}
}
private void cleanupTempFile(Path tempPath) {
if (tempPath != null) {
try {
Files.deleteIfExists(tempPath);
} catch (Exception e) {
log.warn("Failed to cleanup temp file: {}", tempPath, e);
}
}
}
private FileProcessResult processFileInLibrary(String fileName, LibraryEntity library, LibraryPathEntity path, File file, BookFileType type) {
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(library)
.libraryPathEntity(path)
@@ -347,87 +424,67 @@ public class BookDropService {
return processor.processFile(libraryFile);
}
public void discardSelectedFiles(boolean selectAll, List<Long> excludedIds, List<Long> selectedIds) {
bookdropMonitoringService.pauseMonitoring();
Path bookdropPath = Path.of(appProperties.getBookdropFolder());
AtomicInteger deletedFiles = new AtomicInteger();
AtomicInteger deletedDirs = new AtomicInteger();
AtomicInteger deletedCovers = new AtomicInteger();
try {
if (!Files.exists(bookdropPath)) {
log.info("Bookdrop folder does not exist: {}", bookdropPath);
return;
}
List<BookdropFileEntity> filesToDelete;
if (selectAll) {
filesToDelete = bookdropFileRepository.findAll().stream()
.filter(f -> excludedIds == null || !excludedIds.contains(f.getId()))
.toList();
log.info("Discarding all files except excluded IDs: {}", excludedIds);
} else {
filesToDelete = bookdropFileRepository.findAllById(selectedIds == null ? List.of() : selectedIds);
log.info("Discarding selected files: {}", selectedIds);
}
for (BookdropFileEntity entity : filesToDelete) {
try {
Path filePath = Path.of(entity.getFilePath());
if (Files.exists(filePath) && Files.isRegularFile(filePath) && Files.deleteIfExists(filePath)) {
deletedFiles.incrementAndGet();
log.debug("Deleted file from disk: id={}, path={}", entity.getId(), filePath);
}
Path coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", entity.getId() + ".jpg");
if (Files.exists(coverPath) && Files.deleteIfExists(coverPath)) {
deletedCovers.incrementAndGet();
log.debug("Deleted cover image: id={}, path={}", entity.getId(), coverPath);
}
} catch (IOException e) {
log.warn("Failed to delete file or cover for bookdropId={}: {}", entity.getId(), e.getMessage());
}
}
bookdropFileRepository.deleteAllById(filesToDelete.stream().map(BookdropFileEntity::getId).toList());
log.info("Deleted {} bookdrop DB entries", filesToDelete.size());
try (Stream<Path> paths = Files.walk(bookdropPath)) {
paths.sorted(Comparator.reverseOrder())
.filter(p -> !p.equals(bookdropPath) && Files.isDirectory(p))
.forEach(p -> {
try (Stream<Path> subPaths = Files.list(p)) {
if (subPaths.findAny().isEmpty()) {
Files.deleteIfExists(p);
deletedDirs.incrementAndGet();
log.debug("Deleted empty directory: {}", p);
}
} catch (IOException e) {
log.warn("Failed to delete folder: {}", p, e);
}
});
} catch (IOException e) {
log.warn("Failed to scan bookdrop folder for empty directories", e);
}
bookdropNotificationService.sendBookdropFileSummaryNotification();
log.info("Bookdrop cleanup summary: deleted {} files, {} folders, {} DB entries, {} covers",
deletedFiles.get(), deletedDirs.get(), filesToDelete.size(), deletedCovers.get());
} finally {
bookdropMonitoringService.resumeMonitoring();
log.info("Bookdrop monitoring resumed after cleanup");
}
}
public Resource getBookdropCover(long bookdropId) {
String coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropId + ".jpg").toString();
File coverFile = new File(coverPath);
if (coverFile.exists() && coverFile.isFile()) {
return new PathResource(coverFile.toPath());
private List<BookdropFileEntity> getFilesToDelete(boolean selectAll, List<Long> excludedIds, List<Long> selectedIds) {
if (selectAll) {
List<BookdropFileEntity> filesToDelete = bookdropFileRepository.findAll().stream()
.filter(f -> excludedIds == null || !excludedIds.contains(f.getId()))
.toList();
log.info("Discarding all files except excluded IDs: {}", excludedIds);
return filesToDelete;
} else {
return null;
List<BookdropFileEntity> filesToDelete = bookdropFileRepository.findAllById(selectedIds == null ? List.of() : selectedIds);
log.info("Discarding selected files: {}", selectedIds);
return filesToDelete;
}
}
}
private void deleteFilesAndCovers(List<BookdropFileEntity> filesToDelete, AtomicInteger deletedFiles, AtomicInteger deletedCovers) {
for (BookdropFileEntity entity : filesToDelete) {
try {
Path filePath = Path.of(entity.getFilePath());
if (Files.exists(filePath) && Files.isRegularFile(filePath) && Files.deleteIfExists(filePath)) {
deletedFiles.incrementAndGet();
log.debug("Deleted file from disk: id={}, path={}", entity.getId(), filePath);
}
Path coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", entity.getId() + ".jpg");
if (Files.exists(coverPath) && Files.deleteIfExists(coverPath)) {
deletedCovers.incrementAndGet();
log.debug("Deleted cover image: id={}, path={}", entity.getId(), coverPath);
}
} catch (IOException e) {
log.warn("Failed to delete file or cover for bookdropId={}: {}", entity.getId(), e.getMessage());
}
}
}
private void deleteEmptyDirectories(Path bookdropPath, AtomicInteger deletedDirs) {
try (Stream<Path> paths = Files.walk(bookdropPath)) {
paths.sorted(Comparator.reverseOrder())
.filter(p -> !p.equals(bookdropPath) && Files.isDirectory(p))
.forEach(p -> {
try (Stream<Path> subPaths = Files.list(p)) {
if (subPaths.findAny().isEmpty()) {
Files.deleteIfExists(p);
deletedDirs.incrementAndGet();
log.debug("Deleted empty directory: {}", p);
}
} catch (IOException e) {
log.warn("Failed to delete folder: {}", p, e);
}
});
} catch (IOException e) {
log.warn("Failed to scan bookdrop folder for empty directories", e);
}
}
private BookdropFileResult failureResult(String fileName, String message) {
return BookdropFileResult.builder()
.fileName(fileName)
.message(message)
.success(false)
.build();
}
private record FileProcessingContext(Long libraryId, Long pathId, BookMetadata metadata) {
}
}
@@ -93,8 +93,7 @@ public class BookdropMonitoringService {
try {
watchKey = bookdrop.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
StandardWatchEventKinds.ENTRY_DELETE);
paused = false;
log.info("Bookdrop monitoring resumed.");
} catch (IOException e) {
@@ -3,172 +3,86 @@ package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
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.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.library.LibraryService;
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
import com.adityachandel.booklore.util.PathPatternResolver;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Slf4j
@Service
@AllArgsConstructor
public class FileMoveService {
private static final int BATCH_SIZE = 100;
private final BookQueryService bookQueryService;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final BookMapper bookMapper;
private final NotificationService notificationService;
private final LibraryService libraryService;
private final MonitoringProtectionService monitoringProtectionService;
private final AppSettingService appSettingService;
private final UnifiedFileMoveService unifiedFileMoveService;
public void moveFiles(FileMoveRequest request) {
Set<Long> bookIds = request.getBookIds();
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
String defaultPattern = appSettingService.getAppSettings().getUploadPattern();
log.info("Moving {} books in batches of {}", bookIds.size(), BATCH_SIZE);
log.info("Starting file move for {} books", books.size());
List<Book> allUpdatedBooks = new ArrayList<>();
int totalProcessed = 0;
int offset = 0;
Set<Long> libraryIds = new HashSet<>();
while (offset < bookIds.size()) {
log.info("Processing batch {}/{}", (offset / BATCH_SIZE) + 1, (bookIds.size() + BATCH_SIZE - 1) / BATCH_SIZE);
List<BookEntity> batchBooks = bookQueryService.findWithMetadataByIdsWithPagination(bookIds, offset, BATCH_SIZE);
if (batchBooks.isEmpty()) {
log.info("No more books at offset {}", offset);
break;
}
List<Book> batchUpdatedBooks = processBookChunk(batchBooks);
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);
}
public String generatePathFromPattern(BookEntity book, String pattern) {
return PathPatternResolver.resolvePattern(book, pattern);
}
private List<Book> processBookChunk(List<BookEntity> books) {
List<Book> updatedBooks = new ArrayList<>();
monitoringProtectionService.executeWithProtection(() -> {
for (BookEntity book : books) {
processBookMove(book, defaultPattern, updatedBooks, libraryIds);
unifiedFileMoveService.moveBatchBookFiles(books, new UnifiedFileMoveService.BatchMoveCallback() {
@Override
public void onBookMoved(BookEntity book) {
bookRepository.save(book);
updatedBooks.add(bookMapper.toBook(book));
}
log.info("Completed file move for {} books.", books.size());
sendUpdateNotifications(updatedBooks);
}, "file move operations");
// Trigger library rescan immediately after file operations complete
if (!libraryIds.isEmpty()) {
rescanLibraries(libraryIds);
}
}
private void processBookMove(BookEntity book, String defaultPattern, List<Book> updatedBooks, Set<Long> libraryIds) {
if (book.getMetadata() == null) return;
String pattern = getFileNamingPattern(book, defaultPattern);
if (pattern == null) return;
if (!hasRequiredPathComponents(book)) return;
Path oldFilePath = book.getFullFilePath();
if (!Files.exists(oldFilePath)) {
log.warn("File does not exist for book id {}: {}", book.getId(), oldFilePath);
return;
}
log.info("Processing book id {}: '{}'", book.getId(), book.getMetadata().getTitle());
Path newFilePath = generateNewFilePath(book, pattern);
if (oldFilePath.equals(newFilePath)) {
log.info("Source and destination paths are identical for book id {}. Skipping.", book.getId());
return;
}
try {
moveFileAndUpdateBook(book, oldFilePath, newFilePath, updatedBooks, libraryIds);
// Move additional files if present
if (book.getAdditionalFiles() != null && !book.getAdditionalFiles().isEmpty()) {
moveAdditionalFiles(book, pattern);
@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);
}
} catch (IOException e) {
log.error("Failed to move file for book id {}: {}", book.getId(), e.getMessage(), e);
}
}
});
private String getFileNamingPattern(BookEntity book, String defaultPattern) {
if (book.getLibraryPath() == null || book.getLibraryPath().getLibrary() == null) {
log.error("Book id {} has no library associated. Skipping.", book.getId());
return null;
}
LibraryEntity library = book.getLibraryPath().getLibrary();
String pattern = library.getFileNamingPattern();
if (pattern == null || pattern.trim().isEmpty()) {
pattern = defaultPattern;
log.info("Using default pattern for library {} as no custom pattern is set", library.getName());
}
if (pattern == null || pattern.trim().isEmpty()) {
log.error("No file naming pattern available for book id {}. Skipping.", book.getId());
return null;
}
return pattern;
}
private 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;
}
private Path generateNewFilePath(BookEntity book, String pattern) {
String newRelativePathStr = generatePathFromPattern(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();
}
private void moveFileAndUpdateBook(BookEntity book, Path oldFilePath, Path newFilePath,
List<Book> updatedBooks, Set<Long> libraryIds) throws IOException {
if (newFilePath.getParent() != null) {
Files.createDirectories(newFilePath.getParent());
}
log.info("Moving file from {} to {}", oldFilePath, newFilePath);
Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING);
updateBookPaths(book, newFilePath);
bookRepository.save(book);
updatedBooks.add(bookMapper.toBook(book));
log.info("Updated book id {} with new path", book.getId());
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot));
if (book.getLibraryPath().getLibrary().getId() != null) {
libraryIds.add(book.getLibraryPath().getLibrary().getId());
}
}
private 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);
return updatedBooks;
}
private void sendUpdateNotifications(List<Book> updatedBooks) {
@@ -176,169 +90,4 @@ public class FileMoveService {
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_UPDATE, updatedBooks);
}
}
private void rescanLibraries(Set<Long> libraryIds) {
for (Long libraryId : libraryIds) {
try {
libraryService.rescanLibrary(libraryId);
log.info("Rescanned library id {} after file move", libraryId);
} catch (Exception e) {
log.error("Failed to rescan library id {}: {}", libraryId, e.getMessage(), e);
}
}
}
public String generatePathFromPattern(BookEntity book, String pattern) {
return PathPatternResolver.resolvePattern(book, pattern);
}
private void moveAdditionalFiles(BookEntity book, String pattern) throws IOException {
Map<String, Integer> fileNameCounter = new HashMap<>();
for (BookAdditionalFileEntity additionalFile : book.getAdditionalFiles()) {
Path oldAdditionalFilePath = additionalFile.getFullFilePath();
if (!Files.exists(oldAdditionalFilePath)) {
log.warn("Additional file does not exist for book id {}: {}", book.getId(), oldAdditionalFilePath);
continue;
}
String newRelativePathStr = PathPatternResolver.resolvePattern(book.getMetadata(), pattern, additionalFile.getFileName());
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
newRelativePathStr = newRelativePathStr.substring(1);
}
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
Path newAdditionalFilePath = libraryRoot.resolve(newRelativePathStr).normalize();
// Check for filename uniqueness and add index if necessary
newAdditionalFilePath = ensureUniqueFilePath(newAdditionalFilePath, fileNameCounter);
if (oldAdditionalFilePath.equals(newAdditionalFilePath)) {
log.debug("Source and destination paths are identical for additional file id {}. Skipping.", additionalFile.getId());
continue;
}
// Create parent directories if needed
if (newAdditionalFilePath.getParent() != null) {
Files.createDirectories(newAdditionalFilePath.getParent());
}
log.info("Moving additional file from {} to {}", oldAdditionalFilePath, newAdditionalFilePath);
Files.move(oldAdditionalFilePath, newAdditionalFilePath, StandardCopyOption.REPLACE_EXISTING);
// Update additional file paths
updateAdditionalFilePaths(additionalFile, newAdditionalFilePath, libraryRoot);
bookAdditionalFileRepository.save(additionalFile);
log.info("Updated additional file id {} with new path", additionalFile.getId());
}
}
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 {
// File name already exists, add index
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);
}
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;
}
}
}
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);
}
}
}
@@ -0,0 +1,303 @@
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.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.PathPatternResolver;
import lombok.AllArgsConstructor;
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;
/**
* 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()) {
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());
}
// 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;
}
}
}
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 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);
}
}
}
@@ -0,0 +1,147 @@
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.info("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");
}
}
@@ -0,0 +1,184 @@
package com.adityachandel.booklore.service.file;
import com.adityachandel.booklore.model.entity.BookEntity;
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;
/**
* 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();
if (!Files.exists(currentFilePath)) {
log.warn("File does not exist for book ID {}: {}. Skipping file move.", bookEntity.getId(), currentFilePath);
return;
}
// Check if current path differs from expected pattern
Path expectedFilePath = fileMovingHelper.generateNewFilePath(bookEntity, 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);
// For single file moves, use targeted path protection
monitoredFileOperationService.executeWithMonitoringSuspended(currentFilePath, expectedFilePath, bookEntity.getLibraryPath().getLibrary().getId(), () -> {
try {
boolean moved = fileMovingHelper.moveBookFileIfNeeded(bookEntity, pattern);
if (moved) {
log.info("Successfully moved file for book ID {} from {} to {} to match library pattern", 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);
}
});
}
/**
* Moves multiple book files in batches with library-level monitoring protection.
* Used for bulk file operations where many files need to be moved.
*/
public void moveBatchBookFiles(List<BookEntity> books, BatchMoveCallback callback) {
if (books.isEmpty()) {
log.debug("No books to move");
return;
}
Set<Long> libraryIds = 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;
Long libraryId = book.getLibraryPath().getLibrary().getId();
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
libraryToRootsMap.computeIfAbsent(libraryId, k -> new HashSet<>()).add(libraryRoot);
libraryIds.add(libraryId);
}
// Unregister libraries for batch operation
unregisterLibrariesBatch(libraryToRootsMap);
try {
// Process each book
for (BookEntity book : books) {
if (book.getMetadata() == null) continue;
String pattern = fileMovingHelper.getFileNamingPattern(book.getLibraryPath().getLibrary());
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 {
boolean moved = fileMovingHelper.moveBookFileIfNeeded(book, pattern);
if (moved) {
log.debug("Book {} moved successfully", book.getId());
callback.onBookMoved(book);
}
// Move additional files if any
if (book.getAdditionalFiles() != null && !book.getAdditionalFiles().isEmpty()) {
fileMovingHelper.moveAdditionalFiles(book, pattern);
}
} catch (IOException e) {
log.error("Move failed for book {}: {}", book.getId(), e.getMessage(), e);
callback.onBookMoveFailed(book, e);
}
}
// Small delay to let filesystem operations settle
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted during batch move delay");
}
} finally {
// Re-register libraries
registerLibrariesBatch(libraryToRootsMap);
}
}
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();
monitoringRegistrationService.unregisterLibrary(libraryId);
log.debug("Unregistered library {}", libraryId);
}
}
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();
for (Path libraryRoot : libraryRoots) {
if (Files.exists(libraryRoot) && Files.isDirectory(libraryRoot)) {
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
log.debug("Re-registered library {} at {}", libraryId, libraryRoot);
}
}
}
}
/**
* Callback interface for batch move operations
*/
public interface BatchMoveCallback {
void onBookMoved(BookEntity book);
void onBookMoveFailed(BookEntity book, Exception error);
}
}
@@ -104,6 +104,7 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
if (!sameLibraryPath) {
entity.setLibraryPath(libraryFile.getLibraryPathEntity());
entity.setLibrary(libraryFile.getLibraryEntity());
updated = true;
}
@@ -13,6 +13,7 @@ import com.adityachandel.booklore.repository.AuthorRepository;
import com.adityachandel.booklore.repository.CategoryRepository;
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.metadata.backuprestore.MetadataBackupRestore;
import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupRestoreFactory;
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
@@ -49,6 +50,7 @@ public class BookMetadataUpdater {
private final MetadataWriterFactory metadataWriterFactory;
private final MetadataBackupRestoreFactory metadataBackupRestoreFactory;
private final BookReviewUpdateService bookReviewUpdateService;
private final UnifiedFileMoveService unifiedFileMoveService;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void setBookMetadata(BookEntity bookEntity, MetadataUpdateWrapper wrapper, boolean setThumbnail, boolean mergeCategories) {
@@ -109,45 +111,55 @@ public class BookMetadataUpdater {
log.info("CBX metadata writing disabled for book ID {}", bookId);
} else {
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
try {
String thumbnailUrl = setThumbnail ? newMetadata.getThumbnailUrl() : null;
try {
String thumbnailUrl = setThumbnail ? 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, false, 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;
if ((StringUtils.hasText(thumbnailUrl) && isLocalOrPrivateUrl(thumbnailUrl) || Boolean.TRUE.equals(metadata.getCoverLocked()))) {
log.debug("Blocked local/private thumbnail URL: {}", thumbnailUrl);
thumbnailUrl = null;
}
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());
File file = new File(bookEntity.getFullFilePath().toUri());
writer.writeMetadataToFile(file, metadata, thumbnailUrl, false, 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());
}
bookEntity.setCurrentHash(newHash);
} catch (Exception e) {
log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage());
}
bookEntity.setCurrentHash(newHash);
} catch (Exception e) {
log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage());
}
});
}
});
}
}
boolean moveFilesToLibraryPattern = settings.isMoveFilesToLibraryPattern();
if (moveFilesToLibraryPattern) {
try {
unifiedFileMoveService.moveSingleBookFile(bookEntity);
} 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) {
handleFieldUpdate(e.getTitleLocked(), clear.isTitle(), m.getTitle(), v -> e.setTitle(nullIfBlank(v)));
handleFieldUpdate(e.getSubtitleLocked(), clear.isSubtitle(), m.getSubtitle(), v -> e.setSubtitle(nullIfBlank(v)));
@@ -1,124 +0,0 @@
package com.adityachandel.booklore.service.monitoring;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.function.Supplier;
/**
* Thread-safe service for managing monitoring protection during file operations.
*
* This service prevents race conditions where file operations are detected as
* "missing files" by the monitoring system, which could lead to data loss.
*
* The service ensures:
* - Thread-safe pause/resume operations
* - Monitoring always resumes even on exceptions
* - Protection against concurrent operations interfering with each other
*/
@Slf4j
@Service
@AllArgsConstructor
public class MonitoringProtectionService {
private final MonitoringService monitoringService;
// Synchronization lock to prevent race conditions in pause/resume logic
private static final Object monitoringLock = new Object();
/**
* Executes an operation with monitoring protection.
*
* @param operation The operation to execute while monitoring is paused
* @param operationName Name for logging purposes
* @param <T> Return type of the operation
* @return Result of the operation
*/
public <T> T executeWithProtection(Supplier<T> operation, String operationName) {
boolean didPause = pauseMonitoringSafely();
try {
log.debug("Executing {} with monitoring protection (paused: {})", operationName, didPause);
return operation.get();
} finally {
resumeMonitoringSafely(didPause, operationName);
}
}
/**
* Executes a void operation with monitoring protection.
*
* @param operation The operation to execute while monitoring is paused
* @param operationName Name for logging purposes
*/
public void executeWithProtection(Runnable operation, String operationName) {
executeWithProtection(() -> {
operation.run();
return null;
}, operationName);
}
/**
* Thread-safe pause of monitoring service.
*
* @return true if monitoring was paused by this call, false if already paused
*/
private boolean pauseMonitoringSafely() {
synchronized (monitoringLock) {
if (!monitoringService.isPaused()) {
monitoringService.pauseMonitoring();
log.debug("Monitoring paused for file operations");
return true;
}
log.debug("Monitoring already paused by another operation");
return false;
}
}
/**
* Thread-safe resume of monitoring service with a 5-second delay.
* The delay is critical to prevent race conditions where file operations
* are still settling when monitoring resumes.
*
* @param didPause true if this operation paused monitoring
* @param operationName name of the operation for logging
*/
private void resumeMonitoringSafely(boolean didPause, String operationName) {
if (!didPause) {
log.debug("Monitoring was not paused by {} - no resume needed", operationName);
return;
}
// Use virtual thread for delayed resume to avoid blocking
Thread.startVirtualThread(() -> {
try {
Thread.sleep(5_000); // Critical 5-second delay for filesystem operations to settle
synchronized (monitoringLock) {
// Double-check that monitoring is still paused before resuming
if (monitoringService.isPaused()) {
monitoringService.resumeMonitoring();
log.debug("Monitoring resumed after {} completed with 5s delay", operationName);
} else {
log.warn("Monitoring was already resumed by another thread during {}", operationName);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while delaying resume of monitoring after {}", operationName);
}
});
}
/**
* Checks if monitoring is currently paused.
*
* @return true if monitoring is paused
*/
public boolean isMonitoringPaused() {
synchronized (monitoringLock) {
return monitoringService.isPaused();
}
}
}
@@ -0,0 +1,81 @@
package com.adityachandel.booklore.service.monitoring;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.nio.file.Files;
import java.nio.file.Path;
@Slf4j
@Service
@AllArgsConstructor
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 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;
}
try {
monitoringService.registerPath(libraryRoot, libraryId);
try (var stream = Files.walk(libraryRoot)) {
stream.filter(Files::isDirectory)
.filter(path -> !path.equals(libraryRoot))
.forEach(path -> monitoringService.registerPath(path, libraryId));
}
} catch (Exception e) {
log.error("Failed to register library paths for libraryId {} at {}", libraryId, libraryRoot, e);
}
}
}
@@ -29,14 +29,11 @@ public class MonitoringService {
private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
private final Set<Path> monitoredPaths = ConcurrentHashMap.newKeySet();
private final Map<Path, WatchKey> registeredWatchKeys = new ConcurrentHashMap<>();
private final Map<Path, Long> pathToLibraryIdMap = new ConcurrentHashMap<>();
private final Map<Long, Boolean> libraryWatchStatusMap = new ConcurrentHashMap<>();
private final Map<Path, WatchKey> registeredWatchKeys = new ConcurrentHashMap<>();
private final Map<Long, List<Path>> libraryIdToPaths = new ConcurrentHashMap<>();
private int pauseCount = 0;
private final Object pauseLock = new Object();
public MonitoringService(LibraryFileEventProcessor libraryFileEventProcessor, WatchService watchService, MonitoringTask monitoringTask) {
this.libraryFileEventProcessor = libraryFileEventProcessor;
this.watchService = watchService;
@@ -60,60 +57,6 @@ public class MonitoringService {
}
}
public synchronized void pauseMonitoring() {
pauseCount++;
if (pauseCount == 1) {
int count = 0;
for (Path path : new HashSet<>(monitoredPaths)) {
unregisterPath(path, false);
count++;
}
log.info("Monitoring paused ({} paths unregistered, pauseCount={})", count, pauseCount);
} else {
log.info("Monitoring pause requested (pauseCount={})", pauseCount);
}
}
public synchronized void resumeMonitoring() {
if (pauseCount == 0) {
log.warn("resumeMonitoring() called but monitoring is not paused");
return;
}
pauseCount--;
if (pauseCount == 0) {
libraryIdToPaths.forEach((libraryId, rootPaths) -> {
for (Path rootPath : rootPaths) {
if (Files.exists(rootPath)) {
try (Stream<Path> stream = Files.walk(rootPath)) {
stream.filter(Files::isDirectory).forEach(path -> {
if (Files.exists(path)) {
registerPath(path, libraryId);
}
});
} catch (IOException e) {
log.warn("Failed to walk path during resume: {}", rootPath, e);
}
} else {
log.debug("Skipping registration of non-existent path during resume: {}", rootPath);
}
}
});
synchronized (pauseLock) {
pauseLock.notifyAll();
}
log.info("Monitoring resumed");
} else {
log.info("Monitoring resume requested (pauseCount={}), monitoring still paused", pauseCount);
}
}
public synchronized boolean isPaused() {
return pauseCount > 0;
}
public void registerLibraries(List<Library> libraries) {
libraries.forEach(lib -> libraryWatchStatusMap.put(lib.getId(), lib.isWatch()));
libraries.stream().filter(Library::isWatch).forEach(this::registerLibrary);
@@ -159,19 +102,7 @@ public class MonitoringService {
libraryWatchStatusMap.put(libraryId, false);
libraryIdToPaths.remove(libraryId);
log.info("Unregistered library {} from monitoring", libraryId);
}
public void unregisterLibraries(Set<Long> libraryIds) {
libraryIds.forEach(this::unregisterLibrary);
}
public boolean isLibraryWatched(Long libraryId) {
return libraryWatchStatusMap.getOrDefault(libraryId, false);
}
public boolean isRelevantBookFile(Path path) {
return BookFileExtension.fromFileName(path.getFileName().toString()).isPresent();
log.debug("Unregistered library {} from monitoring", libraryId);
}
public synchronized boolean registerPath(Path path, Long libraryId) {
@@ -201,11 +132,21 @@ public class MonitoringService {
if (key != null) key.cancel();
pathToLibraryIdMap.remove(path);
if (logUnregister) {
log.info("Unregistered path: {}", path);
log.debug("Unregistered path: {}", path);
}
}
}
private void unregisterSubPaths(Path deletedPath) {
Set<Path> toRemove = monitoredPaths.stream()
.filter(p -> p.startsWith(deletedPath))
.collect(Collectors.toSet());
for (Path path : toRemove) {
unregisterPath(path);
}
}
@EventListener
public void handleFileChangeEvent(FileChangeEvent event) {
Path fullPath = event.getFilePath();
@@ -220,26 +161,8 @@ public class MonitoringService {
boolean isRelevantFile = isRelevantBookFile(fullPath);
if (!(isDir || isRelevantFile)) return;
if (isDir && kind == StandardWatchEventKinds.ENTRY_CREATE) {
Long parentLibraryId = pathToLibraryIdMap.get(event.getWatchedFolder());
if (parentLibraryId != null) {
try (Stream<Path> stream = Files.walk(fullPath)) {
stream.filter(Files::isDirectory).forEach(path -> registerPath(path, parentLibraryId));
} catch (IOException e) {
log.warn("Failed to register nested paths: {}", fullPath, e);
}
}
}
if (isDir && kind == StandardWatchEventKinds.ENTRY_DELETE) {
unregisterSubPaths(fullPath);
}
if (!eventQueue.offer(event)) {
log.warn("Event queue full, dropping: {}", fullPath);
} else {
log.debug("Queued: {} [{}]", fullPath, kind.name());
}
handleDirectoryEvents(event, fullPath, kind, isDir);
queueEvent(event, fullPath, kind);
}
@EventListener
@@ -258,15 +181,8 @@ public class MonitoringService {
singleThreadExecutor.submit(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
synchronized (pauseLock) {
while (isPaused()) {
pauseLock.wait();
}
}
FileChangeEvent event = eventQueue.take();
processFileChangeEvent(event);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
@@ -284,9 +200,7 @@ public class MonitoringService {
if (libraryId != null) {
try {
libraryFileEventProcessor.processFile(
event.getEventKind(), libraryId, watchedFolder.toString(), filePath.toString()
);
libraryFileEventProcessor.processFile(event.getEventKind(), libraryId, watchedFolder.toString(), filePath.toString());
} catch (InvalidDataAccessApiUsageException e) {
log.debug("InvalidDataAccessApiUsageException for libraryId={}", libraryId);
}
@@ -295,13 +209,36 @@ public class MonitoringService {
}
}
private void unregisterSubPaths(Path deletedPath) {
Set<Path> toRemove = monitoredPaths.stream()
.filter(p -> p.startsWith(deletedPath))
.collect(Collectors.toSet());
private void handleDirectoryEvents(FileChangeEvent event, Path fullPath, WatchEvent.Kind<?> kind, boolean isDir) {
if (isDir && kind == StandardWatchEventKinds.ENTRY_CREATE) {
Long parentLibraryId = pathToLibraryIdMap.get(event.getWatchedFolder());
if (parentLibraryId != null) {
try (Stream<Path> stream = Files.walk(fullPath)) {
stream.filter(Files::isDirectory).forEach(path -> registerPath(path, parentLibraryId));
} catch (IOException e) {
log.warn("Failed to register nested paths: {}", fullPath, e);
}
}
}
for (Path path : toRemove) {
unregisterPath(path);
if (isDir && kind == StandardWatchEventKinds.ENTRY_DELETE) {
unregisterSubPaths(fullPath);
}
}
}
private void queueEvent(FileChangeEvent event, Path fullPath, WatchEvent.Kind<?> kind) {
if (!eventQueue.offer(event)) {
log.warn("Event queue full, dropping: {}", fullPath);
} else {
log.debug("Queued: {} [{}]", fullPath, kind.name());
}
}
public boolean isRelevantBookFile(Path path) {
return BookFileExtension.fromFileName(path.getFileName().toString()).isPresent();
}
public boolean isPathMonitored(Path path) {
return monitoredPaths.contains(path.toAbsolutePath().normalize());
}
}
@@ -3,50 +3,36 @@ 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;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.AdditionalFileType;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.FileProcessStatus;
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.FileFingerprint;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.file.FileMovingHelper;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.util.PathPatternResolver;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.GroupPrincipal;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
@RequiredArgsConstructor
@@ -54,202 +40,190 @@ import java.util.Optional;
@Slf4j
public class FileUploadService {
private static final String UPLOAD_TEMP_PREFIX = "upload-";
private static final String BOOKDROP_TEMP_PREFIX = "bookdrop-";
private static final long BYTES_TO_KB_DIVISOR = 1024L;
private static final long MB_TO_BYTES_MULTIPLIER = 1024L * 1024L;
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final BookAdditionalFileRepository additionalFileRepository;
private final BookFileProcessorRegistry processorRegistry;
private final NotificationService notificationService;
private final AppSettingService appSettingService;
private final AppProperties appProperties;
private final PdfMetadataExtractor pdfMetadataExtractor;
private final EpubMetadataExtractor epubMetadataExtractor;
private final AdditionalFileMapper additionalFileMapper;
private final MonitoringService monitoringService;
private final FileMovingHelper fileMovingHelper;
@Value("${PUID:${USER_ID:0}}")
private String userId;
@Value("${PGID:${GROUP_ID:0}}")
private String groupId;
public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException {
public void uploadFile(MultipartFile file, long libraryId, long pathId) {
validateFile(file);
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
LibraryPathEntity libraryPathEntity = libraryEntity.getLibraryPaths()
.stream()
.filter(p -> p.getId() == pathId)
.findFirst()
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
Path tempPath = Files.createTempFile("upload-", Objects.requireNonNull(file.getOriginalFilename()));
FileProcessResult result;
boolean wePaused = false;
if (!monitoringService.isPaused()) {
monitoringService.pauseMonitoring();
wePaused = true;
}
final LibraryEntity libraryEntity = findLibraryById(libraryId);
final LibraryPathEntity libraryPathEntity = findLibraryPathById(libraryEntity, pathId);
final String originalFileName = getValidatedFileName(file);
Path tempPath = null;
try {
tempPath = createTempFile(UPLOAD_TEMP_PREFIX, originalFileName);
file.transferTo(tempPath);
setTemporaryFileOwnership(tempPath);
BookFileExtension fileExt = BookFileExtension.fromFileName(file.getOriginalFilename()).orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
BookMetadata metadata = extractMetadata(fileExt, tempPath.toFile());
String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
if (uploadPattern.endsWith("/") || uploadPattern.endsWith("\\")) {
uploadPattern += "{currentFilename}";
}
String relativePath = PathPatternResolver.resolvePattern(metadata, uploadPattern, file.getOriginalFilename());
Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
File finalFile = finalPath.toFile();
final BookFileExtension fileExtension = getFileExtension(originalFileName);
final BookMetadata metadata = extractMetadata(fileExtension, tempPath.toFile());
final String uploadPattern = fileMovingHelper.getFileNamingPattern(libraryEntity);
if (finalFile.exists()) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
final String relativePath = PathPatternResolver.resolvePattern(metadata, uploadPattern, originalFileName);
final Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
Files.createDirectories(finalPath.getParent());
Files.move(tempPath, finalPath);
validateFinalPath(finalPath);
moveFileToFinalLocation(tempPath, finalPath);
log.info("File uploaded to final location: {}", finalPath);
result = processFile(finalFile.getName(), libraryEntity, libraryPathEntity, finalFile, fileExt.getType());
if (result != null && result.getStatus() != FileProcessStatus.DUPLICATE) {
notificationService.sendMessage(Topic.BOOK_ADD, result.getBook());
}
return result.getBook();
} catch (IOException e) {
log.error("Failed to upload file: {}", originalFileName, e);
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
} finally {
Files.deleteIfExists(tempPath);
if (wePaused) {
Thread.startVirtualThread(() -> {
try {
Thread.sleep(5_000);
monitoringService.resumeMonitoring();
log.info("Monitoring resumed after 5s delay");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while delaying resume of monitoring");
}
});
}
cleanupTempFile(tempPath);
}
}
@Transactional
public AdditionalFile uploadAdditionalFile(Long bookId, MultipartFile file, AdditionalFileType additionalFileType, String description) throws IOException {
Optional<BookEntity> bookOpt = bookRepository.findById(bookId);
if (bookOpt.isEmpty()) {
throw new IllegalArgumentException("Book not found with id: " + bookId);
}
BookEntity book = bookOpt.get();
String originalFileName = file.getOriginalFilename();
if (originalFileName == null) {
throw new IllegalArgumentException("File must have a name");
}
Path tempPath = Files.createTempFile("upload-", Objects.requireNonNull(file.getOriginalFilename()));
boolean wePaused = false;
if (!monitoringService.isPaused()) {
monitoringService.pauseMonitoring();
wePaused = true;
}
final BookEntity book = findBookById(bookId);
final String originalFileName = getValidatedFileName(file);
Path tempPath = null;
try {
tempPath = createTempFile(UPLOAD_TEMP_PREFIX, originalFileName);
file.transferTo(tempPath);
setTemporaryFileOwnership(tempPath);
final String fileHash = FileFingerprint.generateHash(tempPath);
validateAlternativeFormatDuplicate(additionalFileType, fileHash);
// Check for duplicates by hash, but only for alternative formats
String fileHash = FileFingerprint.generateHash(tempPath);
if (additionalFileType == AdditionalFileType.ALTERNATIVE_FORMAT) {
Optional<BookAdditionalFileEntity> existingAltFormat = additionalFileRepository.findByAltFormatCurrentHash(fileHash);
if (existingAltFormat.isPresent()) {
throw new IllegalArgumentException("Alternative format file already exists with same content");
}
}
// Store file in same directory as the book
Path finalPath = Paths.get(book.getLibraryPath().getPath(), book.getFileSubPath(), originalFileName);
File finalFile = finalPath.toFile();
if (finalFile.exists()) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
Files.createDirectories(finalPath.getParent());
Files.move(tempPath, finalPath);
final Path finalPath = buildAdditionalFilePath(book, originalFileName);
validateFinalPath(finalPath);
moveFileToFinalLocation(tempPath, finalPath);
log.info("Additional file uploaded to final location: {}", finalPath);
// Create entity
BookAdditionalFileEntity entity = BookAdditionalFileEntity.builder()
.book(book)
.fileName(originalFileName)
.fileSubPath(book.getFileSubPath())
.additionalFileType(additionalFileType)
.fileSizeKb(file.getSize() / 1024)
.initialHash(fileHash)
.currentHash(fileHash)
.description(description)
.addedOn(Instant.now())
.build();
final BookAdditionalFileEntity entity = createAdditionalFileEntity(book, originalFileName, additionalFileType, file.getSize(), fileHash, description);
final BookAdditionalFileEntity savedEntity = additionalFileRepository.save(entity);
entity = additionalFileRepository.save(entity);
return additionalFileMapper.toAdditionalFile(savedEntity);
return additionalFileMapper.toAdditionalFile(entity);
} catch (IOException e) {
log.error("Failed to upload additional file for book {}: {}", bookId, originalFileName, e);
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
} finally {
Files.deleteIfExists(tempPath);
if (wePaused) {
Thread.startVirtualThread(() -> {
try {
Thread.sleep(5_000);
monitoringService.resumeMonitoring();
log.info("Monitoring resumed after 5s delay");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while delaying resume of monitoring");
}
});
}
cleanupTempFile(tempPath);
}
}
public Book uploadFileBookDrop(MultipartFile file) throws IOException {
validateFile(file);
Path dropFolder = Paths.get(appProperties.getBookdropFolder());
final Path dropFolder = Paths.get(appProperties.getBookdropFolder());
Files.createDirectories(dropFolder);
String originalFilename = Objects.requireNonNull(file.getOriginalFilename());
Path tempPath = Files.createTempFile("bookdrop-", originalFilename);
final String originalFilename = getValidatedFileName(file);
Path tempPath = null;
try {
tempPath = createTempFile(BOOKDROP_TEMP_PREFIX, originalFilename);
file.transferTo(tempPath);
setTemporaryFileOwnership(tempPath);
Path finalPath = dropFolder.resolve(originalFilename);
if (Files.exists(finalPath)) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
final Path finalPath = dropFolder.resolve(originalFilename);
validateFinalPath(finalPath);
Files.move(tempPath, finalPath);
log.info("File moved to book-drop folder: {}", finalPath);
return null;
} finally {
Files.deleteIfExists(tempPath);
cleanupTempFile(tempPath);
}
}
private LibraryEntity findLibraryById(long libraryId) {
return libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
}
private LibraryPathEntity findLibraryPathById(LibraryEntity libraryEntity, long pathId) {
return libraryEntity.getLibraryPaths()
.stream()
.filter(p -> p.getId() == pathId)
.findFirst()
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryEntity.getId()));
}
private BookEntity findBookById(Long bookId) {
return bookRepository.findById(bookId)
.orElseThrow(() -> new IllegalArgumentException("Book not found with id: " + bookId));
}
private String getValidatedFileName(MultipartFile file) {
final String originalFileName = file.getOriginalFilename();
if (originalFileName == null) {
throw new IllegalArgumentException("File must have a name");
}
return originalFileName;
}
private BookFileExtension getFileExtension(String fileName) {
return BookFileExtension.fromFileName(fileName)
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
}
private Path createTempFile(String prefix, String fileName) throws IOException {
return Files.createTempFile(prefix, fileName);
}
private void validateFinalPath(Path finalPath) {
if (Files.exists(finalPath)) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
}
private void moveFileToFinalLocation(Path sourcePath, Path targetPath) throws IOException {
Files.createDirectories(targetPath.getParent());
Files.move(sourcePath, targetPath);
}
private void validateAlternativeFormatDuplicate(AdditionalFileType additionalFileType, String fileHash) {
if (additionalFileType == AdditionalFileType.ALTERNATIVE_FORMAT) {
final Optional<BookAdditionalFileEntity> existingAltFormat = additionalFileRepository.findByAltFormatCurrentHash(fileHash);
if (existingAltFormat.isPresent()) {
throw new IllegalArgumentException("Alternative format file already exists with same content");
}
}
}
private Path buildAdditionalFilePath(BookEntity book, String fileName) {
return Paths.get(book.getLibraryPath().getPath(), book.getFileSubPath(), fileName);
}
private BookAdditionalFileEntity createAdditionalFileEntity(BookEntity book, String fileName, AdditionalFileType additionalFileType, long fileSize, String fileHash, String description) {
return BookAdditionalFileEntity.builder()
.book(book)
.fileName(fileName)
.fileSubPath(book.getFileSubPath())
.additionalFileType(additionalFileType)
.fileSizeKb(fileSize / BYTES_TO_KB_DIVISOR)
.initialHash(fileHash)
.currentHash(fileHash)
.description(description)
.addedOn(Instant.now())
.build();
}
private void cleanupTempFile(Path tempPath) {
if (tempPath != null) {
try {
Files.deleteIfExists(tempPath);
} catch (IOException e) {
log.warn("Failed to cleanup temp file: {}", tempPath, e);
}
}
}
@@ -262,41 +236,14 @@ public class FileUploadService {
}
private void validateFile(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
final String originalFilename = file.getOriginalFilename();
if (originalFilename == null || BookFileExtension.fromFileName(originalFilename).isEmpty()) {
throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension");
}
int maxSizeMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
if (file.getSize() > maxSizeMb * 1024L * 1024L) {
final int maxSizeMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
if (file.getSize() > maxSizeMb * MB_TO_BYTES_MULTIPLIER) {
throw ApiError.FILE_TOO_LARGE.createException(maxSizeMb);
}
}
private void setTemporaryFileOwnership(Path tempPath) throws IOException {
UserPrincipalLookupService lookupService = FileSystems.getDefault()
.getUserPrincipalLookupService();
if (!userId.equals("0")) {
UserPrincipal user = lookupService.lookupPrincipalByName(userId);
Files.getFileAttributeView(tempPath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setOwner(user);
}
if (!groupId.equals("0")) {
GroupPrincipal group = lookupService.lookupPrincipalByGroupName(groupId);
Files.getFileAttributeView(tempPath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(group);
}
}
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()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileSubPath(subPath)
.bookFileType(type)
.fileName(fileName)
.build();
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
return processor.processFile(libraryFile);
}
}
@@ -208,11 +208,22 @@ public class FileService {
if (!folder.exists() && !folder.mkdirs()) {
throw new IOException("Failed to create directory: " + folder.getAbsolutePath());
}
BufferedImage rgbImage = new BufferedImage(
coverImage.getWidth(),
coverImage.getHeight(),
BufferedImage.TYPE_INT_RGB
);
Graphics2D g = rgbImage.createGraphics();
g.drawImage(coverImage, 0, 0, Color.WHITE, null);
g.dispose();
File originalFile = new File(folder, COVER_FILENAME);
boolean originalSaved = ImageIO.write(coverImage, IMAGE_FORMAT, originalFile);
BufferedImage thumb = resizeImage(coverImage, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
boolean originalSaved = ImageIO.write(rgbImage, IMAGE_FORMAT, originalFile);
BufferedImage thumb = resizeImage(rgbImage, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
File thumbnailFile = new File(folder, THUMBNAIL_FILENAME);
boolean thumbnailSaved = ImageIO.write(thumb, IMAGE_FORMAT, thumbnailFile);
return originalSaved && thumbnailSaved;
}
@@ -336,6 +347,27 @@ public class FileService {
log.warn("Skipping file due to missing hash: {}", libraryFile.getFullPath());
return Optional.empty();
}
// First check for soft-deleted books with the same hash
Optional<BookEntity> softDeletedBook = bookRepository.findByCurrentHashAndDeletedTrue(hash);
if (softDeletedBook.isPresent()) {
BookEntity book = softDeletedBook.get();
log.info("Found soft-deleted book with same hash, undeleting: bookId={} file='{}'",
book.getId(), libraryFile.getFileName());
// Undelete the book
book.setDeleted(false);
book.setDeletedAt(null);
// Update file information
book.setFileName(libraryFile.getFileName());
book.setFileSubPath(libraryFile.getFileSubPath());
book.setLibraryPath(libraryFile.getLibraryPathEntity());
book.setLibrary(libraryFile.getLibraryEntity());
return Optional.of(bookMapper.toBook(book));
}
Optional<BookEntity> existingByHash = bookRepository.findByCurrentHash(hash);
if (existingByHash.isPresent()) {
BookEntity book = existingByHash.get();