Merge pull request #1170 from booklore-app/develop
Merge develop into master for the release
This commit is contained in:
+80
-17
@@ -26,6 +26,7 @@ import com.adityachandel.booklore.service.file.FileMovingHelper;
|
|||||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||||
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
||||||
|
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||||
import com.adityachandel.booklore.util.FileUtils;
|
import com.adityachandel.booklore.util.FileUtils;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
@@ -44,9 +45,11 @@ import java.nio.file.Paths;
|
|||||||
import java.nio.file.StandardCopyOption;
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
@@ -69,6 +72,7 @@ public class BookDropService {
|
|||||||
private final BookdropFileMapper mapper;
|
private final BookdropFileMapper mapper;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
private final FileMovingHelper fileMovingHelper;
|
private final FileMovingHelper fileMovingHelper;
|
||||||
|
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||||
|
|
||||||
private static final int CHUNK_SIZE = 100;
|
private static final int CHUNK_SIZE = 100;
|
||||||
|
|
||||||
@@ -206,27 +210,86 @@ public class BookDropService {
|
|||||||
BookdropFinalizeResult results,
|
BookdropFinalizeResult results,
|
||||||
AtomicInteger failedCount,
|
AtomicInteger failedCount,
|
||||||
AtomicInteger totalFilesProcessed) {
|
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);
|
// Collect all libraries that will be affected by moves
|
||||||
|
Set<Long> affectedLibraries = collectAffectedLibraries(ids, metadataById, defaultLibraryId, defaultPathId);
|
||||||
|
|
||||||
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunk);
|
// Unregister monitoring for all affected libraries
|
||||||
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
|
unregisterAffectedLibraries(affectedLibraries);
|
||||||
|
|
||||||
for (Long id : chunk) {
|
try {
|
||||||
BookdropFileEntity file = fileMap.get(id);
|
for (int i = 0; i < ids.size(); i += CHUNK_SIZE) {
|
||||||
if (file == null) {
|
int end = Math.min(i + CHUNK_SIZE, ids.size());
|
||||||
log.warn("File ID {} missing in DB during finalizeImport chunk processing", id);
|
List<Long> chunk = ids.subList(i, end);
|
||||||
failedCount.incrementAndGet();
|
|
||||||
|
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();
|
totalFilesProcessed.incrementAndGet();
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
|
}
|
||||||
totalFilesProcessed.incrementAndGet();
|
} finally {
|
||||||
|
// Re-register monitoring for all affected libraries
|
||||||
|
reregisterAffectedLibraries(affectedLibraries);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<Long> collectAffectedLibraries(List<Long> ids,
|
||||||
|
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById,
|
||||||
|
Long defaultLibraryId,
|
||||||
|
Long defaultPathId) {
|
||||||
|
Set<Long> affectedLibraries = new HashSet<>();
|
||||||
|
|
||||||
|
List<BookdropFileEntity> files = bookdropFileRepository.findAllById(ids);
|
||||||
|
|
||||||
|
for (BookdropFileEntity fileEntity : files) {
|
||||||
|
try {
|
||||||
|
FileProcessingContext context = prepareFileProcessingContext(fileEntity, metadataById.get(fileEntity.getId()), defaultLibraryId, defaultPathId);
|
||||||
|
affectedLibraries.add(context.libraryId());
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Failed to determine library for file {}: {}", fileEntity.getId(), e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.info("Collected {} unique libraries for monitoring unregistration: {}", affectedLibraries.size(), affectedLibraries);
|
||||||
|
return affectedLibraries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void unregisterAffectedLibraries(Set<Long> libraryIds) {
|
||||||
|
for (Long libraryId : libraryIds) {
|
||||||
|
monitoringRegistrationService.unregisterLibrary(libraryId);
|
||||||
|
log.debug("Unregistered library {} from monitoring", libraryId);
|
||||||
|
}
|
||||||
|
log.info("Unregistered {} libraries from monitoring", libraryIds.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void reregisterAffectedLibraries(Set<Long> libraryIds) {
|
||||||
|
for (Long libraryId : libraryIds) {
|
||||||
|
try {
|
||||||
|
LibraryEntity library = libraryRepository.findById(libraryId).orElse(null);
|
||||||
|
if (library != null) {
|
||||||
|
for (LibraryPathEntity libPath : library.getLibraryPaths()) {
|
||||||
|
Path libraryRoot = Path.of(libPath.getPath());
|
||||||
|
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
|
||||||
|
log.debug("Re-registered library {} path {} for monitoring", libraryId, libraryRoot);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Failed to re-register library {} for monitoring: {}", libraryId, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.info("Re-registered {} libraries for monitoring", libraryIds.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void updateFinalResults(BookdropFinalizeResult results, AtomicInteger totalFilesProcessed, AtomicInteger failedCount) {
|
private void updateFinalResults(BookdropFinalizeResult results, AtomicInteger totalFilesProcessed, AtomicInteger failedCount) {
|
||||||
@@ -302,7 +365,7 @@ public class BookDropService {
|
|||||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
|
|
||||||
LibraryPathEntity path = library.getLibraryPaths().stream()
|
LibraryPathEntity path = library.getLibraryPaths().stream()
|
||||||
.filter(p -> p.getId() == pathId)
|
.filter(p -> p.getId().equals(pathId))
|
||||||
.findFirst()
|
.findFirst()
|
||||||
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
|
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
|
||||||
|
|
||||||
@@ -328,8 +391,7 @@ public class BookDropService {
|
|||||||
return performFileMove(bookdropFile, source, target, library, path, metadata);
|
return performFileMove(bookdropFile, source, target, library, path, metadata);
|
||||||
}
|
}
|
||||||
|
|
||||||
private BookdropFileResult performFileMove(BookdropFileEntity bookdropFile, Path source, Path target,
|
private BookdropFileResult performFileMove(BookdropFileEntity bookdropFile, Path source, Path target, LibraryEntity library, LibraryPathEntity path, BookMetadata metadata) {
|
||||||
LibraryEntity library, LibraryPathEntity path, BookMetadata metadata) {
|
|
||||||
Path tempPath = null;
|
Path tempPath = null;
|
||||||
try {
|
try {
|
||||||
tempPath = Files.createTempFile("bookdrop-finalize-", bookdropFile.getFileName());
|
tempPath = Files.createTempFile("bookdrop-finalize-", bookdropFile.getFileName());
|
||||||
@@ -488,3 +550,4 @@ public class BookDropService {
|
|||||||
private record FileProcessingContext(Long libraryId, Long pathId, BookMetadata metadata) {
|
private record FileProcessingContext(Long libraryId, Long pathId, BookMetadata metadata) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -49,8 +49,7 @@ public class BookdropMonitoringService {
|
|||||||
this.watchService = FileSystems.getDefault().newWatchService();
|
this.watchService = FileSystems.getDefault().newWatchService();
|
||||||
this.watchKey = bookdrop.register(watchService,
|
this.watchKey = bookdrop.register(watchService,
|
||||||
StandardWatchEventKinds.ENTRY_CREATE,
|
StandardWatchEventKinds.ENTRY_CREATE,
|
||||||
StandardWatchEventKinds.ENTRY_DELETE,
|
StandardWatchEventKinds.ENTRY_DELETE);
|
||||||
StandardWatchEventKinds.ENTRY_MODIFY);
|
|
||||||
this.running = true;
|
this.running = true;
|
||||||
this.paused = false;
|
this.paused = false;
|
||||||
this.watchThread = new Thread(this::processEvents, "BookdropFolderWatcher");
|
this.watchThread = new Thread(this::processEvents, "BookdropFolderWatcher");
|
||||||
|
|||||||
+31
-20
@@ -39,33 +39,44 @@ public class UnifiedFileMoveService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Path currentFilePath = bookEntity.getFullFilePath();
|
Path currentFilePath = bookEntity.getFullFilePath();
|
||||||
if (!Files.exists(currentFilePath)) {
|
Path expectedFilePath = fileMovingHelper.generateNewFilePath(bookEntity, pattern);
|
||||||
log.warn("File does not exist for book ID {}: {}. Skipping file move.", bookEntity.getId(), currentFilePath);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if current path differs from expected pattern
|
// Check if current path differs from expected pattern
|
||||||
Path expectedFilePath = fileMovingHelper.generateNewFilePath(bookEntity, pattern);
|
|
||||||
if (currentFilePath.equals(expectedFilePath)) {
|
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());
|
log.debug("File for book ID {} is already in the correct location according to library pattern. No move needed.", bookEntity.getId());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath);
|
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
|
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
|
||||||
monitoredFileOperationService.executeWithMonitoringSuspended(currentFilePath, expectedFilePath, bookEntity.getLibraryPath().getLibrary().getId(), () -> {
|
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath())
|
||||||
try {
|
.toAbsolutePath().normalize();
|
||||||
boolean moved = fileMovingHelper.moveBookFileIfNeeded(bookEntity, pattern);
|
|
||||||
if (moved) {
|
// unregister the entire library to suppress all watch events during the move
|
||||||
log.info("Successfully moved file for book ID {} from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, bookEntity.getFullFilePath());
|
monitoringRegistrationService.unregisterLibrary(libraryId);
|
||||||
}
|
|
||||||
return moved;
|
try {
|
||||||
} catch (IOException e) {
|
monitoredFileOperationService.executeWithMonitoringSuspended(
|
||||||
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
|
currentFilePath, expectedFilePath, libraryId, () -> {
|
||||||
throw new RuntimeException("File move failed", e);
|
try {
|
||||||
}
|
boolean moved = fileMovingHelper.moveBookFileIfNeeded(bookEntity, pattern);
|
||||||
});
|
if (moved) {
|
||||||
|
log.info("Successfully moved file for book ID {} from {} to {}",
|
||||||
|
bookEntity.getId(), currentFilePath, bookEntity.getFullFilePath());
|
||||||
|
}
|
||||||
|
return moved;
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
|
||||||
|
throw new RuntimeException("File move failed", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
// re-register all folders under the library after the move
|
||||||
|
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -178,7 +189,7 @@ public class UnifiedFileMoveService {
|
|||||||
*/
|
*/
|
||||||
public interface BatchMoveCallback {
|
public interface BatchMoveCallback {
|
||||||
void onBookMoved(BookEntity book);
|
void onBookMoved(BookEntity book);
|
||||||
|
|
||||||
void onBookMoveFailed(BookEntity book, Exception error);
|
void onBookMoveFailed(BookEntity book, Exception error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+11
-2
@@ -96,8 +96,17 @@ public class HardcoverParser implements BookParser {
|
|||||||
metadata.setCategories(doc.getGenres());
|
metadata.setCategories(doc.getGenres());
|
||||||
|
|
||||||
if (doc.getIsbns() != null) {
|
if (doc.getIsbns() != null) {
|
||||||
metadata.setIsbn10(doc.getIsbns().stream().filter(isbn -> isbn.length() == 10).findFirst().orElse(null));
|
String inputIsbn = fetchMetadataRequest.getIsbn();
|
||||||
metadata.setIsbn13(doc.getIsbns().stream().filter(isbn -> isbn.length() == 13).findFirst().orElse(null));
|
if (inputIsbn != null && inputIsbn.length() == 10 && doc.getIsbns().contains(inputIsbn)) {
|
||||||
|
metadata.setIsbn10(inputIsbn);
|
||||||
|
} else {
|
||||||
|
metadata.setIsbn10(doc.getIsbns().stream().filter(isbn -> isbn.length() == 10).findFirst().orElse(null));
|
||||||
|
}
|
||||||
|
if (inputIsbn != null && inputIsbn.length() == 13 && doc.getIsbns().contains(inputIsbn)) {
|
||||||
|
metadata.setIsbn13(inputIsbn);
|
||||||
|
} else {
|
||||||
|
metadata.setIsbn13(doc.getIsbns().stream().filter(isbn -> isbn.length() == 13).findFirst().orElse(null));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null);
|
metadata.setThumbnailUrl(doc.getImage() != null ? doc.getImage().getUrl() : null);
|
||||||
|
|||||||
+1
-1
@@ -72,7 +72,7 @@ public class LibraryFileEventProcessor {
|
|||||||
ScheduledFuture<?> pendingDelete = pendingDeletes.remove(path);
|
ScheduledFuture<?> pendingDelete = pendingDeletes.remove(path);
|
||||||
if (pendingDelete != null) {
|
if (pendingDelete != null) {
|
||||||
pendingDelete.cancel(false);
|
pendingDelete.cancel(false);
|
||||||
log.info("[DEBOUNCE] CREATE ignored because pending DELETE exists for '{}'", path);
|
log.debug("[DEBOUNCE] CREATE ignored because pending DELETE exists for '{}'", path);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Otherwise process CREATE immediately
|
// Otherwise process CREATE immediately
|
||||||
|
|||||||
+3
@@ -23,6 +23,7 @@ import com.adityachandel.booklore.service.file.FileMovingHelper;
|
|||||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||||
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
||||||
|
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.junit.Ignore;
|
import org.junit.Ignore;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
@@ -57,6 +58,8 @@ class BookDropServiceTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private BookdropFileRepository bookdropFileRepository;
|
private BookdropFileRepository bookdropFileRepository;
|
||||||
@Mock
|
@Mock
|
||||||
|
private MonitoringRegistrationService monitoringRegistrationService;
|
||||||
|
@Mock
|
||||||
private LibraryRepository libraryRepository;
|
private LibraryRepository libraryRepository;
|
||||||
@Mock
|
@Mock
|
||||||
private BookRepository bookRepository;
|
private BookRepository bookRepository;
|
||||||
|
|||||||
@@ -55,7 +55,6 @@
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
height: 100dvh;
|
height: 100dvh;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background-color: #171717;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#epubContainer {
|
#epubContainer {
|
||||||
@@ -165,8 +164,3 @@
|
|||||||
::ng-deep .p-divider.p-divider-horizontal {
|
::ng-deep .p-divider.p-divider-horizontal {
|
||||||
margin: 0.25rem 0 0.5rem 0 !important;
|
margin: 0.25rem 0 0.5rem 0 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
::ng-deep .p-drawer-left,
|
|
||||||
::ng-deep .p-drawer-right {
|
|
||||||
background-color: #171717 !important;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {AsyncPipe} from '@angular/common';
|
|||||||
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
|
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
|
||||||
import {BookService} from '../../../book/service/book.service';
|
import {BookService} from '../../../book/service/book.service';
|
||||||
import {BookState} from '../../../book/model/state/book-state.model';
|
import {BookState} from '../../../book/model/state/book-state.model';
|
||||||
import {Book} from '../../../book/model/book.model';
|
import {Book, ReadStatus} from '../../../book/model/book.model';
|
||||||
import {UserService} from '../../../settings/user-management/user.service';
|
import {UserService} from '../../../settings/user-management/user.service';
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@ export class MainDashboardComponent implements OnInit {
|
|||||||
|
|
||||||
this.lastReadBooks$ = this.bookService.bookState$.pipe(
|
this.lastReadBooks$ = this.bookService.bookState$.pipe(
|
||||||
map((state: BookState) => (
|
map((state: BookState) => (
|
||||||
(state.books || []).filter(book => book.lastReadTime)
|
(state.books || []).filter(book => book.lastReadTime && (book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED))
|
||||||
.sort((a, b) => {
|
.sort((a, b) => {
|
||||||
const aTime = new Date(a.lastReadTime!).getTime();
|
const aTime = new Date(a.lastReadTime!).getTime();
|
||||||
const bTime = new Date(b.lastReadTime!).getTime();
|
const bTime = new Date(b.lastReadTime!).getTime();
|
||||||
|
|||||||
Reference in New Issue
Block a user