Merge pull request #1170 from booklore-app/develop
Merge develop into master for the release
This commit is contained in:
+81
-18
@@ -26,6 +26,7 @@ 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.MonitoringRegistrationService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -44,9 +45,11 @@ import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -69,6 +72,7 @@ public class BookDropService {
|
||||
private final BookdropFileMapper mapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final FileMovingHelper fileMovingHelper;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
|
||||
private static final int CHUNK_SIZE = 100;
|
||||
|
||||
@@ -206,27 +210,86 @@ public class BookDropService {
|
||||
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);
|
||||
// Collect all libraries that will be affected by moves
|
||||
Set<Long> affectedLibraries = collectAffectedLibraries(ids, metadataById, defaultLibraryId, defaultPathId);
|
||||
|
||||
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunk);
|
||||
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
|
||||
// Unregister monitoring for all affected libraries
|
||||
unregisterAffectedLibraries(affectedLibraries);
|
||||
|
||||
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();
|
||||
try {
|
||||
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();
|
||||
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) {
|
||||
@@ -302,7 +365,7 @@ public class BookDropService {
|
||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
|
||||
LibraryPathEntity path = library.getLibraryPaths().stream()
|
||||
.filter(p -> p.getId() == pathId)
|
||||
.filter(p -> p.getId().equals(pathId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
|
||||
|
||||
@@ -328,8 +391,7 @@ public class BookDropService {
|
||||
return performFileMove(bookdropFile, source, target, library, path, metadata);
|
||||
}
|
||||
|
||||
private BookdropFileResult performFileMove(BookdropFileEntity bookdropFile, Path source, Path target,
|
||||
LibraryEntity library, LibraryPathEntity path, BookMetadata metadata) {
|
||||
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());
|
||||
@@ -487,4 +549,5 @@ public class BookDropService {
|
||||
|
||||
private record FileProcessingContext(Long libraryId, Long pathId, BookMetadata metadata) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-2
@@ -49,8 +49,7 @@ public class BookdropMonitoringService {
|
||||
this.watchService = FileSystems.getDefault().newWatchService();
|
||||
this.watchKey = bookdrop.register(watchService,
|
||||
StandardWatchEventKinds.ENTRY_CREATE,
|
||||
StandardWatchEventKinds.ENTRY_DELETE,
|
||||
StandardWatchEventKinds.ENTRY_MODIFY);
|
||||
StandardWatchEventKinds.ENTRY_DELETE);
|
||||
this.running = true;
|
||||
this.paused = false;
|
||||
this.watchThread = new Thread(this::processEvents, "BookdropFolderWatcher");
|
||||
|
||||
+32
-21
@@ -39,33 +39,44 @@ public class UnifiedFileMoveService {
|
||||
}
|
||||
|
||||
Path currentFilePath = bookEntity.getFullFilePath();
|
||||
if (!Files.exists(currentFilePath)) {
|
||||
log.warn("File does not exist for book ID {}: {}. Skipping file move.", bookEntity.getId(), currentFilePath);
|
||||
return;
|
||||
}
|
||||
Path expectedFilePath = fileMovingHelper.generateNewFilePath(bookEntity, pattern);
|
||||
|
||||
// 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);
|
||||
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);
|
||||
}
|
||||
});
|
||||
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
|
||||
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath())
|
||||
.toAbsolutePath().normalize();
|
||||
|
||||
// unregister the entire library to suppress all watch events during the move
|
||||
monitoringRegistrationService.unregisterLibrary(libraryId);
|
||||
|
||||
try {
|
||||
monitoredFileOperationService.executeWithMonitoringSuspended(
|
||||
currentFilePath, expectedFilePath, libraryId, () -> {
|
||||
try {
|
||||
boolean moved = fileMovingHelper.moveBookFileIfNeeded(bookEntity, pattern);
|
||||
if (moved) {
|
||||
log.info("Successfully moved file for book ID {} from {} to {}",
|
||||
bookEntity.getId(), currentFilePath, bookEntity.getFullFilePath());
|
||||
}
|
||||
return moved;
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
|
||||
throw new RuntimeException("File move failed", e);
|
||||
}
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
// re-register all folders under the library after the move
|
||||
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -178,7 +189,7 @@ public class UnifiedFileMoveService {
|
||||
*/
|
||||
public interface BatchMoveCallback {
|
||||
void onBookMoved(BookEntity book);
|
||||
|
||||
void onBookMoveFailed(BookEntity book, Exception error);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+11
-2
@@ -96,8 +96,17 @@ public class HardcoverParser implements BookParser {
|
||||
metadata.setCategories(doc.getGenres());
|
||||
|
||||
if (doc.getIsbns() != null) {
|
||||
metadata.setIsbn10(doc.getIsbns().stream().filter(isbn -> isbn.length() == 10).findFirst().orElse(null));
|
||||
metadata.setIsbn13(doc.getIsbns().stream().filter(isbn -> isbn.length() == 13).findFirst().orElse(null));
|
||||
String inputIsbn = fetchMetadataRequest.getIsbn();
|
||||
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);
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ public class LibraryFileEventProcessor {
|
||||
ScheduledFuture<?> pendingDelete = pendingDeletes.remove(path);
|
||||
if (pendingDelete != null) {
|
||||
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;
|
||||
}
|
||||
// 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.BookFileProcessorRegistry;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -57,6 +58,8 @@ class BookDropServiceTest {
|
||||
@Mock
|
||||
private BookdropFileRepository bookdropFileRepository;
|
||||
@Mock
|
||||
private MonitoringRegistrationService monitoringRegistrationService;
|
||||
@Mock
|
||||
private LibraryRepository libraryRepository;
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@@ -55,7 +55,6 @@
|
||||
flex-direction: column;
|
||||
height: 100dvh;
|
||||
overflow: hidden;
|
||||
background-color: #171717;
|
||||
}
|
||||
|
||||
#epubContainer {
|
||||
@@ -165,8 +164,3 @@
|
||||
::ng-deep .p-divider.p-divider-horizontal {
|
||||
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 {BookService} from '../../../book/service/book.service';
|
||||
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 {ProgressSpinner} from 'primeng/progressspinner';
|
||||
|
||||
@@ -47,7 +47,7 @@ export class MainDashboardComponent implements OnInit {
|
||||
|
||||
this.lastReadBooks$ = this.bookService.bookState$.pipe(
|
||||
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) => {
|
||||
const aTime = new Date(a.lastReadTime!).getTime();
|
||||
const bTime = new Date(b.lastReadTime!).getTime();
|
||||
|
||||
Reference in New Issue
Block a user