WIP: Watcher

This commit is contained in:
aditya.chandel
2025-01-27 23:52:15 -07:00
parent 32fe27128f
commit 8918c2b344
12 changed files with 284 additions and 12 deletions
@@ -2,7 +2,9 @@ package com.adityachandel.booklore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync
@SpringBootApplication
public class BookloreApplication {
@@ -0,0 +1,25 @@
package com.adityachandel.booklore.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.WatchService;
@Slf4j
@Configuration
public class MonitoringConfig {
@Bean
public WatchService watchService() {
WatchService watchService = null;
try {
watchService = FileSystems.getDefault().newWatchService();
} catch (IOException e) {
log.error("Error creating WatchService:", e);
}
return watchService;
}
}
@@ -10,7 +10,6 @@ import java.util.List;
@Mapper(componentModel = "spring")
public interface LibraryMapper {
@Mapping(target = "paths", source = "libraryEntity.libraryPaths")
@Mapping(target = "paths", source = "libraryPaths")
Library toLibrary(LibraryEntity libraryEntity);
}
@@ -14,6 +14,7 @@ public class Library {
private String name;
private Sort sort;
private String icon;
private boolean watch;
private List<LibraryPath> paths;
}
@@ -31,5 +31,8 @@ public class LibraryEntity {
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true)
private List<LibraryPathEntity> libraryPaths;
private boolean watch;
private String icon;
}
@@ -13,14 +13,17 @@ import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.persistence.EntityManager;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@@ -38,6 +41,7 @@ public class LibraryProcessingService {
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
private final BookRepository bookRepository;
private final EntityManager entityManager;
@Transactional
@@ -49,6 +53,48 @@ public class LibraryProcessingService {
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing library: " + libraryEntity.getName()));
}
@Transactional
public void processFile(long libraryId, String libraryPath, String filePath) {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath));
Path path = Paths.get(filePath);
String fileName = path.getFileName().toString();
LibraryPathEntity libraryPathEntity = getLibraryPathEntityForFile(libraryEntity, libraryPath);
libraryPathEntity = entityManager.merge(libraryPathEntity);
String fileSubPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), path);
BookFileType bookFileType = getBookFileType(fileName);
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileSubPath(fileSubPath)
.fileName(fileName)
.bookFileType(bookFileType)
.build();
processLibraryFiles(List.of(libraryFile));
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath));
}
@Transactional
protected LibraryPathEntity getLibraryPathEntityForFile(LibraryEntity libraryEntity, String libraryPath) {
return libraryEntity.getLibraryPaths().stream().filter(l -> l.getPath().equals(libraryPath))
.findFirst()
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(libraryPath));
}
@Transactional
protected BookFileType getBookFileType(String fileName) {
if (fileName.endsWith(".pdf")) {
return BookFileType.PDF;
} else {
return BookFileType.EPUB;
}
}
/*@Transactional
public void refreshLibrary(long libraryId) throws IOException {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
@@ -16,6 +16,7 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryPathRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.InvalidDataAccessApiUsageException;
@@ -26,6 +27,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Slf4j
@Service
@@ -52,7 +54,7 @@ public class LibraryService {
Set<String> deletedPaths = currentPaths.stream().filter(path -> !updatedPaths.contains(path)).collect(Collectors.toSet());
Set<String> newPaths = updatedPaths.stream().filter(path -> !currentPaths.contains(path)).collect(Collectors.toSet());
if(newPaths.isEmpty() && deletedPaths.isEmpty()) {
if (newPaths.isEmpty() && deletedPaths.isEmpty()) {
return libraryMapper.toLibrary(libraryRepository.save(library));
} else {
if (!deletedPaths.isEmpty()) {
@@ -164,9 +166,9 @@ public class LibraryService {
return bookEntities.stream().map(bookMapper::toBook).toList();
}
public Library updateSort(long libraryId, Sort sort) {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
libraryEntity.setSort(sort);
return libraryMapper.toLibrary(libraryRepository.save(libraryEntity));
@Transactional
public List<Library> getAllLibraries() {
return libraryRepository.findAll().stream().map(libraryMapper::toLibrary).collect(Collectors.toList());
}
}
@@ -0,0 +1,22 @@
package com.adityachandel.booklore.service.monitoring;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;
@Getter
public class FileChangeEvent extends ApplicationEvent {
private final Path filePath;
private final WatchEvent.Kind<?> eventKind;
private final Path watchedFolder;
public FileChangeEvent(Object source, Path filePath, WatchEvent.Kind<?> eventKind, Path watchedFolder) {
super(source);
this.filePath = filePath;
this.eventKind = eventKind;
this.watchedFolder = watchedFolder;
}
}
@@ -0,0 +1,114 @@
package com.adityachandel.booklore.service.monitoring;
import com.adityachandel.booklore.model.dto.Library;
import com.adityachandel.booklore.service.LibraryProcessingService;
import com.adityachandel.booklore.service.LibraryService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.*;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Service
@AllArgsConstructor
public class MonitoringService {
private final LibraryProcessingService libraryProcessingService;
private final WatchService watchService;
private final LibraryService libraryService;
private final MonitoringTask monitoringTask;
private final Set<Path> monitoredPaths = ConcurrentHashMap.newKeySet();
private final Map<Path, Long> pathToLibraryIdMap = new ConcurrentHashMap<>();
@PostConstruct
public void initializeMonitoring() {
log.info("Initializing monitoring service...");
loadInitialPaths();
monitoringTask.monitor();
}
private void loadInitialPaths() {
libraryService.getAllLibraries()
.stream()
.filter(Library::isWatch)
.forEach(library -> {
library.getPaths().forEach(libraryPath -> {
Path path = Paths.get(libraryPath.getPath());
if (Files.isDirectory(path)) {
pathToLibraryIdMap.put(path, library.getId()); // Map path to libraryId
registerPathWithLibraryId(path);
}
});
});
log.info("Loaded initial monitored folders: {}", pathToLibraryIdMap);
}
public synchronized void registerPathWithLibraryId(Path path) {
try {
if (monitoredPaths.add(path)) {
path.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
log.info("Registered folder for monitoring: {}", path);
} else {
log.warn("Path is already registered: {}", path);
}
} catch (IOException e) {
log.error("Error registering path: {}", path, e);
}
}
public synchronized void unregisterPath(String folderPath) {
Path path = Paths.get(folderPath);
if (monitoredPaths.remove(path)) {
pathToLibraryIdMap.remove(path); // Remove the path-to-libraryId mapping
log.info("Unregistered folder from monitoring: {}", folderPath);
} else {
log.warn("Folder not found in monitored paths: {}", folderPath);
}
}
@EventListener
public void handleFileChangeEvent(FileChangeEvent event) {
Path filePath = event.getFilePath();
Path watchedFolder = event.getWatchedFolder();
Long libraryId = pathToLibraryIdMap.get(watchedFolder);
if (libraryId != null) {
Thread.startVirtualThread(() -> {
try {
libraryProcessingService.processFile(libraryId, watchedFolder.toString(), filePath.toString());
} catch (InvalidDataAccessApiUsageException e) {
log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
}
log.info("Parsing task completed!");
});
log.info("Handling file change event for library {}: {} (from folder: {}) with kind: {}", libraryId, filePath, watchedFolder, event.getEventKind());
} else {
log.warn("No libraryId found for watched folder: {}", watchedFolder);
}
}
@PreDestroy
public void stopMonitoring() {
log.info("Shutting down monitoring service...");
if (watchService != null) {
try {
watchService.close();
} catch (IOException e) {
log.error("Exception while closing the WatchService", e);
}
}
}
}
@@ -0,0 +1,57 @@
package com.adityachandel.booklore.service.monitoring;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
@Slf4j
@Service
@AllArgsConstructor
public class MonitoringTask {
private final WatchService watchService;
private final ApplicationEventPublisher eventPublisher;
private static final String PDF_EXTENSION = ".pdf";
private static final String EPUB_EXTENSION = ".epub";
@Async
public void monitor() {
log.info("START_MONITORING");
try {
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
Path fileName = (Path) event.context();
Path directory = (Path) key.watchable();
Path fullPath = directory.resolve(fileName);
if (isPdfOrEpub(fileName)) {
log.info("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}",
kind,
fileName,
fullPath,
directory);
eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, directory));
}
}
key.reset();
}
} catch (InterruptedException e) {
log.warn("Monitoring task interrupted", e);
Thread.currentThread().interrupt();
}
}
private boolean isPdfOrEpub(Path fileName) {
String fileNameStr = fileName.toString().toLowerCase();
return fileNameStr.endsWith(PDF_EXTENSION) || fileNameStr.endsWith(EPUB_EXTENSION);
}
}
@@ -1,9 +1,10 @@
CREATE TABLE IF NOT EXISTS library
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) UNIQUE NOT NULL,
sort VARCHAR(255) NULL,
icon VARCHAR(64) NOT NULL
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) UNIQUE NOT NULL,
sort VARCHAR(255) NULL,
icon VARCHAR(64) NOT NULL,
watch BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE TABLE IF NOT EXISTS library_path
@@ -62,7 +62,7 @@
<div class="flex flex-col gap-x-4 mt-auto">
<p-divider></p-divider>
<div class="flex justify-between">
<p-button label="Back" icon="pi pi-arrow-left" severity="info" (onClick)="goBackClick()"></p-button>
<p-button label="To Metadata List" icon="pi pi-arrow-left" severity="info" (onClick)="goBackClick()"></p-button>
<div class="flex gap-x-4 justify-end">
<p-button label="Unlock All" icon="pi pi-lock-open" [outlined]="true" severity="success" (onClick)="unlockAll()"></p-button>
<p-button label="Lock All" icon="pi pi-lock" [outlined]="true" severity="warn" (onClick)="lockAll()"></p-button>