Merge pull request #1117 from booklore-app/develop
Merge develop into master for the release
This commit is contained in:
@@ -4,6 +4,7 @@ build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
example-chart/charts/
|
||||
|
||||
## MacOS ###
|
||||
.DS_Store
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ RUN gradle clean build -x test
|
||||
# Stage 3: Final image
|
||||
FROM eclipse-temurin:21-jre-alpine
|
||||
|
||||
RUN apk update && apk add nginx gettext
|
||||
RUN apk update && apk add nginx gettext su-exec
|
||||
|
||||
COPY ./nginx.conf /etc/nginx/nginx.conf
|
||||
COPY --from=angular-build /angular-app/dist/booklore/browser /usr/share/nginx/html
|
||||
|
||||
@@ -101,8 +101,8 @@ services:
|
||||
# image: ghcr.io/booklore-app/booklore:latest
|
||||
container_name: booklore
|
||||
environment:
|
||||
- PUID=1000
|
||||
- PGID=1000
|
||||
- USER_ID=0 # Modify this if the volume's ownership is not root
|
||||
- GROUP_ID=0 # Modify this if the volume's ownership is not root
|
||||
- TZ=Etc/UTC
|
||||
- DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore # Only modify this if you're familiar with JDBC and your database setup
|
||||
- DATABASE_USERNAME=booklore # Must match MYSQL_USER defined in the mariadb container
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.adityachandel.booklore.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Builder
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class DuplicateFileInfo {
|
||||
private final Long bookId;
|
||||
private final String fileName;
|
||||
private final String fullPath;
|
||||
private final String hash;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.adityachandel.booklore.model;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.enums.FileProcessStatus;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.ToString;
|
||||
|
||||
@Builder
|
||||
@Getter
|
||||
@ToString
|
||||
@AllArgsConstructor
|
||||
public class FileProcessResult {
|
||||
private final Book book;
|
||||
private final FileProcessStatus status;
|
||||
@Builder.Default
|
||||
private final DuplicateFileInfo duplicate = null;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Setter
|
||||
@Getter
|
||||
@Builder
|
||||
public class DuplicateFileNotification {
|
||||
private long libraryId;
|
||||
private String libraryName;
|
||||
private long fileId;
|
||||
private String fileName;
|
||||
private String fullPath;
|
||||
private String hash;
|
||||
private Instant timestamp;
|
||||
}
|
||||
+3
@@ -21,6 +21,9 @@ public class LibraryFile {
|
||||
private BookFileType bookFileType;
|
||||
|
||||
public Path getFullPath() {
|
||||
if (fileSubPath == null || fileSubPath.isEmpty()) {
|
||||
return Paths.get(libraryPathEntity.getPath(), fileName);
|
||||
}
|
||||
return Paths.get(libraryPathEntity.getPath(), fileSubPath, fileName);
|
||||
}
|
||||
}
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum FileProcessStatus {
|
||||
NEW,
|
||||
DUPLICATE,
|
||||
UPDATED
|
||||
}
|
||||
@@ -12,6 +12,7 @@ public enum Topic {
|
||||
BOOK_METADATA_BATCH_UPDATE("/queue/book-metadata-batch-update"),
|
||||
BOOK_METADATA_BATCH_PROGRESS("/queue/book-metadata-batch-progress"),
|
||||
BOOKDROP_FILE("/queue/bookdrop-file"),
|
||||
DUPLICATE_FILE("/queue/duplicate-file"),
|
||||
TASK("/queue/task"),
|
||||
LOG("/queue/log");
|
||||
|
||||
|
||||
+17
-10
@@ -8,7 +8,7 @@ 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.MonitoringService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -41,6 +41,7 @@ public class AdditionalFileService {
|
||||
|
||||
private final BookAdditionalFileRepository additionalFileRepository;
|
||||
private final AdditionalFileMapper additionalFileMapper;
|
||||
private final MonitoringProtectionService monitoringProtectionService;
|
||||
|
||||
public List<AdditionalFile> getAdditionalFilesByBookId(Long bookId) {
|
||||
List<BookAdditionalFileEntity> entities = additionalFileRepository.findByBookId(bookId);
|
||||
@@ -60,16 +61,21 @@ 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 physical file
|
||||
try {
|
||||
Files.deleteIfExists(file.getFullFilePath());
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete physical file: {}", file.getFullFilePath(), e);
|
||||
}
|
||||
|
||||
// Delete database record
|
||||
additionalFileRepository.delete(file);
|
||||
// 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");
|
||||
}
|
||||
|
||||
public ResponseEntity<Resource> downloadAdditionalFile(Long fileId) throws IOException {
|
||||
@@ -92,4 +98,5 @@ public class AdditionalFileService {
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
|
||||
.body(resource);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,6 +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.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -58,6 +59,7 @@ public class BookService {
|
||||
private final BookQueryService bookQueryService;
|
||||
private final UserProgressService userProgressService;
|
||||
private final BookDownloadService bookDownloadService;
|
||||
private final MonitoringProtectionService monitoringProtectionService;
|
||||
|
||||
|
||||
private void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
@@ -493,29 +495,34 @@ public class BookService {
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(ids);
|
||||
List<Long> failedFileDeletions = new ArrayList<>();
|
||||
|
||||
for (BookEntity book : books) {
|
||||
Path fullFilePath = book.getFullFilePath();
|
||||
try {
|
||||
if (Files.exists(fullFilePath)) {
|
||||
Files.delete(fullFilePath);
|
||||
Set<Path> libraryRoots = book.getLibrary().getLibraryPaths().stream()
|
||||
.map(LibraryPathEntity::getPath)
|
||||
.map(Paths::get)
|
||||
.map(Path::normalize)
|
||||
.collect(Collectors.toSet());
|
||||
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());
|
||||
|
||||
deleteEmptyParentDirsUpToLibraryFolders(fullFilePath.getParent(), libraryRoots);
|
||||
deleteEmptyParentDirsUpToLibraryFolders(fullFilePath.getParent(), libraryRoots);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete book file: {}", fullFilePath, e);
|
||||
failedFileDeletions.add(book.getId());
|
||||
}
|
||||
} catch (IOException 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);
|
||||
bookRepository.deleteAll(books);
|
||||
BookDeletionResponse response = new BookDeletionResponse(ids, failedFileDeletions);
|
||||
return failedFileDeletions.isEmpty()
|
||||
? ResponseEntity.ok(response)
|
||||
: ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response);
|
||||
}, "book deletion");
|
||||
}
|
||||
|
||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
|
||||
@@ -582,4 +589,5 @@ public class BookService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+127
-132
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.bookdrop;
|
||||
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;
|
||||
@@ -26,7 +27,7 @@ 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.metadata.MetadataRefreshService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||
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;
|
||||
@@ -62,7 +63,7 @@ public class BookDropService {
|
||||
private final BookdropFileRepository bookdropFileRepository;
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final MonitoringService monitoringService;
|
||||
private final MonitoringProtectionService monitoringProtectionService;
|
||||
private final BookdropMonitoringService bookdropMonitoringService;
|
||||
private final NotificationService notificationService;
|
||||
private final MetadataRefreshService metadataRefreshService;
|
||||
@@ -88,112 +89,103 @@ public class BookDropService {
|
||||
}
|
||||
|
||||
public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) {
|
||||
boolean monitoringWasActive = !monitoringService.isPaused();
|
||||
if (monitoringWasActive) monitoringService.pauseMonitoring();
|
||||
bookdropMonitoringService.pauseMonitoring();
|
||||
return monitoringProtectionService.executeWithProtection(() -> {
|
||||
try {
|
||||
bookdropMonitoringService.pauseMonitoring();
|
||||
|
||||
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
|
||||
.processedAt(Instant.now())
|
||||
.build();
|
||||
Long defaultLibraryId = request.getDefaultLibraryId();
|
||||
Long defaultPathId = request.getDefaultPathId();
|
||||
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()));
|
||||
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();
|
||||
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);
|
||||
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());
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
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()));
|
||||
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;
|
||||
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();
|
||||
}
|
||||
}
|
||||
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();
|
||||
} 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);
|
||||
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);
|
||||
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);
|
||||
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()));
|
||||
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;
|
||||
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();
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
|
||||
if (monitoringWasActive) {
|
||||
Thread.startVirtualThread(() -> {
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
monitoringService.resumeMonitoring();
|
||||
bookdropMonitoringService.resumeMonitoring();
|
||||
log.info("Monitoring resumed after 5s delay following finalizeImport");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("Interrupted while delaying resume of monitoring after finalizeImport");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return results;
|
||||
}, "bookdrop finalize import");
|
||||
}
|
||||
|
||||
private void processFile(
|
||||
@@ -285,51 +277,53 @@ public class BookDropService {
|
||||
return failureResult(targetFile.getName(), "File already exists in the library '" + library.getName() + "'");
|
||||
}
|
||||
|
||||
try {
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.move(source, target);
|
||||
|
||||
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
|
||||
|
||||
Book processedBook = processFile(targetFile.getName(), library, path, targetFile,
|
||||
BookFileExtension.fromFileName(bookdropFile.getFileName())
|
||||
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
|
||||
.getType());
|
||||
|
||||
BookEntity bookEntity = bookRepository.findById(processedBook.getId())
|
||||
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
|
||||
|
||||
notificationService.sendMessage(Topic.BOOK_ADD, processedBook);
|
||||
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);
|
||||
return monitoringProtectionService.executeWithProtection(() -> {
|
||||
try {
|
||||
if (Files.exists(target)) {
|
||||
Files.deleteIfExists(target);
|
||||
log.info("Cleaned up partially created target file: {}", target);
|
||||
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);
|
||||
}
|
||||
} catch (Exception cleanupException) {
|
||||
log.warn("Failed to cleanup target file after move error: {}", target, cleanupException);
|
||||
|
||||
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());
|
||||
}
|
||||
return failureResult(bookdropFile.getFileName(), "Failed to move file: " + e.getMessage());
|
||||
}
|
||||
}, "bookdrop file move");
|
||||
}
|
||||
|
||||
private BookdropFileResult failureResult(String fileName, String message) {
|
||||
@@ -340,7 +334,7 @@ public class BookDropService {
|
||||
.build();
|
||||
}
|
||||
|
||||
private Book processFile(String fileName, LibraryEntity library, LibraryPathEntity path, File file, BookFileType type) {
|
||||
private FileProcessResult processFile(String fileName, LibraryEntity library, LibraryPathEntity path, File file, BookFileType type) {
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.libraryEntity(library)
|
||||
.libraryPathEntity(path)
|
||||
@@ -435,4 +429,5 @@ public class BookDropService {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+7
-8
@@ -21,13 +21,12 @@ public class BookEventBroadcaster {
|
||||
public void broadcastBookAddEvent(Book book) {
|
||||
Long libraryId = book.getLibraryId();
|
||||
userService.getBookLoreUsers().stream()
|
||||
.filter(u -> u.getPermissions().isAdmin() || u.getAssignedLibraries().stream()
|
||||
.anyMatch(lib -> lib.getId().equals(libraryId)))
|
||||
.forEach(u -> {
|
||||
String username = u.getUsername();
|
||||
messagingTemplate.convertAndSendToUser(username, Topic.BOOK_ADD.getPath(), book);
|
||||
messagingTemplate.convertAndSendToUser(username, Topic.LOG.getPath(), createLogNotification("Book added: " + book.getFileName()));
|
||||
log.debug("Sent BOOK_ADD and LOG notifications for '{}' to user '{}'", book.getFileName(), username);
|
||||
});
|
||||
.filter(u -> u.getPermissions().isAdmin() || u.getAssignedLibraries().stream()
|
||||
.anyMatch(lib -> lib.getId().equals(libraryId)))
|
||||
.forEach(u -> {
|
||||
String username = u.getUsername();
|
||||
messagingTemplate.convertAndSendToUser(username, Topic.BOOK_ADD.getPath(), book);
|
||||
messagingTemplate.convertAndSendToUser(username, Topic.LOG.getPath(), createLogNotification("Book added: " + book.getFileName()));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+8
-30
@@ -15,7 +15,7 @@ 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.MonitoringService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
|
||||
import com.adityachandel.booklore.util.PathPatternResolver;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -37,7 +37,7 @@ public class FileMoveService {
|
||||
private final BookMapper bookMapper;
|
||||
private final NotificationService notificationService;
|
||||
private final LibraryService libraryService;
|
||||
private final MonitoringService monitoringService;
|
||||
private final MonitoringProtectionService monitoringProtectionService;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public void moveFiles(FileMoveRequest request) {
|
||||
@@ -49,29 +49,22 @@ public class FileMoveService {
|
||||
|
||||
Set<Long> libraryIds = new HashSet<>();
|
||||
List<Book> updatedBooks = new ArrayList<>();
|
||||
boolean didPause = pauseMonitoringIfNeeded();
|
||||
|
||||
try {
|
||||
monitoringProtectionService.executeWithProtection(() -> {
|
||||
for (BookEntity book : books) {
|
||||
processBookMove(book, defaultPattern, updatedBooks, libraryIds);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
} finally {
|
||||
resumeMonitoringWithDelay(didPause);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean pauseMonitoringIfNeeded() {
|
||||
if (!monitoringService.isPaused()) {
|
||||
monitoringService.pauseMonitoring();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void processBookMove(BookEntity book, String defaultPattern, List<Book> updatedBooks, Set<Long> libraryIds) {
|
||||
if (book.getMetadata() == null) return;
|
||||
@@ -195,22 +188,7 @@ public class FileMoveService {
|
||||
}
|
||||
}
|
||||
|
||||
private void resumeMonitoringWithDelay(boolean didPause) {
|
||||
if (didPause && !monitoringService.isPaused()) {
|
||||
log.info("Monitoring already resumed by another thread.");
|
||||
} else if (didPause) {
|
||||
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");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public String generatePathFromPattern(BookEntity book, String pattern) {
|
||||
return PathPatternResolver.resolvePattern(book, pattern);
|
||||
|
||||
+94
-18
@@ -1,20 +1,26 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.DuplicateFileInfo;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.enums.FileProcessStatus;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
@Slf4j
|
||||
@@ -26,8 +32,16 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
|
||||
protected final BookMapper bookMapper;
|
||||
protected final MetadataMatchService metadataMatchService;
|
||||
protected final FileService fileService;
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
protected AbstractFileProcessor(BookRepository bookRepository, BookAdditionalFileRepository bookAdditionalFileRepository, BookCreatorService bookCreatorService, BookMapper bookMapper, FileService fileService, MetadataMatchService metadataMatchService) {
|
||||
|
||||
protected AbstractFileProcessor(BookRepository bookRepository,
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
BookCreatorService bookCreatorService,
|
||||
BookMapper bookMapper,
|
||||
FileService fileService,
|
||||
MetadataMatchService metadataMatchService) {
|
||||
this.bookRepository = bookRepository;
|
||||
this.bookAdditionalFileRepository = bookAdditionalFileRepository;
|
||||
this.bookCreatorService = bookCreatorService;
|
||||
@@ -38,34 +52,96 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
@Override
|
||||
public Book processFile(LibraryFile libraryFile) {
|
||||
public FileProcessResult processFile(LibraryFile libraryFile) {
|
||||
Path path = libraryFile.getFullPath();
|
||||
String fileName = path.getFileName().toString();
|
||||
String hash = FileFingerprint.generateHash(path);
|
||||
|
||||
Optional<Book> duplicate = fileService.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, bookRepository, bookAdditionalFileRepository, bookMapper);
|
||||
|
||||
if (duplicate.isPresent()) {
|
||||
return handleDuplicate(duplicate.get(), libraryFile);
|
||||
return handleDuplicate(duplicate.get(), libraryFile, hash);
|
||||
}
|
||||
|
||||
Long libraryId = libraryFile.getLibraryEntity().getId();
|
||||
return bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
|
||||
.map(bookMapper::toBook)
|
||||
.orElseGet(() -> createAndMapBook(libraryFile, hash));
|
||||
.map(b -> new FileProcessResult(b, FileProcessStatus.DUPLICATE, createDuplicateInfo(b, libraryFile, hash)))
|
||||
.orElseGet(() -> {
|
||||
Book book = createAndMapBook(libraryFile, hash);
|
||||
return new FileProcessResult(book, FileProcessStatus.NEW, null);
|
||||
});
|
||||
}
|
||||
|
||||
private Book handleDuplicate(Book bookDto, LibraryFile libraryFile) {
|
||||
bookRepository.findById(bookDto.getId())
|
||||
.ifPresent(entity -> {
|
||||
entity.setFileSubPath(libraryFile.getFileSubPath());
|
||||
entity.setFileName(libraryFile.getFileName());
|
||||
entity.setLibraryPath(libraryFile.getLibraryPathEntity());
|
||||
log.info("Duplicate file handled: bookId={} fileName='{}' libraryId={} subPath='{}'",
|
||||
entity.getId(),
|
||||
libraryFile.getFileName(),
|
||||
libraryFile.getLibraryEntity().getId(),
|
||||
libraryFile.getFileSubPath());
|
||||
});
|
||||
return bookDto;
|
||||
private FileProcessResult handleDuplicate(Book bookDto, LibraryFile libraryFile, String hash) {
|
||||
return bookRepository.findById(bookDto.getId())
|
||||
.map(entity -> {
|
||||
boolean sameHash = Objects.equals(entity.getCurrentHash(), hash);
|
||||
boolean sameFileName = Objects.equals(entity.getFileName(), libraryFile.getFileName());
|
||||
boolean sameSubPath = Objects.equals(entity.getFileSubPath(), libraryFile.getFileSubPath());
|
||||
boolean sameLibraryPath = Objects.equals(entity.getLibraryPath(), libraryFile.getLibraryPathEntity());
|
||||
|
||||
if (sameHash && sameFileName && sameSubPath && sameLibraryPath) {
|
||||
return new FileProcessResult(
|
||||
bookDto,
|
||||
FileProcessStatus.DUPLICATE,
|
||||
createDuplicateInfo(bookDto, libraryFile, hash)
|
||||
);
|
||||
}
|
||||
|
||||
boolean folderChanged = !sameSubPath;
|
||||
boolean updated = false;
|
||||
|
||||
if (!sameSubPath) {
|
||||
entity.setFileSubPath(libraryFile.getFileSubPath());
|
||||
updated = true;
|
||||
}
|
||||
|
||||
if (!sameFileName) {
|
||||
entity.setFileName(libraryFile.getFileName());
|
||||
updated = true;
|
||||
}
|
||||
|
||||
if (!sameLibraryPath) {
|
||||
entity.setLibraryPath(libraryFile.getLibraryPathEntity());
|
||||
updated = true;
|
||||
}
|
||||
|
||||
entity.setCurrentHash(hash);
|
||||
|
||||
/*if (folderChanged) {
|
||||
log.info("Duplicate file found in different folder: bookId={} oldSubPath='{}' newSubPath='{}'",
|
||||
entity.getId(),
|
||||
bookDto.getFileSubPath(),
|
||||
libraryFile.getFileSubPath());
|
||||
}*/
|
||||
|
||||
DuplicateFileInfo dupeInfo = createDuplicateInfo(bookMapper.toBook(entity), libraryFile, hash);
|
||||
|
||||
if (updated) {
|
||||
/*log.info("Duplicate file updated: bookId={} fileName='{}' libraryId={} subPath='{}'",
|
||||
entity.getId(),
|
||||
entity.getFileName(),
|
||||
entity.getLibraryPath().getLibrary().getId(),
|
||||
entity.getFileSubPath());*/
|
||||
entityManager.flush();
|
||||
entityManager.detach(entity);
|
||||
return new FileProcessResult(bookMapper.toBook(entity), FileProcessStatus.UPDATED, dupeInfo);
|
||||
} else {
|
||||
entityManager.detach(entity);
|
||||
return new FileProcessResult(bookMapper.toBook(entity), FileProcessStatus.DUPLICATE, dupeInfo);
|
||||
}
|
||||
})
|
||||
.orElse(new FileProcessResult(bookDto, FileProcessStatus.DUPLICATE, null));
|
||||
}
|
||||
|
||||
private DuplicateFileInfo createDuplicateInfo(Book book, LibraryFile libraryFile, String hash) {
|
||||
return new DuplicateFileInfo(
|
||||
book.getId(),
|
||||
libraryFile.getFileName(),
|
||||
libraryFile.getFullPath().toString(),
|
||||
hash
|
||||
);
|
||||
}
|
||||
|
||||
private Book createAndMapBook(LibraryFile libraryFile, String hash) {
|
||||
@@ -77,4 +153,4 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
|
||||
}
|
||||
|
||||
protected abstract BookEntity processNewFile(LibraryFile libraryFile);
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
@@ -9,6 +9,8 @@ import java.util.List;
|
||||
|
||||
public interface BookFileProcessor {
|
||||
List<BookFileType> getSupportedTypes();
|
||||
Book processFile(LibraryFile libraryFile);
|
||||
|
||||
FileProcessResult processFile(LibraryFile libraryFile);
|
||||
|
||||
boolean generateCover(BookEntity bookEntity);
|
||||
}
|
||||
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
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.enums.AdditionalFileType;
|
||||
import com.adityachandel.booklore.model.enums.BookFileExtension;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class BookDeletionService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
private final FileService fileService;
|
||||
private final NotificationService notificationService;
|
||||
|
||||
@PersistenceContext
|
||||
private final EntityManager entityManager;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void deleteRemovedAdditionalFiles(List<Long> additionalFileIds) {
|
||||
if (additionalFileIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<BookAdditionalFileEntity> additionalFiles = bookAdditionalFileRepository.findAllById(additionalFileIds);
|
||||
bookAdditionalFileRepository.deleteAll(additionalFiles);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
log.info("Deleted {} additional files from database", additionalFileIds.size());
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void processDeletedLibraryFiles(List<Long> deletedBookIds, List<LibraryFile> libraryFiles) {
|
||||
if (deletedBookIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookRepository.findAllById(deletedBookIds);
|
||||
List<Long> booksToDelete = new ArrayList<>();
|
||||
|
||||
for (BookEntity book : books) {
|
||||
if (!tryPromoteAlternativeFormatToBook(book, libraryFiles)) {
|
||||
booksToDelete.add(book.getId());
|
||||
}
|
||||
}
|
||||
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
if (!booksToDelete.isEmpty()) {
|
||||
deleteRemovedBooks(booksToDelete);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void deleteRemovedBooks(List<Long> bookIds) {
|
||||
List<BookEntity> books = bookRepository.findAllById(bookIds);
|
||||
for (BookEntity book : books) {
|
||||
try {
|
||||
deleteDirectoryRecursively(Path.of(fileService.getImagesFolder(book.getId())));
|
||||
Path backupDir = Path.of(fileService.getBookMetadataBackupPath(book.getId()));
|
||||
if (Files.exists(backupDir)) {
|
||||
deleteDirectoryRecursively(backupDir);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to clean up files for book ID {}: {}", book.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
bookRepository.deleteAll(books);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
|
||||
if (bookIds.size() > 1) log.info("Books removed: {}", bookIds);
|
||||
}
|
||||
|
||||
private boolean tryPromoteAlternativeFormatToBook(BookEntity book, List<LibraryFile> libraryFiles) {
|
||||
List<BookAdditionalFileEntity> existingAlternativeFormats = findExistingAlternativeFormats(book, libraryFiles);
|
||||
|
||||
if (existingAlternativeFormats.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
BookAdditionalFileEntity promotedFormat = existingAlternativeFormats.getFirst();
|
||||
promoteAlternativeFormatToBook(book, promotedFormat);
|
||||
|
||||
bookAdditionalFileRepository.delete(promotedFormat);
|
||||
|
||||
log.info("Promoted alternative format {} to main book for book ID {}", promotedFormat.getFileName(), book.getId());
|
||||
return true;
|
||||
}
|
||||
|
||||
private List<BookAdditionalFileEntity> findExistingAlternativeFormats(BookEntity book, List<LibraryFile> libraryFiles) {
|
||||
Set<String> currentFileNames = libraryFiles.stream()
|
||||
.map(LibraryFile::getFileName)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (book.getAdditionalFiles() == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
return book.getAdditionalFiles().stream()
|
||||
.filter(additionalFile -> AdditionalFileType.ALTERNATIVE_FORMAT.equals(additionalFile.getAdditionalFileType()))
|
||||
.filter(additionalFile -> currentFileNames.contains(additionalFile.getFileName()))
|
||||
.filter(additionalFile -> BookFileExtension.fromFileName(additionalFile.getFileName()).isPresent())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private void promoteAlternativeFormatToBook(BookEntity book, BookAdditionalFileEntity alternativeFormat) {
|
||||
book.setFileName(alternativeFormat.getFileName());
|
||||
book.setFileSubPath(alternativeFormat.getFileSubPath());
|
||||
BookFileExtension.fromFileName(alternativeFormat.getFileName())
|
||||
.ifPresent(ext -> book.setBookType(ext.getType()));
|
||||
|
||||
book.setFileSizeKb(alternativeFormat.getFileSizeKb());
|
||||
book.setCurrentHash(alternativeFormat.getCurrentHash());
|
||||
book.setInitialHash(alternativeFormat.getInitialHash());
|
||||
|
||||
bookRepository.save(book);
|
||||
}
|
||||
|
||||
private void deleteDirectoryRecursively(Path path) throws IOException {
|
||||
if (Files.exists(path)) {
|
||||
try (Stream<Path> walk = Files.walk(path)) {
|
||||
walk.sorted(Comparator.reverseOrder()).forEach(p -> {
|
||||
try {
|
||||
Files.deleteIfExists(p);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete file or directory: {}", p, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class BookRestorationService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookMapper bookMapper;
|
||||
private final NotificationService notificationService;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void restoreDeletedBooks(List<LibraryFile> libraryFiles) {
|
||||
if (libraryFiles.isEmpty()) return;
|
||||
|
||||
LibraryEntity libraryEntity = libraryFiles.getFirst().getLibraryEntity();
|
||||
Set<Path> currentPaths = libraryFiles.stream()
|
||||
.map(LibraryFile::getFullPath)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
List<BookEntity> toRestore = libraryEntity.getBookEntities().stream()
|
||||
.filter(book -> Boolean.TRUE.equals(book.getDeleted()))
|
||||
.filter(book -> currentPaths.contains(book.getFullFilePath()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (toRestore.isEmpty()) return;
|
||||
|
||||
toRestore.forEach(book -> {
|
||||
book.setDeleted(false);
|
||||
book.setDeletedAt(null);
|
||||
book.setAddedOn(Instant.now());
|
||||
notificationService.sendMessage(Topic.BOOK_ADD, bookMapper.toBookWithDescription(book, false));
|
||||
});
|
||||
bookRepository.saveAll(toRestore);
|
||||
|
||||
List<Long> restoredIds = toRestore.stream()
|
||||
.map(BookEntity::getId)
|
||||
.toList();
|
||||
|
||||
log.info("Restored {} books in library: {}", restoredIds.size(), libraryEntity.getName());
|
||||
}
|
||||
}
|
||||
+36
-11
@@ -1,10 +1,13 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.DuplicateFileInfo;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.DuplicateFileNotification;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
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.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
|
||||
@@ -15,12 +18,9 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
@Slf4j
|
||||
@@ -28,6 +28,7 @@ public class FileAsBookProcessor implements LibraryFileProcessor {
|
||||
|
||||
private final BookEventBroadcaster bookEventBroadcaster;
|
||||
private final BookFileProcessorRegistry processorRegistry;
|
||||
private final NotificationService notificationService;
|
||||
|
||||
@Override
|
||||
public LibraryScanMode getScanMode() {
|
||||
@@ -39,16 +40,40 @@ public class FileAsBookProcessor implements LibraryFileProcessor {
|
||||
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
for (LibraryFile libraryFile : libraryFiles) {
|
||||
log.info("Processing file: {}", libraryFile.getFileName());
|
||||
Book book = processLibraryFile(libraryFile);
|
||||
if (book != null) {
|
||||
bookEventBroadcaster.broadcastBookAddEvent(book);
|
||||
log.info("Processed file: {}", libraryFile.getFileName());
|
||||
|
||||
FileProcessResult result = processLibraryFile(libraryFile);
|
||||
|
||||
if (result != null) {
|
||||
if (result.getDuplicate() != null) {
|
||||
DuplicateFileInfo dupe = result.getDuplicate();
|
||||
|
||||
DuplicateFileNotification notification = DuplicateFileNotification.builder()
|
||||
.libraryId(libraryEntity.getId())
|
||||
.libraryName(libraryEntity.getName())
|
||||
.fileId(dupe.getBookId())
|
||||
.fileName(dupe.getFileName())
|
||||
.fullPath(dupe.getFullPath())
|
||||
.hash(dupe.getHash())
|
||||
.timestamp(Instant.now())
|
||||
.build();
|
||||
|
||||
log.info("Duplicate file detected: {}", notification);
|
||||
|
||||
notificationService.sendMessage(Topic.DUPLICATE_FILE, notification);
|
||||
}
|
||||
|
||||
if (result.getStatus() != FileProcessStatus.DUPLICATE) {
|
||||
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
|
||||
log.info("Processed file: {}", libraryFile.getFileName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.info("Finished processing library '{}'", libraryEntity.getName());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected Book processLibraryFile(LibraryFile libraryFile) {
|
||||
protected FileProcessResult processLibraryFile(LibraryFile libraryFile) {
|
||||
BookFileType type = libraryFile.getBookFileType();
|
||||
if (type == null) {
|
||||
log.warn("Unsupported file type for file: {}", libraryFile.getFileName());
|
||||
|
||||
+7
-19
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
@@ -47,20 +47,17 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
|
||||
@Override
|
||||
public boolean supportsSupplementaryFiles() {
|
||||
// This processor supports supplementary files, as it processes all files in the folder.
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
// Group files by their directory path
|
||||
Map<Path, List<LibraryFile>> filesByDirectory = libraryFiles.stream()
|
||||
.collect(Collectors.groupingBy(libraryFile -> libraryFile.getFullPath().getParent()));
|
||||
|
||||
log.info("Processing {} directories with {} total files for library: {}",
|
||||
filesByDirectory.size(), libraryFiles.size(), libraryEntity.getName());
|
||||
|
||||
// Process each directory
|
||||
var sortedDirectories = filesByDirectory.entrySet()
|
||||
.stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
@@ -91,7 +88,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
return new GetOrCreateBookResult(existingBook, filesInDirectory);
|
||||
}
|
||||
|
||||
// No existing book, check parent directories
|
||||
Optional<BookEntity> parentBook = findBookInParentDirectories(directoryPath, libraryEntity);
|
||||
if (parentBook.isPresent()) {
|
||||
log.debug("Found parent book for directory {}: {}", directoryPath, parentBook.get().getFileName());
|
||||
@@ -113,7 +109,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
}
|
||||
|
||||
private Optional<BookEntity> findExistingBookInDirectory(Path directoryPath, LibraryEntity libraryEntity) {
|
||||
// Find books in all library paths for this library
|
||||
return libraryEntity.getLibraryPaths().stream()
|
||||
.flatMap(libPath -> {
|
||||
String filesSearchPath = Path.of(libPath.getPath())
|
||||
@@ -157,7 +152,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
}
|
||||
|
||||
private Optional<CreateBookResult> createNewBookFromDirectory(Path directoryPath, List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
|
||||
// Find the best candidate for the main book file
|
||||
Optional<LibraryFile> mainBookFile = findBestMainBookFile(filesInDirectory, libraryEntity);
|
||||
|
||||
if (mainBookFile.isEmpty()) {
|
||||
@@ -170,20 +164,17 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
try {
|
||||
log.info("Creating new book from file: {}", bookFile.getFileName());
|
||||
|
||||
// Create the main book
|
||||
BookFileProcessor processor = bookFileProcessorRegistry.getProcessorOrThrow(bookFile.getBookFileType());
|
||||
Book book = processor.processFile(bookFile);
|
||||
FileProcessResult result = processor.processFile(bookFile);
|
||||
|
||||
if (book != null) {
|
||||
bookEventBroadcaster.broadcastBookAddEvent(book);
|
||||
if (result.getBook() != null) {
|
||||
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
|
||||
|
||||
// Find the created book entity
|
||||
BookEntity bookEntity = bookRepository.getReferenceById(book.getId());
|
||||
BookEntity bookEntity = bookRepository.getReferenceById(result.getBook().getId());
|
||||
if (bookEntity.getFullFilePath().equals(bookFile.getFullPath())) {
|
||||
log.info("Successfully created new book: {}", bookEntity.getFileName());
|
||||
} else {
|
||||
log.warn("Found duplicate book with different path: {} vs {}",
|
||||
bookEntity.getFullFilePath(), bookFile.getFullPath());
|
||||
log.warn("Found duplicate book with different path: {} vs {}", bookEntity.getFullFilePath(), bookFile.getFullPath());
|
||||
}
|
||||
|
||||
return Optional.of(new CreateBookResult(bookEntity, bookFile));
|
||||
@@ -206,7 +197,7 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
.min(Comparator.comparingInt(f -> {
|
||||
BookFileType bookFileType = f.getBookFileType();
|
||||
return bookFileType == defaultBookFormat
|
||||
? -1 // Prefer the default format
|
||||
? -1
|
||||
: bookFileType.ordinal();
|
||||
}));
|
||||
}
|
||||
@@ -222,7 +213,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
}
|
||||
|
||||
private void createAdditionalFileIfNotExists(BookEntity bookEntity, LibraryFile file, AdditionalFileType fileType) {
|
||||
// Check if an additional file already exists
|
||||
Optional<BookAdditionalFileEntity> existingFile = bookAdditionalFileRepository
|
||||
.findByLibraryPath_IdAndFileSubPathAndFileName(
|
||||
file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName());
|
||||
@@ -232,7 +222,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create a new additional file
|
||||
String hash = FileFingerprint.generateHash(file.getFullPath());
|
||||
BookAdditionalFileEntity additionalFile = BookAdditionalFileEntity.builder()
|
||||
.book(bookEntity)
|
||||
@@ -251,7 +240,6 @@ public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
|
||||
log.debug("Successfully created additional file: {}", file.getFileName());
|
||||
} catch (Exception e) {
|
||||
// Remove an additional file from the book entity if its creation fails
|
||||
bookEntity.getAdditionalFiles().removeIf(a -> a.equals(additionalFile));
|
||||
|
||||
log.error("Error creating additional file {}: {}", file.getFileName(), e.getMessage(), e);
|
||||
|
||||
+10
-154
@@ -1,21 +1,19 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
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.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.NotificationService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -25,7 +23,6 @@ import java.io.IOException;
|
||||
import java.nio.file.FileVisitOption;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
@@ -39,11 +36,12 @@ public class LibraryProcessingService {
|
||||
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final NotificationService notificationService;
|
||||
private final BookRepository bookRepository;
|
||||
private final BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
private final FileService fileService;
|
||||
private final BookMapper bookMapper;
|
||||
private final LibraryFileProcessorRegistry fileProcessorRegistry;
|
||||
private final BookRestorationService bookRestorationService;
|
||||
private final BookDeletionService bookDeletionService;
|
||||
@PersistenceContext
|
||||
private final EntityManager entityManager;
|
||||
|
||||
@Transactional
|
||||
public void processLibrary(long libraryId) throws IOException {
|
||||
@@ -64,48 +62,19 @@ public class LibraryProcessingService {
|
||||
List<Long> additionalFileIds = detectDeletedAdditionalFiles(libraryFiles, libraryEntity);
|
||||
if (!additionalFileIds.isEmpty()) {
|
||||
log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName());
|
||||
deleteRemovedAdditionalFiles(additionalFileIds);
|
||||
bookDeletionService.deleteRemovedAdditionalFiles(additionalFileIds);
|
||||
}
|
||||
List<Long> bookIds = detectDeletedBookIds(libraryFiles, libraryEntity);
|
||||
if (!bookIds.isEmpty()) {
|
||||
log.info("Detected {} removed books in library: {}", bookIds.size(), libraryEntity.getName());
|
||||
processDeletedLibraryFiles(bookIds, libraryFiles);
|
||||
bookDeletionService.processDeletedLibraryFiles(bookIds, libraryFiles);
|
||||
}
|
||||
restoreDeletedBooks(libraryFiles);
|
||||
bookRestorationService.restoreDeletedBooks(libraryFiles);
|
||||
entityManager.clear();
|
||||
processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity);
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
|
||||
}
|
||||
|
||||
private void restoreDeletedBooks(List<LibraryFile> libraryFiles) {
|
||||
if (libraryFiles.isEmpty()) return;
|
||||
|
||||
LibraryEntity libraryEntity = libraryFiles.get(0).getLibraryEntity();
|
||||
Set<Path> currentPaths = libraryFiles.stream()
|
||||
.map(LibraryFile::getFullPath)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
List<BookEntity> toRestore = libraryEntity.getBookEntities().stream()
|
||||
.filter(book -> Boolean.TRUE.equals(book.getDeleted()))
|
||||
.filter(book -> currentPaths.contains(book.getFullFilePath()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (toRestore.isEmpty()) return;
|
||||
|
||||
toRestore.forEach(book -> {
|
||||
book.setDeleted(false);
|
||||
book.setDeletedAt(null);
|
||||
book.setAddedOn(Instant.now());
|
||||
notificationService.sendMessage(Topic.BOOK_ADD, bookMapper.toBookWithDescription(book, false));
|
||||
});
|
||||
bookRepository.saveAll(toRestore);
|
||||
|
||||
List<Long> restoredIds = toRestore.stream()
|
||||
.map(BookEntity::getId)
|
||||
.toList();
|
||||
|
||||
log.info("Restored {} books in library: {}", restoredIds.size(), libraryEntity.getName());
|
||||
}
|
||||
|
||||
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
@@ -157,119 +126,6 @@ public class LibraryProcessingService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected void deleteRemovedAdditionalFiles(List<Long> additionalFileIds) {
|
||||
if (additionalFileIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<BookAdditionalFileEntity> additionalFiles = bookAdditionalFileRepository.findAllById(additionalFileIds);
|
||||
bookAdditionalFileRepository.deleteAll(additionalFiles);
|
||||
|
||||
log.info("Deleted {} additional files from database", additionalFileIds.size());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected void processDeletedLibraryFiles(List<Long> deletedBookIds, List<LibraryFile> libraryFiles) {
|
||||
if (deletedBookIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookRepository.findAllById(deletedBookIds);
|
||||
List<Long> booksToDelete = new ArrayList<>();
|
||||
|
||||
for (BookEntity book : books) {
|
||||
if (!tryPromoteAlternativeFormatToBook(book, libraryFiles)) {
|
||||
booksToDelete.add(book.getId());
|
||||
}
|
||||
}
|
||||
|
||||
if (!booksToDelete.isEmpty()) {
|
||||
deleteRemovedBooks(booksToDelete);
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean tryPromoteAlternativeFormatToBook(BookEntity book, List<LibraryFile> libraryFiles) {
|
||||
// Find existing alternative formats for this book
|
||||
List<BookAdditionalFileEntity> existingAlternativeFormats = findExistingAlternativeFormats(book, libraryFiles);
|
||||
|
||||
if (existingAlternativeFormats.isEmpty()) {
|
||||
return false; // No alternative formats to promote
|
||||
}
|
||||
|
||||
// Promote the first alternative format to become the main book
|
||||
BookAdditionalFileEntity promotedFormat = existingAlternativeFormats.getFirst();
|
||||
promoteAlternativeFormatToBook(book, promotedFormat);
|
||||
|
||||
// Remove the promoted format from additional files
|
||||
bookAdditionalFileRepository.delete(promotedFormat);
|
||||
|
||||
log.info("Promoted alternative format {} to main book for book ID {}", promotedFormat.getFileName(), book.getId());
|
||||
return true;
|
||||
}
|
||||
|
||||
private List<BookAdditionalFileEntity> findExistingAlternativeFormats(BookEntity book, List<LibraryFile> libraryFiles) {
|
||||
Set<String> currentFileNames = libraryFiles.stream()
|
||||
.map(LibraryFile::getFileName)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (book.getAdditionalFiles() == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
return book.getAdditionalFiles().stream()
|
||||
.filter(additionalFile -> AdditionalFileType.ALTERNATIVE_FORMAT.equals(additionalFile.getAdditionalFileType()))
|
||||
.filter(additionalFile -> currentFileNames.contains(additionalFile.getFileName()))
|
||||
.filter(additionalFile -> BookFileExtension.fromFileName(additionalFile.getFileName()).isPresent())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private void promoteAlternativeFormatToBook(BookEntity book, BookAdditionalFileEntity alternativeFormat) {
|
||||
book.setFileName(alternativeFormat.getFileName());
|
||||
book.setFileSubPath(alternativeFormat.getFileSubPath());
|
||||
BookFileExtension.fromFileName(alternativeFormat.getFileName())
|
||||
.ifPresent(ext -> book.setBookType(ext.getType()));
|
||||
|
||||
book.setFileSizeKb(alternativeFormat.getFileSizeKb());
|
||||
book.setCurrentHash(alternativeFormat.getCurrentHash());
|
||||
book.setInitialHash(alternativeFormat.getInitialHash());
|
||||
|
||||
bookRepository.save(book);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected void deleteRemovedBooks(List<Long> bookIds) {
|
||||
List<BookEntity> books = bookRepository.findAllById(bookIds);
|
||||
for (BookEntity book : books) {
|
||||
try {
|
||||
deleteDirectoryRecursively(Path.of(fileService.getImagesFolder(book.getId())));
|
||||
Path backupDir = Path.of(fileService.getBookMetadataBackupPath(book.getId()));
|
||||
if (Files.exists(backupDir)) {
|
||||
deleteDirectoryRecursively(backupDir);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to clean up files for book ID {}: {}", book.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
bookRepository.deleteAll(books);
|
||||
notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
|
||||
if (bookIds.size() > 1) log.info("Books removed: {}", bookIds);
|
||||
}
|
||||
|
||||
private void deleteDirectoryRecursively(Path path) throws IOException {
|
||||
if (Files.exists(path)) {
|
||||
try (Stream<Path> walk = Files.walk(path)) {
|
||||
walk.sorted(Comparator.reverseOrder()).forEach(p -> {
|
||||
try {
|
||||
Files.deleteIfExists(p);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete file or directory: {}", p, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
List<LibraryFile> allFiles = new ArrayList<>();
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-7
@@ -3,6 +3,7 @@ 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;
|
||||
@@ -14,6 +15,7 @@ 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;
|
||||
@@ -64,10 +66,10 @@ public class FileUploadService {
|
||||
private final AdditionalFileMapper additionalFileMapper;
|
||||
private final MonitoringService monitoringService;
|
||||
|
||||
@Value("${PUID:0}")
|
||||
@Value("${PUID:${USER_ID:0}}")
|
||||
private String userId;
|
||||
|
||||
@Value("${GUID:0}")
|
||||
@Value("${PGID:${GROUP_ID:0}}")
|
||||
private String groupId;
|
||||
|
||||
public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException {
|
||||
@@ -82,7 +84,7 @@ public class FileUploadService {
|
||||
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
|
||||
|
||||
Path tempPath = Files.createTempFile("upload-", Objects.requireNonNull(file.getOriginalFilename()));
|
||||
Book book;
|
||||
FileProcessResult result;
|
||||
|
||||
boolean wePaused = false;
|
||||
if (!monitoringService.isPaused()) {
|
||||
@@ -113,10 +115,12 @@ public class FileUploadService {
|
||||
|
||||
log.info("File uploaded to final location: {}", finalPath);
|
||||
|
||||
book = processFile(finalFile.getName(), libraryEntity, libraryPathEntity, finalFile, fileExt.getType());
|
||||
notificationService.sendMessage(Topic.BOOK_ADD, book);
|
||||
result = processFile(finalFile.getName(), libraryEntity, libraryPathEntity, finalFile, fileExt.getType());
|
||||
if (result != null && result.getStatus() != FileProcessStatus.DUPLICATE) {
|
||||
notificationService.sendMessage(Topic.BOOK_ADD, result.getBook());
|
||||
}
|
||||
|
||||
return book;
|
||||
return result.getBook();
|
||||
|
||||
} catch (IOException e) {
|
||||
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
|
||||
@@ -281,7 +285,7 @@ public class FileUploadService {
|
||||
}
|
||||
}
|
||||
|
||||
private Book processFile(String fileName, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile, BookFileType type) {
|
||||
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()
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.adityachandel.booklore.service.BookDownloadService;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.service.BookService;
|
||||
import com.adityachandel.booklore.service.UserProgressService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -48,6 +49,7 @@ class BookServiceDeleteTests {
|
||||
BookQueryService bookQueryService = Mockito.mock(BookQueryService.class);
|
||||
UserProgressService userProgressService = Mockito.mock(UserProgressService.class);
|
||||
BookDownloadService bookDownloadService = Mockito.mock(BookDownloadService.class);
|
||||
MonitoringProtectionService monitoringProtectionService = Mockito.mock(MonitoringProtectionService.class);
|
||||
|
||||
bookService = new BookService(
|
||||
bookRepository,
|
||||
@@ -63,7 +65,8 @@ class BookServiceDeleteTests {
|
||||
authenticationService,
|
||||
bookQueryService,
|
||||
userProgressService,
|
||||
bookDownloadService
|
||||
bookDownloadService,
|
||||
monitoringProtectionService
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+22
-7
@@ -14,7 +14,8 @@ import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.file.FileMoveService;
|
||||
import com.adityachandel.booklore.service.library.LibraryService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
@@ -55,7 +56,7 @@ class FileMoveServiceMoveFilesTest {
|
||||
private NotificationService notificationService;
|
||||
|
||||
@Mock
|
||||
private MonitoringService monitoringService;
|
||||
private MonitoringProtectionService monitoringProtectionService;
|
||||
|
||||
@Mock
|
||||
private AppSettingService appSettingService;
|
||||
@@ -69,6 +70,16 @@ class FileMoveServiceMoveFilesTest {
|
||||
@TempDir
|
||||
Path tempLibraryRoot;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Configure the mock to actually execute the Runnable for all tests
|
||||
doAnswer(invocation -> {
|
||||
Runnable runnable = invocation.getArgument(0);
|
||||
runnable.run();
|
||||
return null;
|
||||
}).when(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("file move operations"));
|
||||
}
|
||||
|
||||
private BookEntity createBookWithFile(Path libraryRoot, String fileSubPath, String fileName) throws IOException {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.id(42L)
|
||||
@@ -388,6 +399,7 @@ class FileMoveServiceMoveFilesTest {
|
||||
Book dto = Book.builder().id(book.getId()).build();
|
||||
when(bookMapper.toBook(book)).thenReturn(dto);
|
||||
|
||||
|
||||
FileMoveRequest req = new FileMoveRequest();
|
||||
req.setBookIds(Set.of(book.getId()));
|
||||
fileMoveService.moveFiles(req);
|
||||
@@ -398,7 +410,12 @@ class FileMoveServiceMoveFilesTest {
|
||||
|
||||
verify(bookRepository).save(book);
|
||||
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), anyList());
|
||||
verify(libraryService).rescanLibrary(book.getLibraryPath().getLibrary().getId());
|
||||
|
||||
// Verify monitoring protection was applied correctly
|
||||
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("file move operations"));
|
||||
|
||||
// Note: Library rescan now happens asynchronously with 8-second delay
|
||||
// We can't verify it immediately in the test, but the operation is scheduled
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -549,8 +566,7 @@ class FileMoveServiceMoveFilesTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_doesNotPauseMonitoringWhenAlreadyPaused() {
|
||||
when(monitoringService.isPaused()).thenReturn(true);
|
||||
void testMoveFiles_executesWithMonitoringProtection() {
|
||||
when(bookQueryService.findAllWithMetadataByIds(anySet())).thenReturn(List.of());
|
||||
AppSettings settings = new AppSettings();
|
||||
settings.setUploadPattern("X/{title}");
|
||||
@@ -560,8 +576,7 @@ class FileMoveServiceMoveFilesTest {
|
||||
req.setBookIds(Set.of(999L));
|
||||
fileMoveService.moveFiles(req);
|
||||
|
||||
verify(monitoringService, never()).pauseMonitoring();
|
||||
verify(monitoringService, never()).resumeMonitoring();
|
||||
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("file move operations"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.mapper.AdditionalFileMapper;
|
||||
import com.adityachandel.booklore.model.entity.BookAdditionalFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.AdditionalFileType;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdditionalFileServiceTest {
|
||||
|
||||
@Mock
|
||||
private BookAdditionalFileRepository additionalFileRepository;
|
||||
|
||||
@Mock
|
||||
private AdditionalFileMapper additionalFileMapper;
|
||||
|
||||
@Mock
|
||||
private MonitoringProtectionService monitoringProtectionService;
|
||||
|
||||
@InjectMocks
|
||||
private AdditionalFileService additionalFileService;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Configure mock to execute the Runnable for file operations (lenient for tests that don't use it)
|
||||
lenient().doAnswer(invocation -> {
|
||||
Runnable runnable = invocation.getArgument(0);
|
||||
runnable.run();
|
||||
return null;
|
||||
}).when(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAdditionalFile_success() throws IOException {
|
||||
// Arrange
|
||||
Path testFile = tempDir.resolve("test-file.pdf");
|
||||
Files.createFile(testFile);
|
||||
|
||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setPath(tempDir.toString());
|
||||
|
||||
BookEntity book = new BookEntity();
|
||||
book.setLibraryPath(libraryPath);
|
||||
|
||||
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
|
||||
.id(1L)
|
||||
.fileName("test-file.pdf")
|
||||
.fileSubPath("")
|
||||
.additionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT)
|
||||
.book(book)
|
||||
.build();
|
||||
|
||||
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
|
||||
|
||||
// Act
|
||||
additionalFileService.deleteAdditionalFile(1L);
|
||||
|
||||
// Assert
|
||||
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
|
||||
verify(additionalFileRepository).delete(fileEntity);
|
||||
assertThat(Files.exists(testFile)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAdditionalFile_fileNotFound() {
|
||||
// Arrange
|
||||
when(additionalFileRepository.findById(1L)).thenReturn(Optional.empty());
|
||||
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> additionalFileService.deleteAdditionalFile(1L))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("Additional file not found with id: 1");
|
||||
|
||||
verify(monitoringProtectionService, never()).executeWithProtection(any(Runnable.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAdditionalFile_physicalFileNotExists() {
|
||||
// Arrange
|
||||
Path nonExistentFile = tempDir.resolve("non-existent.pdf");
|
||||
|
||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setPath(tempDir.toString());
|
||||
|
||||
BookEntity book = new BookEntity();
|
||||
book.setLibraryPath(libraryPath);
|
||||
|
||||
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
|
||||
.id(1L)
|
||||
.fileName("non-existent.pdf")
|
||||
.fileSubPath("")
|
||||
.additionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT)
|
||||
.book(book)
|
||||
.build();
|
||||
|
||||
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
|
||||
|
||||
// Act
|
||||
additionalFileService.deleteAdditionalFile(1L);
|
||||
|
||||
// Assert
|
||||
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
|
||||
verify(additionalFileRepository).delete(fileEntity);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAdditionalFile_ioExceptionDuringDeletion() throws IOException {
|
||||
// This test verifies that DB record is still deleted even if file deletion fails
|
||||
// Arrange
|
||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setPath("/invalid/path");
|
||||
|
||||
BookEntity book = new BookEntity();
|
||||
book.setLibraryPath(libraryPath);
|
||||
|
||||
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
|
||||
.id(1L)
|
||||
.fileName("test-file.pdf")
|
||||
.fileSubPath("")
|
||||
.additionalFileType(AdditionalFileType.ALTERNATIVE_FORMAT)
|
||||
.book(book)
|
||||
.build();
|
||||
|
||||
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
|
||||
|
||||
// Act
|
||||
additionalFileService.deleteAdditionalFile(1L);
|
||||
|
||||
// Assert - DB record should still be deleted even if file deletion fails
|
||||
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
|
||||
verify(additionalFileRepository).delete(fileEntity);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAdditionalFile_withMonitoringProtection() {
|
||||
// Arrange
|
||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setPath(tempDir.toString());
|
||||
|
||||
BookEntity book = new BookEntity();
|
||||
book.setLibraryPath(libraryPath);
|
||||
|
||||
BookAdditionalFileEntity fileEntity = BookAdditionalFileEntity.builder()
|
||||
.id(1L)
|
||||
.fileName("test-file.pdf")
|
||||
.fileSubPath("subfolder")
|
||||
.additionalFileType(AdditionalFileType.SUPPLEMENTARY)
|
||||
.book(book)
|
||||
.build();
|
||||
|
||||
when(additionalFileRepository.findById(1L)).thenReturn(Optional.of(fileEntity));
|
||||
|
||||
// Act
|
||||
additionalFileService.deleteAdditionalFile(1L);
|
||||
|
||||
// Assert - Verify monitoring protection was used
|
||||
verify(monitoringProtectionService).executeWithProtection(any(Runnable.class), eq("additional file deletion"));
|
||||
|
||||
// Verify the operation name is correct for logging/tracking
|
||||
verify(monitoringProtectionService).executeWithProtection(
|
||||
any(Runnable.class),
|
||||
eq("additional file deletion")
|
||||
);
|
||||
}
|
||||
}
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BookServiceDeleteBooksTest {
|
||||
|
||||
@Mock private BookRepository bookRepository;
|
||||
@Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
@Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
@Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
@Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||
@Mock private ShelfRepository shelfRepository;
|
||||
@Mock private FileService fileService;
|
||||
@Mock private BookMapper bookMapper;
|
||||
@Mock private UserRepository userRepository;
|
||||
@Mock private UserBookProgressRepository userBookProgressRepository;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private BookQueryService bookQueryService;
|
||||
@Mock private UserProgressService userProgressService;
|
||||
@Mock private BookDownloadService bookDownloadService;
|
||||
@Mock private MonitoringProtectionService monitoringProtectionService;
|
||||
|
||||
private BookService bookService;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
bookService = new BookService(
|
||||
bookRepository,
|
||||
pdfViewerPreferencesRepository,
|
||||
epubViewerPreferencesRepository,
|
||||
cbxViewerPreferencesRepository,
|
||||
newPdfViewerPreferencesRepository,
|
||||
shelfRepository,
|
||||
fileService,
|
||||
bookMapper,
|
||||
userRepository,
|
||||
userBookProgressRepository,
|
||||
authenticationService,
|
||||
bookQueryService,
|
||||
userProgressService,
|
||||
bookDownloadService,
|
||||
monitoringProtectionService
|
||||
);
|
||||
|
||||
// Configure mock to execute the Supplier for file operations
|
||||
when(monitoringProtectionService.executeWithProtection(any(Supplier.class), eq("book deletion")))
|
||||
.thenAnswer(invocation -> {
|
||||
Supplier<?> supplier = invocation.getArgument(0);
|
||||
return supplier.get();
|
||||
});
|
||||
}
|
||||
|
||||
private LibraryEntity createTestLibrary() {
|
||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setPath(tempDir.toString());
|
||||
|
||||
LibraryEntity library = new LibraryEntity();
|
||||
library.setId(1L);
|
||||
library.setName("Test Library");
|
||||
library.setLibraryPaths(List.of(libraryPath));
|
||||
|
||||
return library;
|
||||
}
|
||||
|
||||
private LibraryPathEntity createTestLibraryPath() {
|
||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setPath(tempDir.toString());
|
||||
return libraryPath;
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteBooks_successfulDeletion() throws IOException {
|
||||
// Arrange
|
||||
Path testFile1 = tempDir.resolve("book1.epub");
|
||||
Path testFile2 = tempDir.resolve("book2.pdf");
|
||||
Files.createFile(testFile1);
|
||||
Files.createFile(testFile2);
|
||||
|
||||
LibraryEntity library = createTestLibrary();
|
||||
LibraryPathEntity libraryPath = createTestLibraryPath();
|
||||
|
||||
BookEntity book1 = BookEntity.builder()
|
||||
.id(1L)
|
||||
.fileName("book1.epub")
|
||||
.fileSubPath("")
|
||||
.libraryPath(libraryPath)
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
BookEntity book2 = BookEntity.builder()
|
||||
.id(2L)
|
||||
.fileName("book2.pdf")
|
||||
.fileSubPath("")
|
||||
.libraryPath(libraryPath)
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
List<BookEntity> books = List.of(book1, book2);
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L))).thenReturn(books);
|
||||
|
||||
// Act
|
||||
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of(1L, 2L));
|
||||
|
||||
// Assert
|
||||
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
|
||||
BookDeletionResponse deletionResponse = response.getBody();
|
||||
assertThat(deletionResponse).isNotNull();
|
||||
assertThat(deletionResponse.getDeleted()).containsExactlyInAnyOrder(1L, 2L);
|
||||
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty();
|
||||
|
||||
// Verify monitoring protection was used
|
||||
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
|
||||
|
||||
// Verify books were deleted from database
|
||||
verify(bookRepository).deleteAll(books);
|
||||
|
||||
// Verify files were deleted
|
||||
assertThat(Files.exists(testFile1)).isFalse();
|
||||
assertThat(Files.exists(testFile2)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteBooks_fileNotFound() {
|
||||
// Arrange
|
||||
Path nonExistentFile = tempDir.resolve("non-existent.epub");
|
||||
|
||||
LibraryEntity library = createTestLibrary();
|
||||
LibraryPathEntity libraryPath = createTestLibraryPath();
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.id(1L)
|
||||
.fileName("non-existent.epub")
|
||||
.fileSubPath("")
|
||||
.libraryPath(libraryPath)
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
|
||||
|
||||
// Act
|
||||
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of(1L));
|
||||
|
||||
// Assert
|
||||
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
|
||||
BookDeletionResponse deletionResponse = response.getBody();
|
||||
assertThat(deletionResponse).isNotNull();
|
||||
assertThat(deletionResponse.getDeleted()).containsExactly(1L);
|
||||
|
||||
// File doesn't exist, so no deletion failure is recorded
|
||||
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty();
|
||||
|
||||
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
|
||||
verify(bookRepository).deleteAll(List.of(book));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteBooks_partialFailure() throws IOException {
|
||||
// Arrange
|
||||
Path existingFile = tempDir.resolve("existing.epub");
|
||||
Files.createFile(existingFile);
|
||||
|
||||
LibraryEntity library = createTestLibrary();
|
||||
LibraryPathEntity libraryPath = createTestLibraryPath();
|
||||
|
||||
BookEntity existingBook = BookEntity.builder()
|
||||
.id(1L)
|
||||
.fileName("existing.epub")
|
||||
.fileSubPath("")
|
||||
.libraryPath(libraryPath)
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
BookEntity missingBook = BookEntity.builder()
|
||||
.id(2L)
|
||||
.fileName("missing.epub")
|
||||
.fileSubPath("")
|
||||
.libraryPath(libraryPath)
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
List<BookEntity> books = List.of(existingBook, missingBook);
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L, 2L))).thenReturn(books);
|
||||
|
||||
// Act
|
||||
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of(1L, 2L));
|
||||
|
||||
// Assert
|
||||
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
|
||||
BookDeletionResponse deletionResponse = response.getBody();
|
||||
assertThat(deletionResponse).isNotNull();
|
||||
assertThat(deletionResponse.getDeleted()).containsExactlyInAnyOrder(1L, 2L);
|
||||
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty(); // Missing file is not considered a failure
|
||||
|
||||
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
|
||||
verify(bookRepository).deleteAll(books);
|
||||
|
||||
// Existing file should be deleted
|
||||
assertThat(Files.exists(existingFile)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteBooks_emptySet() {
|
||||
// Act
|
||||
ResponseEntity<BookDeletionResponse> response = bookService.deleteBooks(Set.of());
|
||||
|
||||
// Assert
|
||||
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
|
||||
BookDeletionResponse deletionResponse = response.getBody();
|
||||
assertThat(deletionResponse).isNotNull();
|
||||
assertThat(deletionResponse.getDeleted()).isEmpty();
|
||||
assertThat(deletionResponse.getFailedFileDeletions()).isEmpty();
|
||||
|
||||
// Should still use monitoring protection even for empty operations
|
||||
verify(monitoringProtectionService).executeWithProtection(any(Supplier.class), eq("book deletion"));
|
||||
verify(bookRepository).deleteAll(List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteBooks_verifyMonitoringProtectionUsage() {
|
||||
// Arrange
|
||||
LibraryEntity library = createTestLibrary();
|
||||
LibraryPathEntity libraryPath = createTestLibraryPath();
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.id(1L)
|
||||
.fileName("test.epub")
|
||||
.fileSubPath("")
|
||||
.libraryPath(libraryPath)
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
|
||||
|
||||
// Act
|
||||
bookService.deleteBooks(Set.of(1L));
|
||||
|
||||
// Assert - Verify monitoring protection is called with correct parameters
|
||||
verify(monitoringProtectionService).executeWithProtection(
|
||||
any(Supplier.class),
|
||||
eq("book deletion")
|
||||
);
|
||||
}
|
||||
}
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MonitoringProtectionConcurrentTest {
|
||||
|
||||
@Mock
|
||||
private MonitoringService monitoringService;
|
||||
|
||||
private MonitoringProtectionService monitoringProtectionService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
monitoringProtectionService = new MonitoringProtectionService(monitoringService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentOperations_properSynchronization() throws InterruptedException {
|
||||
// Arrange
|
||||
when(monitoringService.isPaused()).thenReturn(false, true, true, true, true);
|
||||
|
||||
AtomicInteger operationCount = new AtomicInteger(0);
|
||||
AtomicInteger pauseCount = new AtomicInteger(0);
|
||||
AtomicInteger resumeCount = new AtomicInteger(0);
|
||||
|
||||
// Track pause/resume calls
|
||||
doAnswer(invocation -> {
|
||||
pauseCount.incrementAndGet();
|
||||
return null;
|
||||
}).when(monitoringService).pauseMonitoring();
|
||||
|
||||
doAnswer(invocation -> {
|
||||
resumeCount.incrementAndGet();
|
||||
return null;
|
||||
}).when(monitoringService).resumeMonitoring();
|
||||
|
||||
int numberOfThreads = 10;
|
||||
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfThreads);
|
||||
|
||||
// Act - Run multiple concurrent operations
|
||||
List<Future<?>> futures = new ArrayList<>();
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
final int operationId = i;
|
||||
Future<?> future = executor.submit(() -> {
|
||||
try {
|
||||
monitoringProtectionService.executeWithProtection(() -> {
|
||||
operationCount.incrementAndGet();
|
||||
// Simulate some work
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}, "concurrent test operation " + operationId);
|
||||
} finally {
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
futures.add(future);
|
||||
}
|
||||
|
||||
// Wait for all operations to complete
|
||||
boolean completed = latch.await(30, TimeUnit.SECONDS);
|
||||
executor.shutdown();
|
||||
|
||||
// Assert
|
||||
assertThat(completed).isTrue();
|
||||
assertThat(operationCount.get()).isEqualTo(numberOfThreads);
|
||||
|
||||
// Verify monitoring was paused at least once (may be fewer due to synchronization)
|
||||
assertThat(pauseCount.get()).isGreaterThan(0);
|
||||
|
||||
// Wait a bit for resume calls (they happen with delay in virtual threads)
|
||||
Thread.sleep(6000);
|
||||
assertThat(resumeCount.get()).isGreaterThan(0);
|
||||
|
||||
// All futures should complete successfully
|
||||
for (Future<?> future : futures) {
|
||||
assertThat(future.isDone()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentOperations_onlyOnePausesMonitoring() throws InterruptedException {
|
||||
// Arrange - First call returns false (not paused), subsequent return true (already paused)
|
||||
when(monitoringService.isPaused()).thenReturn(false).thenReturn(true);
|
||||
|
||||
AtomicInteger pauseCallCount = new AtomicInteger(0);
|
||||
doAnswer(invocation -> {
|
||||
pauseCallCount.incrementAndGet();
|
||||
return null;
|
||||
}).when(monitoringService).pauseMonitoring();
|
||||
|
||||
int numberOfThreads = 5;
|
||||
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
|
||||
CountDownLatch startLatch = new CountDownLatch(1);
|
||||
CountDownLatch finishLatch = new CountDownLatch(numberOfThreads);
|
||||
|
||||
// Act - Start all threads at the same time to maximize contention
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
executor.submit(() -> {
|
||||
try {
|
||||
startLatch.await(); // Wait for signal to start
|
||||
monitoringProtectionService.executeWithProtection(() -> {
|
||||
// Simulate work
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}, "sync test");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
finishLatch.countDown();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
startLatch.countDown(); // Start all threads
|
||||
boolean completed = finishLatch.await(10, TimeUnit.SECONDS);
|
||||
executor.shutdown();
|
||||
|
||||
// Assert
|
||||
assertThat(completed).isTrue();
|
||||
|
||||
// Only one thread should have actually called pauseMonitoring due to synchronization
|
||||
assertThat(pauseCallCount.get()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentOperations_withExceptions() throws InterruptedException {
|
||||
// Arrange
|
||||
when(monitoringService.isPaused()).thenReturn(false, true, true);
|
||||
|
||||
AtomicInteger successCount = new AtomicInteger(0);
|
||||
AtomicInteger exceptionCount = new AtomicInteger(0);
|
||||
AtomicInteger resumeCount = new AtomicInteger(0);
|
||||
|
||||
doAnswer(invocation -> {
|
||||
resumeCount.incrementAndGet();
|
||||
return null;
|
||||
}).when(monitoringService).resumeMonitoring();
|
||||
|
||||
int numberOfThreads = 8;
|
||||
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfThreads);
|
||||
|
||||
// Act - Half the operations throw exceptions
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
final int operationId = i;
|
||||
executor.submit(() -> {
|
||||
try {
|
||||
monitoringProtectionService.executeWithProtection(() -> {
|
||||
if (operationId % 2 == 0) {
|
||||
successCount.incrementAndGet();
|
||||
} else {
|
||||
exceptionCount.incrementAndGet();
|
||||
throw new RuntimeException("Test exception " + operationId);
|
||||
}
|
||||
}, "exception test " + operationId);
|
||||
} catch (RuntimeException e) {
|
||||
// Expected for half the operations
|
||||
} finally {
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
boolean completed = latch.await(10, TimeUnit.SECONDS);
|
||||
executor.shutdown();
|
||||
|
||||
// Assert
|
||||
assertThat(completed).isTrue();
|
||||
assertThat(successCount.get()).isEqualTo(numberOfThreads / 2);
|
||||
assertThat(exceptionCount.get()).isEqualTo(numberOfThreads / 2);
|
||||
|
||||
// Wait for resume calls (delayed)
|
||||
Thread.sleep(6000);
|
||||
|
||||
// Even with exceptions, monitoring should still be resumed
|
||||
assertThat(resumeCount.get()).isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentOperations_supplierReturnValues() throws InterruptedException, ExecutionException, TimeoutException {
|
||||
// Arrange
|
||||
when(monitoringService.isPaused()).thenReturn(false, true, true, true);
|
||||
|
||||
int numberOfThreads = 6;
|
||||
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
|
||||
|
||||
// Act - Use Supplier version to test return values
|
||||
List<Future<String>> futures = new ArrayList<>();
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
final int operationId = i;
|
||||
Future<String> future = executor.submit(() ->
|
||||
monitoringProtectionService.executeWithProtection(() -> {
|
||||
try {
|
||||
Thread.sleep(50); // Simulate work
|
||||
return "Result-" + operationId;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return "Interrupted-" + operationId;
|
||||
}
|
||||
}, "supplier test " + operationId)
|
||||
);
|
||||
futures.add(future);
|
||||
}
|
||||
|
||||
// Assert
|
||||
List<String> results = new ArrayList<>();
|
||||
for (Future<String> future : futures) {
|
||||
String result = future.get(10, TimeUnit.SECONDS);
|
||||
results.add(result);
|
||||
}
|
||||
|
||||
executor.shutdown();
|
||||
|
||||
assertThat(results).hasSize(numberOfThreads);
|
||||
for (int i = 0; i < numberOfThreads; i++) {
|
||||
assertThat(results).contains("Result-" + i);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stressTest_manyQuickOperations() throws InterruptedException {
|
||||
// Arrange
|
||||
when(monitoringService.isPaused()).thenReturn(false).thenReturn(true);
|
||||
|
||||
AtomicInteger completedOperations = new AtomicInteger(0);
|
||||
int numberOfOperations = 100;
|
||||
ExecutorService executor = Executors.newFixedThreadPool(20);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfOperations);
|
||||
|
||||
// Act - Many quick operations to test lock contention
|
||||
for (int i = 0; i < numberOfOperations; i++) {
|
||||
executor.submit(() -> {
|
||||
try {
|
||||
monitoringProtectionService.executeWithProtection(() -> {
|
||||
completedOperations.incrementAndGet();
|
||||
// Very quick operation
|
||||
}, "stress test");
|
||||
} finally {
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
boolean completed = latch.await(30, TimeUnit.SECONDS);
|
||||
executor.shutdown();
|
||||
|
||||
// Assert
|
||||
assertThat(completed).isTrue();
|
||||
assertThat(completedOperations.get()).isEqualTo(numberOfOperations);
|
||||
|
||||
// Should only pause once due to synchronization, even with many operations
|
||||
verify(monitoringService, times(1)).pauseMonitoring();
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Integration test to verify that critical file operations properly use monitoring protection
|
||||
* to prevent race conditions that can cause data loss.
|
||||
*
|
||||
* This addresses the race condition bug where monitoring would detect file operations
|
||||
* as "missing files" and delete them before the operations completed.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MonitoringProtectionIntegrationTest {
|
||||
|
||||
@Mock
|
||||
private MonitoringService monitoringService;
|
||||
|
||||
@Test
|
||||
void testMonitoringProtectionPattern_PauseAndResumeSequence() {
|
||||
// Given - monitoring service that reports not paused initially
|
||||
when(monitoringService.isPaused()).thenReturn(false);
|
||||
|
||||
// When - simulating the monitoring protection pattern used in file operations
|
||||
boolean didPause = pauseMonitoringIfNeeded();
|
||||
try {
|
||||
// Critical file operation would happen here
|
||||
// (simulated - actual file operations tested in integration tests)
|
||||
} finally {
|
||||
resumeMonitoringImmediately(didPause);
|
||||
}
|
||||
|
||||
// Then - verify the correct sequence occurred
|
||||
verify(monitoringService).isPaused(); // Check current state
|
||||
verify(monitoringService).pauseMonitoring(); // Pause before operation
|
||||
verify(monitoringService).resumeMonitoring(); // Resume after operation
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMonitoringProtectionPattern_AlreadyPaused() {
|
||||
// Given - monitoring service that reports already paused
|
||||
when(monitoringService.isPaused()).thenReturn(true);
|
||||
|
||||
// When - simulating the monitoring protection pattern
|
||||
boolean didPause = pauseMonitoringIfNeeded();
|
||||
try {
|
||||
// Critical file operation would happen here
|
||||
} finally {
|
||||
resumeMonitoringImmediately(didPause);
|
||||
}
|
||||
|
||||
// Then - verify no additional pause/resume calls were made
|
||||
verify(monitoringService).isPaused(); // Check current state
|
||||
verify(monitoringService, never()).pauseMonitoring(); // Should not pause again
|
||||
verify(monitoringService, never()).resumeMonitoring(); // Should not resume what we didn't pause
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMonitoringProtectionPattern_ExceptionHandling() {
|
||||
// Given - monitoring service that reports not paused initially
|
||||
when(monitoringService.isPaused()).thenReturn(false);
|
||||
|
||||
// When - simulating the monitoring protection pattern with exception
|
||||
boolean didPause = pauseMonitoringIfNeeded();
|
||||
try {
|
||||
// Simulate a critical file operation that throws an exception
|
||||
throw new RuntimeException("File operation failed");
|
||||
} catch (RuntimeException e) {
|
||||
// Exception handling would occur here in real code
|
||||
} finally {
|
||||
resumeMonitoringImmediately(didPause);
|
||||
}
|
||||
|
||||
// Then - verify monitoring was still resumed despite the exception
|
||||
verify(monitoringService).isPaused();
|
||||
verify(monitoringService).pauseMonitoring();
|
||||
verify(monitoringService).resumeMonitoring(); // Critical: must resume even on failure
|
||||
}
|
||||
|
||||
// Helper methods that mirror the actual implementation pattern
|
||||
|
||||
private boolean pauseMonitoringIfNeeded() {
|
||||
if (!monitoringService.isPaused()) {
|
||||
monitoringService.pauseMonitoring();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void resumeMonitoringImmediately(boolean didPause) {
|
||||
if (didPause) {
|
||||
monitoringService.resumeMonitoring();
|
||||
}
|
||||
}
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringProtectionService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Integration test that simulates the actual race condition scenario:
|
||||
* File operations happening while monitoring service detects "missing" files.
|
||||
*
|
||||
* This test verifies that MonitoringProtectionService prevents the race condition
|
||||
* that was causing data loss in the original bug.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MonitoringProtectionRaceConditionTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Mock
|
||||
private MonitoringService monitoringService;
|
||||
|
||||
private MonitoringProtectionService monitoringProtectionService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
monitoringProtectionService = new MonitoringProtectionService(monitoringService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void raceConditionPrevention_fileMoveDuringMonitoring() throws InterruptedException, IOException, ExecutionException, TimeoutException {
|
||||
// Arrange
|
||||
Path sourceFile = tempDir.resolve("source.txt");
|
||||
Path targetFile = tempDir.resolve("target.txt");
|
||||
Files.write(sourceFile, "test content".getBytes());
|
||||
|
||||
AtomicBoolean fileOperationCompleted = new AtomicBoolean(false);
|
||||
AtomicBoolean monitoringDetectedMissingFile = new AtomicBoolean(false);
|
||||
AtomicBoolean raceConditionOccurred = new AtomicBoolean(false);
|
||||
|
||||
// Configure mock behavior - monitoring is paused during file operations
|
||||
when(monitoringService.isPaused()).thenAnswer(invocation -> {
|
||||
// isPaused() should return true when monitoring is paused (during file operations)
|
||||
// We start unpaused, then get paused during the operation, then unpaused after
|
||||
return !fileOperationCompleted.get(); // true when operation is running = paused
|
||||
});
|
||||
|
||||
// Start aggressive monitoring that looks for the file
|
||||
ExecutorService monitoringExecutor = Executors.newSingleThreadExecutor();
|
||||
Future<?> monitoringTask = monitoringExecutor.submit(() -> {
|
||||
while (!fileOperationCompleted.get()) {
|
||||
if (!monitoringService.isPaused() && !Files.exists(sourceFile)) {
|
||||
monitoringDetectedMissingFile.set(true);
|
||||
if (!fileOperationCompleted.get()) {
|
||||
// This would be where the monitoring service deletes the "missing" file
|
||||
raceConditionOccurred.set(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1); // Very aggressive checking
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Act - Perform file operation with protection
|
||||
monitoringProtectionService.executeWithProtection(() -> {
|
||||
try {
|
||||
// Simulate the file operation that was causing issues
|
||||
Thread.sleep(100); // Simulate some processing time
|
||||
Files.move(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
|
||||
Thread.sleep(100); // Simulate more processing time
|
||||
fileOperationCompleted.set(true);
|
||||
} catch (InterruptedException | IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}, "race condition test");
|
||||
|
||||
// Wait for monitoring task to complete
|
||||
monitoringTask.get(10, TimeUnit.SECONDS);
|
||||
monitoringExecutor.shutdown();
|
||||
|
||||
// Assert
|
||||
assertThat(Files.exists(targetFile)).isTrue();
|
||||
assertThat(Files.exists(sourceFile)).isFalse();
|
||||
assertThat(fileOperationCompleted.get()).isTrue();
|
||||
|
||||
// The critical assertion: monitoring should not have detected a missing file during the operation
|
||||
assertThat(raceConditionOccurred.get())
|
||||
.withFailMessage("Race condition occurred! Monitoring detected missing file during protected operation")
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void raceConditionPrevention_multipleConcurrentFileOperations() throws InterruptedException, IOException, ExecutionException, TimeoutException {
|
||||
// Arrange
|
||||
when(monitoringService.isPaused()).thenReturn(false).thenReturn(true);
|
||||
|
||||
// Multiple file operations that could interfere with each other
|
||||
int numberOfOperations = 10;
|
||||
List<Path> sourceFiles = new ArrayList<>();
|
||||
List<Path> targetFiles = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < numberOfOperations; i++) {
|
||||
Path source = tempDir.resolve("source_" + i + ".txt");
|
||||
Path target = tempDir.resolve("target_" + i + ".txt");
|
||||
Files.write(source, ("content " + i).getBytes());
|
||||
sourceFiles.add(source);
|
||||
targetFiles.add(target);
|
||||
}
|
||||
|
||||
AtomicInteger completedOperations = new AtomicInteger(0);
|
||||
AtomicInteger raceConditionCount = new AtomicInteger(0);
|
||||
|
||||
// Start monitoring that checks for missing files
|
||||
ExecutorService monitoringExecutor = Executors.newSingleThreadExecutor();
|
||||
Future<?> monitoringTask = monitoringExecutor.submit(() -> {
|
||||
while (completedOperations.get() < numberOfOperations) {
|
||||
if (!monitoringService.isPaused()) {
|
||||
// Check for any missing source files
|
||||
for (int i = 0; i < numberOfOperations; i++) {
|
||||
Path source = sourceFiles.get(i);
|
||||
Path target = targetFiles.get(i);
|
||||
|
||||
// If source is gone but target doesn't exist, it's a race condition
|
||||
if (!Files.exists(source) && !Files.exists(target)) {
|
||||
raceConditionCount.incrementAndGet();
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
Thread.sleep(1);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Act - Perform multiple concurrent file operations
|
||||
ExecutorService operationExecutor = Executors.newFixedThreadPool(5);
|
||||
CountDownLatch latch = new CountDownLatch(numberOfOperations);
|
||||
|
||||
for (int i = 0; i < numberOfOperations; i++) {
|
||||
final int operationIndex = i;
|
||||
operationExecutor.submit(() -> {
|
||||
try {
|
||||
monitoringProtectionService.executeWithProtection(() -> {
|
||||
try {
|
||||
Thread.sleep(50); // Simulate processing
|
||||
Files.move(sourceFiles.get(operationIndex),
|
||||
targetFiles.get(operationIndex),
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
completedOperations.incrementAndGet();
|
||||
} catch (InterruptedException | IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}, "concurrent operation " + operationIndex);
|
||||
} finally {
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Wait for all operations to complete
|
||||
boolean allCompleted = latch.await(30, TimeUnit.SECONDS);
|
||||
monitoringTask.get(5, TimeUnit.SECONDS);
|
||||
|
||||
operationExecutor.shutdown();
|
||||
monitoringExecutor.shutdown();
|
||||
|
||||
// Assert
|
||||
assertThat(allCompleted).isTrue();
|
||||
assertThat(completedOperations.get()).isEqualTo(numberOfOperations);
|
||||
|
||||
// All target files should exist
|
||||
for (Path target : targetFiles) {
|
||||
assertThat(Files.exists(target)).isTrue();
|
||||
}
|
||||
|
||||
// No source files should exist
|
||||
for (Path source : sourceFiles) {
|
||||
assertThat(Files.exists(source)).isFalse();
|
||||
}
|
||||
|
||||
// Critical assertion: no race conditions should have occurred
|
||||
assertThat(raceConditionCount.get())
|
||||
.withFailMessage("Race conditions detected during concurrent operations")
|
||||
.isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void monitoringResumesAfterDelay() throws InterruptedException {
|
||||
// Arrange
|
||||
when(monitoringService.isPaused()).thenReturn(false, true);
|
||||
|
||||
// Act - Perform operation with protection
|
||||
monitoringProtectionService.executeWithProtection(() -> {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}, "delay test");
|
||||
|
||||
// Wait for monitoring to resume (should happen after 5 seconds)
|
||||
Thread.sleep(6000);
|
||||
|
||||
// Assert - Verify monitoring service methods were called
|
||||
verify(monitoringService).pauseMonitoring();
|
||||
verify(monitoringService).resumeMonitoring();
|
||||
}
|
||||
}
|
||||
+511
@@ -0,0 +1,511 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.DuplicateFileInfo;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
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.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.FileProcessStatus;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class AbstractFileProcessorTest {
|
||||
|
||||
@Mock
|
||||
BookRepository bookRepository;
|
||||
@Mock
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
@Mock
|
||||
BookCreatorService bookCreatorService;
|
||||
@Mock
|
||||
BookMapper bookMapper;
|
||||
@Mock
|
||||
MetadataMatchService metadataMatchService;
|
||||
@Mock
|
||||
FileService fileService;
|
||||
@Mock
|
||||
EntityManager entityManager;
|
||||
|
||||
TestFileProcessor processor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
processor = new TestFileProcessor(
|
||||
bookRepository,
|
||||
bookAdditionalFileRepository,
|
||||
bookCreatorService,
|
||||
bookMapper,
|
||||
fileService,
|
||||
metadataMatchService
|
||||
);
|
||||
|
||||
// Inject EntityManager via reflection
|
||||
try {
|
||||
var field = AbstractFileProcessor.class.getDeclaredField("entityManager");
|
||||
field.setAccessible(true);
|
||||
field.set(processor, entityManager);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldReturnDuplicate_whenDuplicateFoundByFileService() {
|
||||
// Given
|
||||
LibraryFile libraryFile = createMockLibraryFile();
|
||||
Book duplicateBook = createMockBook(1L, "file.pdf");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(
|
||||
eq(libraryFile), eq("hash1"), eq(bookRepository), eq(bookAdditionalFileRepository), eq(bookMapper)))
|
||||
.thenReturn(Optional.of(duplicateBook));
|
||||
|
||||
BookEntity bookEntity = createMockBookEntity(1L, "file.pdf", "hash1", "sub", libraryFile.getLibraryPathEntity());
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result.getStatus()).isEqualTo(FileProcessStatus.DUPLICATE);
|
||||
assertThat(result.getDuplicate()).isNotNull();
|
||||
assertThat(result.getDuplicate().getBookId()).isEqualTo(1L);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldReturnDuplicate_whenBookFoundByFileNameAndLibraryId() {
|
||||
// Given
|
||||
LibraryFile libraryFile = createMockLibraryFile();
|
||||
BookEntity existingEntity = createMockBookEntity(2L, "file.pdf", "hash2", "sub", libraryFile.getLibraryPathEntity());
|
||||
Book existingBook = createMockBook(2L, "file.pdf");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash2");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.empty());
|
||||
when(bookRepository.findBookByFileNameAndLibraryId("file.pdf", 1L))
|
||||
.thenReturn(Optional.of(existingEntity));
|
||||
when(bookMapper.toBook(existingEntity)).thenReturn(existingBook);
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result.getStatus()).isEqualTo(FileProcessStatus.DUPLICATE);
|
||||
assertThat(result.getBook()).isEqualTo(existingBook);
|
||||
assertThat(result.getDuplicate()).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldReturnNew_whenNoDuplicateFound() {
|
||||
// Given
|
||||
LibraryFile libraryFile = createMockLibraryFile();
|
||||
BookEntity newEntity = createMockBookEntity(3L, "file.pdf", "hash3", "sub", libraryFile.getLibraryPathEntity());
|
||||
Book newBook = createMockBook(3L, "file.pdf");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash3");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.empty());
|
||||
when(bookRepository.findBookByFileNameAndLibraryId("file.pdf", 1L))
|
||||
.thenReturn(Optional.empty());
|
||||
when(metadataMatchService.calculateMatchScore(any())).thenReturn(85F);
|
||||
when(bookMapper.toBook(newEntity)).thenReturn(newBook);
|
||||
|
||||
processor.setProcessNewFileResult(newEntity);
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result.getStatus()).isEqualTo(FileProcessStatus.NEW);
|
||||
assertThat(result.getBook()).isEqualTo(newBook);
|
||||
assertThat(result.getDuplicate()).isNull();
|
||||
verify(bookCreatorService).saveConnections(newEntity);
|
||||
verify(metadataMatchService).calculateMatchScore(newEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldReturnUpdated_whenDuplicateFoundWithDifferentMetadata() {
|
||||
// Given
|
||||
LibraryFile libraryFile = createMockLibraryFile();
|
||||
libraryFile.setFileSubPath("new-sub");
|
||||
|
||||
Book duplicateBook = createMockBook(1L, "file.pdf");
|
||||
BookEntity existingEntity = createMockBookEntity(1L, "file.pdf", "hash1", "old-sub", libraryFile.getLibraryPathEntity());
|
||||
Book updatedBook = createMockBook(1L, "file.pdf");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(duplicateBook));
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
|
||||
when(bookMapper.toBook(existingEntity)).thenReturn(updatedBook);
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result.getStatus()).isEqualTo(FileProcessStatus.UPDATED);
|
||||
assertThat(result.getBook()).isEqualTo(updatedBook);
|
||||
assertThat(existingEntity.getFileSubPath()).isEqualTo("new-sub");
|
||||
verify(entityManager).flush();
|
||||
verify(entityManager).detach(existingEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldReturnUpdated_whenDuplicateFoundWithDifferentFileName() {
|
||||
// Given
|
||||
LibraryFile libraryFile = createMockLibraryFile();
|
||||
libraryFile.setFileName("new-file.pdf");
|
||||
|
||||
Book duplicateBook = createMockBook(1L, "old-file.pdf");
|
||||
BookEntity existingEntity = createMockBookEntity(1L, "old-file.pdf", "hash1", "sub", libraryFile.getLibraryPathEntity());
|
||||
Book updatedBook = createMockBook(1L, "new-file.pdf");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(duplicateBook));
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
|
||||
when(bookMapper.toBook(existingEntity)).thenReturn(updatedBook);
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result.getStatus()).isEqualTo(FileProcessStatus.UPDATED);
|
||||
assertThat(result.getBook()).isEqualTo(updatedBook);
|
||||
assertThat(existingEntity.getFileName()).isEqualTo("new-file.pdf");
|
||||
verify(entityManager).flush();
|
||||
verify(entityManager).detach(existingEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldReturnUpdated_whenDuplicateFoundWithDifferentLibraryPath() {
|
||||
// Given
|
||||
LibraryEntity library = LibraryEntity.builder().id(2L).build();
|
||||
LibraryPathEntity newLibraryPath = LibraryPathEntity.builder()
|
||||
.id(2L)
|
||||
.library(library)
|
||||
.path("/new-path")
|
||||
.build();
|
||||
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.fileName("file.pdf")
|
||||
.fileSubPath("sub")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.libraryEntity(library)
|
||||
.libraryPathEntity(newLibraryPath)
|
||||
.build();
|
||||
|
||||
Book duplicateBook = createMockBook(1L, "file.pdf");
|
||||
BookEntity existingEntity = createMockBookEntity(1L, "file.pdf", "hash1", "sub",
|
||||
LibraryPathEntity.builder().id(1L).library(LibraryEntity.builder().id(1L).build()).path("/old-path").build());
|
||||
Book updatedBook = createMockBook(1L, "file.pdf");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(duplicateBook));
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
|
||||
when(bookMapper.toBook(existingEntity)).thenReturn(updatedBook);
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result.getStatus()).isEqualTo(FileProcessStatus.UPDATED);
|
||||
assertThat(result.getBook()).isEqualTo(updatedBook);
|
||||
assertThat(existingEntity.getLibraryPath()).isEqualTo(newLibraryPath);
|
||||
verify(entityManager).flush();
|
||||
verify(entityManager).detach(existingEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldReturnDuplicate_whenDuplicateFoundWithSameMetadata() {
|
||||
// Given
|
||||
LibraryFile libraryFile = createMockLibraryFile();
|
||||
Book duplicateBook = createMockBook(1L, "file.pdf");
|
||||
BookEntity existingEntity = createMockBookEntity(1L, "file.pdf", "hash1", "sub", libraryFile.getLibraryPathEntity());
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(duplicateBook));
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result.getStatus()).isEqualTo(FileProcessStatus.DUPLICATE);
|
||||
assertThat(result.getBook()).isEqualTo(duplicateBook);
|
||||
assertThat(result.getDuplicate()).isNotNull();
|
||||
assertThat(result.getDuplicate().getBookId()).isEqualTo(1L);
|
||||
verify(entityManager, never()).flush();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldReturnDuplicateFromFallback_whenDuplicateBookNotFoundInRepository() {
|
||||
// Given
|
||||
LibraryFile libraryFile = createMockLibraryFile();
|
||||
Book duplicateBook = createMockBook(1L, "file.pdf");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(duplicateBook));
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.empty());
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result.getStatus()).isEqualTo(FileProcessStatus.DUPLICATE);
|
||||
assertThat(result.getBook()).isEqualTo(duplicateBook);
|
||||
assertThat(result.getDuplicate()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldUpdateHashEvenWhenOtherMetadataUnchanged() {
|
||||
// Given
|
||||
LibraryFile libraryFile = createMockLibraryFile();
|
||||
Book duplicateBook = createMockBook(1L, "file.pdf");
|
||||
BookEntity existingEntity = createMockBookEntity(1L, "file.pdf", "old-hash", "sub", libraryFile.getLibraryPathEntity());
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("new-hash");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(duplicateBook));
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
|
||||
when(bookMapper.toBook(existingEntity)).thenReturn(duplicateBook);
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(existingEntity.getCurrentHash()).isEqualTo("new-hash");
|
||||
verify(entityManager).detach(existingEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldHandleNullFileSubPath() {
|
||||
// Given
|
||||
LibraryEntity library = LibraryEntity.builder().id(1L).build();
|
||||
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
||||
.id(1L)
|
||||
.library(library)
|
||||
.path("/tmp")
|
||||
.build();
|
||||
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.fileName("file.pdf")
|
||||
.fileSubPath("") // Use empty string instead of null to avoid NPE in Paths.get
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.libraryEntity(library)
|
||||
.libraryPathEntity(libraryPath)
|
||||
.build();
|
||||
|
||||
BookEntity newEntity = createMockBookEntity(3L, "file.pdf", "hash3", "", libraryFile.getLibraryPathEntity());
|
||||
Book newBook = createMockBook(3L, "file.pdf");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash3");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.empty());
|
||||
when(bookRepository.findBookByFileNameAndLibraryId("file.pdf", 1L))
|
||||
.thenReturn(Optional.empty());
|
||||
when(metadataMatchService.calculateMatchScore(any())).thenReturn(90F);
|
||||
when(bookMapper.toBook(newEntity)).thenReturn(newBook);
|
||||
|
||||
processor.setProcessNewFileResult(newEntity);
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result.getStatus()).isEqualTo(FileProcessStatus.NEW);
|
||||
assertThat(result.getBook()).isEqualTo(newBook);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void processFile_shouldHandleMultipleMetadataChangesSimultaneously() {
|
||||
// Given
|
||||
LibraryEntity newLibrary = LibraryEntity.builder().id(2L).build();
|
||||
LibraryPathEntity newLibraryPath = LibraryPathEntity.builder()
|
||||
.id(2L)
|
||||
.library(newLibrary)
|
||||
.path("/new-path")
|
||||
.build();
|
||||
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.fileName("new-file.pdf")
|
||||
.fileSubPath("new-sub")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.libraryEntity(newLibrary)
|
||||
.libraryPathEntity(newLibraryPath)
|
||||
.build();
|
||||
|
||||
Book duplicateBook = createMockBook(1L, "old-file.pdf");
|
||||
BookEntity existingEntity = createMockBookEntity(1L, "old-file.pdf", "hash1", "old-sub",
|
||||
LibraryPathEntity.builder().id(1L).library(LibraryEntity.builder().id(1L).build()).build());
|
||||
Book updatedBook = createMockBook(1L, "new-file.pdf");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(duplicateBook));
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(existingEntity));
|
||||
when(bookMapper.toBook(existingEntity)).thenReturn(updatedBook);
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result.getStatus()).isEqualTo(FileProcessStatus.UPDATED);
|
||||
assertThat(existingEntity.getFileName()).isEqualTo("new-file.pdf");
|
||||
assertThat(existingEntity.getFileSubPath()).isEqualTo("new-sub");
|
||||
assertThat(existingEntity.getLibraryPath()).isEqualTo(newLibraryPath);
|
||||
verify(entityManager).flush();
|
||||
verify(entityManager).detach(existingEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDuplicateInfo_shouldCreateCorrectDuplicateInfo() {
|
||||
// Given
|
||||
LibraryFile libraryFile = createMockLibraryFile();
|
||||
Book book = createMockBook(1L, "file.pdf");
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("hash1");
|
||||
|
||||
when(fileService.checkForDuplicateAndUpdateMetadataIfNeeded(any(), any(), any(), any(), any()))
|
||||
.thenReturn(Optional.of(book));
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(
|
||||
createMockBookEntity(1L, "file.pdf", "hash1", "sub", libraryFile.getLibraryPathEntity())));
|
||||
|
||||
// When
|
||||
FileProcessResult result = processor.processFile(libraryFile);
|
||||
|
||||
// Then
|
||||
DuplicateFileInfo duplicateInfo = result.getDuplicate();
|
||||
assertThat(duplicateInfo).isNotNull();
|
||||
assertThat(duplicateInfo.getBookId()).isEqualTo(1L);
|
||||
assertThat(duplicateInfo.getFileName()).isEqualTo("file.pdf");
|
||||
assertThat(duplicateInfo.getFullPath()).contains("/tmp", "sub", "file.pdf");
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
private LibraryFile createMockLibraryFile() {
|
||||
LibraryEntity library = LibraryEntity.builder().id(1L).build();
|
||||
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
||||
.id(1L)
|
||||
.library(library)
|
||||
.path("/tmp")
|
||||
.build();
|
||||
|
||||
return LibraryFile.builder()
|
||||
.fileName("file.pdf")
|
||||
.fileSubPath("sub")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.libraryEntity(library)
|
||||
.libraryPathEntity(libraryPath)
|
||||
.build();
|
||||
}
|
||||
|
||||
private Book createMockBook(Long id, String fileName) {
|
||||
return Book.builder()
|
||||
.id(id)
|
||||
.fileName(fileName)
|
||||
.fileSubPath("sub")
|
||||
.build();
|
||||
}
|
||||
|
||||
private BookEntity createMockBookEntity(Long id, String fileName, String hash, String subPath, LibraryPathEntity libraryPath) {
|
||||
return BookEntity.builder()
|
||||
.id(id)
|
||||
.fileName(fileName)
|
||||
.currentHash(hash)
|
||||
.fileSubPath(subPath)
|
||||
.libraryPath(libraryPath)
|
||||
.build();
|
||||
}
|
||||
|
||||
// Test implementation of AbstractFileProcessor
|
||||
static class TestFileProcessor extends AbstractFileProcessor {
|
||||
private BookEntity processNewFileResult;
|
||||
|
||||
public TestFileProcessor(BookRepository bookRepository,
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
BookCreatorService bookCreatorService,
|
||||
BookMapper bookMapper,
|
||||
FileService fileService,
|
||||
MetadataMatchService metadataMatchService) {
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BookEntity processNewFile(LibraryFile libraryFile) {
|
||||
return processNewFileResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookFileType> getSupportedTypes() {
|
||||
return List.of(BookFileType.PDF);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean generateCover(BookEntity bookEntity) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void setProcessNewFileResult(BookEntity entity) {
|
||||
this.processNewFileResult = entity;
|
||||
}
|
||||
}
|
||||
}
|
||||
+70
-58
@@ -1,6 +1,8 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.enums.FileProcessStatus;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
@@ -58,7 +60,7 @@ class FileAsBookProcessorTest {
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
|
||||
LibraryFile file1 = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -66,7 +68,7 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
|
||||
LibraryFile file2 = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -74,30 +76,32 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
|
||||
libraryFiles.add(file1);
|
||||
libraryFiles.add(file2);
|
||||
|
||||
|
||||
Book book1 = Book.builder()
|
||||
.fileName("book1.epub")
|
||||
.title("Book 1")
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
|
||||
Book book2 = Book.builder()
|
||||
.fileName("book2.pdf")
|
||||
.title("Book 2")
|
||||
.bookType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(file1)).thenReturn(book1);
|
||||
when(bookFileProcessor.processFile(file2)).thenReturn(book2);
|
||||
|
||||
when(bookFileProcessor.processFile(file1))
|
||||
.thenReturn(new FileProcessResult(book1, FileProcessStatus.NEW, null));
|
||||
when(bookFileProcessor.processFile(file2))
|
||||
.thenReturn(new FileProcessResult(book2, FileProcessStatus.NEW, null));
|
||||
|
||||
// When
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, times(2)).broadcastBookAddEvent(bookCaptor.capture());
|
||||
|
||||
@@ -113,7 +117,7 @@ class FileAsBookProcessorTest {
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
|
||||
LibraryFile validFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -121,7 +125,7 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
|
||||
LibraryFile invalidFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -129,22 +133,23 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("docs")
|
||||
.bookFileType(null)
|
||||
.build();
|
||||
|
||||
|
||||
libraryFiles.add(validFile);
|
||||
libraryFiles.add(invalidFile);
|
||||
|
||||
|
||||
Book book = Book.builder()
|
||||
.fileName("book.epub")
|
||||
.title("Valid Book")
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(validFile)).thenReturn(book);
|
||||
|
||||
when(bookFileProcessor.processFile(validFile))
|
||||
.thenReturn(new FileProcessResult(book, FileProcessStatus.NEW, null));
|
||||
|
||||
// When
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, times(1)).broadcastBookAddEvent(book);
|
||||
verify(processorRegistry, times(1)).getProcessorOrThrow(any());
|
||||
@@ -155,10 +160,10 @@ class FileAsBookProcessorTest {
|
||||
// Given
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
|
||||
// When
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
||||
verify(processorRegistry, never()).getProcessorOrThrow(any());
|
||||
@@ -170,7 +175,7 @@ class FileAsBookProcessorTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
|
||||
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -178,10 +183,10 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("docs")
|
||||
.bookFileType(null)
|
||||
.build();
|
||||
|
||||
|
||||
// When
|
||||
Book result = fileAsBookProcessor.processLibraryFile(libraryFile);
|
||||
|
||||
FileProcessResult result = fileAsBookProcessor.processLibraryFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result).isNull();
|
||||
verify(processorRegistry, never()).getProcessorOrThrow(any());
|
||||
@@ -193,7 +198,7 @@ class FileAsBookProcessorTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
|
||||
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -201,21 +206,24 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
|
||||
Book expectedBook = Book.builder()
|
||||
.fileName("book.epub")
|
||||
.title("Test Book")
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(libraryFile)).thenReturn(expectedBook);
|
||||
|
||||
when(bookFileProcessor.processFile(libraryFile))
|
||||
.thenReturn(new FileProcessResult(expectedBook, FileProcessStatus.NEW, null));
|
||||
|
||||
// When
|
||||
Book result = fileAsBookProcessor.processLibraryFile(libraryFile);
|
||||
|
||||
FileProcessResult result = fileAsBookProcessor.processLibraryFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result).isEqualTo(expectedBook);
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.getBook()).isEqualTo(expectedBook);
|
||||
|
||||
verify(processorRegistry).getProcessorOrThrow(BookFileType.EPUB);
|
||||
verify(bookFileProcessor).processFile(libraryFile);
|
||||
}
|
||||
@@ -226,7 +234,7 @@ class FileAsBookProcessorTest {
|
||||
LibraryEntity libraryEntity = new LibraryEntity();
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
|
||||
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -234,13 +242,13 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(libraryFile)).thenReturn(null);
|
||||
|
||||
|
||||
// When
|
||||
Book result = fileAsBookProcessor.processLibraryFile(libraryFile);
|
||||
|
||||
FileProcessResult result = fileAsBookProcessor.processLibraryFile(libraryFile);
|
||||
|
||||
// Then
|
||||
assertThat(result).isNull();
|
||||
}
|
||||
@@ -252,7 +260,7 @@ class FileAsBookProcessorTest {
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
|
||||
LibraryFile file = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -260,15 +268,15 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
|
||||
libraryFiles.add(file);
|
||||
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
||||
when(bookFileProcessor.processFile(file)).thenReturn(null);
|
||||
|
||||
|
||||
// When
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, never()).broadcastBookAddEvent(any());
|
||||
}
|
||||
@@ -280,7 +288,7 @@ class FileAsBookProcessorTest {
|
||||
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
|
||||
libraryPathEntity.setPath("/library/path");
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
|
||||
LibraryFile epubFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -288,7 +296,7 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
|
||||
LibraryFile pdfFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -296,7 +304,7 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("books")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
|
||||
LibraryFile cbzFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -304,7 +312,7 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("comics")
|
||||
.bookFileType(BookFileType.CBX)
|
||||
.build();
|
||||
|
||||
|
||||
LibraryFile cbrFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -312,44 +320,48 @@ class FileAsBookProcessorTest {
|
||||
.fileSubPath("comics")
|
||||
.bookFileType(BookFileType.CBX)
|
||||
.build();
|
||||
|
||||
|
||||
libraryFiles.add(epubFile);
|
||||
libraryFiles.add(pdfFile);
|
||||
libraryFiles.add(cbzFile);
|
||||
libraryFiles.add(cbrFile);
|
||||
|
||||
|
||||
Book epubBook = Book.builder()
|
||||
.fileName("book.epub")
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
|
||||
Book pdfBook = Book.builder()
|
||||
.fileName("book.pdf")
|
||||
.bookType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
|
||||
Book cbzBook = Book.builder()
|
||||
.fileName("comic.cbz")
|
||||
.bookType(BookFileType.CBX)
|
||||
.build();
|
||||
|
||||
|
||||
Book cbrBook = Book.builder()
|
||||
.fileName("comic.cbr")
|
||||
.bookType(BookFileType.CBX)
|
||||
.build();
|
||||
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.CBX)).thenReturn(bookFileProcessor);
|
||||
|
||||
when(bookFileProcessor.processFile(epubFile)).thenReturn(epubBook);
|
||||
when(bookFileProcessor.processFile(pdfFile)).thenReturn(pdfBook);
|
||||
when(bookFileProcessor.processFile(cbzFile)).thenReturn(cbzBook);
|
||||
when(bookFileProcessor.processFile(cbrFile)).thenReturn(cbrBook);
|
||||
|
||||
when(bookFileProcessor.processFile(epubFile))
|
||||
.thenReturn(new FileProcessResult(epubBook, FileProcessStatus.NEW, null));
|
||||
when(bookFileProcessor.processFile(pdfFile))
|
||||
.thenReturn(new FileProcessResult(pdfBook, FileProcessStatus.NEW, null));
|
||||
when(bookFileProcessor.processFile(cbzFile))
|
||||
.thenReturn(new FileProcessResult(cbzBook, FileProcessStatus.NEW, null));
|
||||
when(bookFileProcessor.processFile(cbrFile))
|
||||
.thenReturn(new FileProcessResult(cbrBook, FileProcessStatus.NEW, null));
|
||||
|
||||
// When
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
|
||||
|
||||
// Then
|
||||
verify(bookEventBroadcaster, times(4)).broadcastBookAddEvent(any(Book.class));
|
||||
}
|
||||
|
||||
+5
-3
@@ -1,10 +1,12 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.AdditionalFileType;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.FileProcessStatus;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.event.AdminEventBroadcaster;
|
||||
@@ -118,7 +120,7 @@ class FolderAsBookFileProcessorTest {
|
||||
when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.PDF))
|
||||
.thenReturn(mockBookFileProcessor);
|
||||
when(mockBookFileProcessor.processFile(any(LibraryFile.class)))
|
||||
.thenReturn(createdBook);
|
||||
.thenReturn(new FileProcessResult(createdBook, FileProcessStatus.NEW, null));
|
||||
when(bookRepository.getReferenceById(createdBook.getId()))
|
||||
.thenReturn(bookEntity);
|
||||
when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString()))
|
||||
@@ -230,7 +232,7 @@ class FolderAsBookFileProcessorTest {
|
||||
when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.EPUB))
|
||||
.thenReturn(mockBookFileProcessor);
|
||||
when(mockBookFileProcessor.processFile(argThat(file -> file.getFileName().equals("book.epub"))))
|
||||
.thenReturn(createdBook);
|
||||
.thenReturn(new FileProcessResult(createdBook, FileProcessStatus.NEW, null));
|
||||
when(bookRepository.getReferenceById(createdBook.getId()))
|
||||
.thenReturn(bookEntity);
|
||||
when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString()))
|
||||
@@ -275,7 +277,7 @@ class FolderAsBookFileProcessorTest {
|
||||
when(bookFileProcessorRegistry.getProcessorOrThrow(BookFileType.PDF))
|
||||
.thenReturn(mockBookFileProcessor);
|
||||
when(mockBookFileProcessor.processFile(argThat(file -> file.getFileName().equals("book.pdf"))))
|
||||
.thenReturn(createdBook);
|
||||
.thenReturn(new FileProcessResult(createdBook, FileProcessStatus.NEW, null));
|
||||
when(bookRepository.getReferenceById(createdBook.getId()))
|
||||
.thenReturn(bookEntity);
|
||||
when(bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(anyLong(), anyString(), anyString()))
|
||||
|
||||
+34
-29
@@ -4,11 +4,13 @@ import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.AdditionalFileMapperImpl;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
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;
|
||||
@@ -110,11 +112,11 @@ class FileUploadServiceTest {
|
||||
Files.write(tempDir.resolve("dup.epub"), new byte[]{1, 2, 3});
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFileBookDrop(file))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_ALREADY_EXISTS.getStatus());
|
||||
assertThat(ex.getMessage()).isEqualTo(ApiError.FILE_ALREADY_EXISTS.getMessage());
|
||||
});
|
||||
.isThrownBy(() -> service.uploadFileBookDrop(file))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_ALREADY_EXISTS.getStatus());
|
||||
assertThat(ex.getMessage()).isEqualTo(ApiError.FILE_ALREADY_EXISTS.getMessage());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -122,11 +124,11 @@ class FileUploadServiceTest {
|
||||
MockMultipartFile file = new MockMultipartFile("file", "bad.txt", "text/plain", "x".getBytes());
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFileBookDrop(file))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.INVALID_FILE_FORMAT.getStatus());
|
||||
assertThat(ex.getMessage()).contains("Invalid file format, only pdf and epub are supported");
|
||||
});
|
||||
.isThrownBy(() -> service.uploadFileBookDrop(file))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.INVALID_FILE_FORMAT.getStatus());
|
||||
assertThat(ex.getMessage()).contains("Invalid file format, only pdf and epub are supported");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -138,11 +140,11 @@ class FileUploadServiceTest {
|
||||
when(appSettingService.getAppSettings()).thenReturn(small);
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFileBookDrop(file))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_TOO_LARGE.getStatus());
|
||||
assertThat(ex.getMessage()).contains("1");
|
||||
});
|
||||
.isThrownBy(() -> service.uploadFileBookDrop(file))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_TOO_LARGE.getStatus());
|
||||
assertThat(ex.getMessage()).contains("1");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -151,8 +153,8 @@ class FileUploadServiceTest {
|
||||
when(libraryRepository.findById(42L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFile(file, 42L, 1L))
|
||||
.satisfies(ex -> assertThat(ex.getStatus()).isEqualTo(ApiError.LIBRARY_NOT_FOUND.getStatus()));
|
||||
.isThrownBy(() -> service.uploadFile(file, 42L, 1L))
|
||||
.satisfies(ex -> assertThat(ex.getStatus()).isEqualTo(ApiError.LIBRARY_NOT_FOUND.getStatus()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -164,8 +166,8 @@ class FileUploadServiceTest {
|
||||
when(libraryRepository.findById(42L)).thenReturn(Optional.of(lib));
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFile(file, 42L, 99L))
|
||||
.satisfies(ex -> assertThat(ex.getStatus()).isEqualTo(ApiError.INVALID_LIBRARY_PATH.getStatus()));
|
||||
.isThrownBy(() -> service.uploadFile(file, 42L, 99L))
|
||||
.satisfies(ex -> assertThat(ex.getStatus()).isEqualTo(ApiError.INVALID_LIBRARY_PATH.getStatus()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -185,11 +187,11 @@ class FileUploadServiceTest {
|
||||
when(libraryRepository.findById(1L)).thenReturn(Optional.of(lib));
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFile(file, 1L, 1L))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_READ_ERROR.getStatus());
|
||||
assertThat(ex.getMessage()).contains("Error reading files from path");
|
||||
});
|
||||
.isThrownBy(() -> service.uploadFile(file, 1L, 1L))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_READ_ERROR.getStatus());
|
||||
assertThat(ex.getMessage()).contains("Error reading files from path");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -206,17 +208,20 @@ class FileUploadServiceTest {
|
||||
when(libraryRepository.findById(7L)).thenReturn(Optional.of(lib));
|
||||
|
||||
BookFileProcessor proc = mock(BookFileProcessor.class);
|
||||
Book stubBook = Book.builder().build();
|
||||
stubBook.setTitle("X");
|
||||
FileProcessResult fileProcessResult = FileProcessResult.builder()
|
||||
.book(Book.builder().build())
|
||||
.status(FileProcessStatus.NEW)
|
||||
.build();
|
||||
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.CBX)).thenReturn(proc);
|
||||
when(proc.processFile(any())).thenReturn(stubBook);
|
||||
when(proc.processFile(any())).thenReturn(fileProcessResult);
|
||||
|
||||
Book result = service.uploadFile(file, 7L, 2L);
|
||||
|
||||
assertThat(result).isSameAs(stubBook);
|
||||
assertThat(result).isSameAs(fileProcessResult.getBook());
|
||||
Path moved = tempDir.resolve("book.cbz");
|
||||
assertThat(Files.exists(moved)).isTrue();
|
||||
verify(notificationService).sendMessage(eq(Topic.BOOK_ADD), same(stubBook));
|
||||
verify(notificationService).sendMessage(eq(Topic.BOOK_ADD), same(fileProcessResult.getBook()));
|
||||
verifyNoInteractions(pdfMetadataExtractor, epubMetadataExtractor);
|
||||
}
|
||||
}
|
||||
|
||||
+12
-6
@@ -2,13 +2,11 @@ package com.adityachandel.booklore.util.builder;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.BookMapperImpl;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
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.LibraryScanMode;
|
||||
import com.adityachandel.booklore.model.enums.*;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.FileFingerprint;
|
||||
@@ -74,7 +72,7 @@ public class LibraryTestBuilder {
|
||||
lenient().when(bookFileProcessorMock.processFile(any(LibraryFile.class)))
|
||||
.then(invocation -> {
|
||||
LibraryFile libraryFile = invocation.getArgument(0);
|
||||
return processFile(libraryFile);
|
||||
return processFileResult(libraryFile);
|
||||
});
|
||||
lenient().when(bookRepositoryMock.getReferenceById(anyLong()))
|
||||
.thenAnswer(invocation -> {
|
||||
@@ -275,7 +273,15 @@ public class LibraryTestBuilder {
|
||||
return hexString.toString();
|
||||
}
|
||||
|
||||
private Book processFile(LibraryFile libraryFile) {
|
||||
private FileProcessResult processFileResult(LibraryFile libraryFile) {
|
||||
var book = processBook(libraryFile);
|
||||
return FileProcessResult.builder()
|
||||
.book(book)
|
||||
.status(FileProcessStatus.NEW)
|
||||
.build();
|
||||
}
|
||||
|
||||
private Book processBook(LibraryFile libraryFile) {
|
||||
var hash = computeFileHash(libraryFile.getFullPath());
|
||||
|
||||
long id = libraryFiles.indexOf(libraryFile) + 1L;
|
||||
|
||||
Generated
+10
@@ -25,6 +25,7 @@
|
||||
"@tweenjs/tween.js": "^25.0.0",
|
||||
"angular-oauth2-oidc": "^20.0.0",
|
||||
"chart.js": "^4.5.0",
|
||||
"chartjs-chart-matrix": "^3.0.0",
|
||||
"chartjs-plugin-datalabels": "^2.2.0",
|
||||
"epubjs": "^0.3.93",
|
||||
"jwt-decode": "^4.0.0",
|
||||
@@ -7450,6 +7451,15 @@
|
||||
"pnpm": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/chartjs-chart-matrix": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/chartjs-chart-matrix/-/chartjs-chart-matrix-3.0.0.tgz",
|
||||
"integrity": "sha512-lUWC1UaWkxGdG02dBJ5r1ppbSYB/uWmwAh11VEs7V3ZQItNCk4am+rmacwkgeb+SQeEj2hP9Qq4oGsUmPl/1lQ==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"chart.js": ">=3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/chartjs-plugin-datalabels": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/chartjs-plugin-datalabels/-/chartjs-plugin-datalabels-2.2.0.tgz",
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
"@tweenjs/tween.js": "^25.0.0",
|
||||
"angular-oauth2-oidc": "^20.0.0",
|
||||
"chart.js": "^4.5.0",
|
||||
"chartjs-chart-matrix": "^3.0.0",
|
||||
"chartjs-plugin-datalabels": "^2.2.0",
|
||||
"epubjs": "^0.3.93",
|
||||
"jwt-decode": "^4.0.0",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Component, inject, OnInit, OnDestroy} from '@angular/core';
|
||||
import {RxStompService} from './shared/websocket/rx-stomp.service';
|
||||
import {BookService} from './book/service/book.service';
|
||||
import {NotificationEventService} from './shared/websocket/notification-event.service';
|
||||
@@ -12,6 +12,9 @@ import {MetadataBatchProgressNotification} from './core/model/metadata-batch-pro
|
||||
import {MetadataProgressService} from './core/service/metadata-progress-service';
|
||||
import {BookdropFileNotification, BookdropFileService} from './bookdrop/bookdrop-file.service';
|
||||
import {TaskEventService} from './shared/websocket/task-event.service';
|
||||
import {DuplicateFileNotification} from './shared/websocket/model/duplicate-file-notification.model';
|
||||
import {DuplicateFileService} from './shared/websocket/duplicate-file.service';
|
||||
import {Subscription} from 'rxjs';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
@@ -20,9 +23,11 @@ import {TaskEventService} from './shared/websocket/task-event.service';
|
||||
standalone: true,
|
||||
imports: [ConfirmDialog, Toast, RouterOutlet]
|
||||
})
|
||||
export class AppComponent implements OnInit {
|
||||
export class AppComponent implements OnInit, OnDestroy {
|
||||
|
||||
loading = true;
|
||||
private subscriptions: Subscription[] = [];
|
||||
private subscriptionsInitialized = false; // Prevent multiple subscription setups
|
||||
private authInit = inject(AuthInitializationService);
|
||||
private bookService = inject(BookService);
|
||||
private rxStompService = inject(RxStompService);
|
||||
@@ -30,37 +35,70 @@ export class AppComponent implements OnInit {
|
||||
private metadataProgressService = inject(MetadataProgressService);
|
||||
private bookdropFileService = inject(BookdropFileService);
|
||||
private taskEventService = inject(TaskEventService);
|
||||
private appConfigService = inject(AppConfigService);
|
||||
private duplicateFileService = inject(DuplicateFileService);
|
||||
private appConfigService = inject(AppConfigService); // Keep it here to ensure the service is initialized
|
||||
|
||||
ngOnInit(): void {
|
||||
this.authInit.initialized$.subscribe(ready => {
|
||||
this.loading = !ready;
|
||||
});
|
||||
this.rxStompService.watch('/user/queue/book-add').subscribe(msg =>
|
||||
this.bookService.handleNewlyCreatedBook(JSON.parse(msg.body))
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/books-remove').subscribe(msg =>
|
||||
this.bookService.handleRemovedBookIds(JSON.parse(msg.body))
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/book-metadata-update').subscribe(msg =>
|
||||
this.bookService.handleBookUpdate(JSON.parse(msg.body))
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/book-metadata-batch-update').subscribe(msg =>
|
||||
this.bookService.handleMultipleBookUpdates(JSON.parse(msg.body))
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/book-metadata-batch-progress').subscribe(msg =>
|
||||
this.metadataProgressService.handleIncomingProgress(JSON.parse(msg.body) as MetadataBatchProgressNotification)
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/log').subscribe(msg => {
|
||||
const logNotification = parseLogNotification(msg.body);
|
||||
this.notificationEventService.handleNewNotification(logNotification);
|
||||
});
|
||||
this.rxStompService.watch('/user/queue/task').subscribe(msg =>
|
||||
this.taskEventService.handleTaskMessage(parseTaskMessage(msg.body))
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/bookdrop-file').subscribe(msg => {
|
||||
const notification = JSON.parse(msg.body) as BookdropFileNotification;
|
||||
this.bookdropFileService.handleIncomingFile(notification);
|
||||
if (ready && !this.subscriptionsInitialized) {
|
||||
this.setupWebSocketSubscriptions();
|
||||
this.subscriptionsInitialized = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private setupWebSocketSubscriptions(): void {
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-add').subscribe(msg =>
|
||||
this.bookService.handleNewlyCreatedBook(JSON.parse(msg.body))
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/books-remove').subscribe(msg =>
|
||||
this.bookService.handleRemovedBookIds(JSON.parse(msg.body))
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-metadata-update').subscribe(msg =>
|
||||
this.bookService.handleBookUpdate(JSON.parse(msg.body))
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-metadata-batch-update').subscribe(msg =>
|
||||
this.bookService.handleMultipleBookUpdates(JSON.parse(msg.body))
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-metadata-batch-progress').subscribe(msg =>
|
||||
this.metadataProgressService.handleIncomingProgress(JSON.parse(msg.body) as MetadataBatchProgressNotification)
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/log').subscribe(msg => {
|
||||
const logNotification = parseLogNotification(msg.body);
|
||||
this.notificationEventService.handleNewNotification(logNotification);
|
||||
})
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/task').subscribe(msg =>
|
||||
this.taskEventService.handleTaskMessage(parseTaskMessage(msg.body))
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/duplicate-file').subscribe(msg =>
|
||||
this.duplicateFileService.addDuplicateFile(JSON.parse(msg.body) as DuplicateFileNotification)
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/bookdrop-file').subscribe(msg => {
|
||||
const notification = JSON.parse(msg.body) as BookdropFileNotification;
|
||||
this.bookdropFileService.handleIncomingFile(notification);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.subscriptions.forEach(sub => sub.unsubscribe());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,14 +22,15 @@ export class BookRuleEvaluatorService {
|
||||
const normalize = (val: any): any => {
|
||||
if (val === null || val === undefined) return val;
|
||||
if (val instanceof Date) return val;
|
||||
const date = new Date(val);
|
||||
if (!isNaN(date.getTime())) return date;
|
||||
if (typeof val === 'string') return val.toLowerCase();
|
||||
if (typeof val === 'string') {
|
||||
const date = new Date(val);
|
||||
if (!isNaN(date.getTime())) return date;
|
||||
return val.toLowerCase();
|
||||
}
|
||||
return val;
|
||||
};
|
||||
|
||||
const value = normalize(rawValue);
|
||||
|
||||
const ruleVal = normalize(rule.value);
|
||||
const ruleStart = normalize(rule.valueStart);
|
||||
const ruleEnd = normalize(rule.valueEnd);
|
||||
|
||||
@@ -407,7 +407,7 @@
|
||||
@if (this.showFilter) {
|
||||
<div
|
||||
class="mobile-filter-mask"
|
||||
(click)="this.showFilter = false">
|
||||
(click)="toggleSidebar()">
|
||||
</div>
|
||||
<app-book-filter
|
||||
[showFilter]="showFilter"
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div class="flex justify-end px-4">
|
||||
<div class="flex justify-end px-4 pt-4">
|
||||
<p-button icon="pi pi-refresh" label="Reset" outlined="true" severity="warn" (onClick)="resetFieldLocks()"></p-button>
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<div class="flex gap-4 justify-center">
|
||||
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
<div class="dialog-container">
|
||||
<div class="info-message">
|
||||
<i class="pi pi-exclamation-triangle"></i>
|
||||
<p>{{ totalRecords }} duplicate file groups have been detected in your library. To maintain data integrity and ensure optimal performance, please review and remove these duplicate entries from your file system.</p>
|
||||
</div>
|
||||
|
||||
<div class="table-container">
|
||||
<p-table
|
||||
#dataTable
|
||||
[value]="(duplicateFiles$ | async) || []"
|
||||
[scrollable]="true"
|
||||
scrollHeight="100%"
|
||||
[paginator]="false"
|
||||
[rows]="15"
|
||||
[rowHover]="true">
|
||||
|
||||
<ng-template pTemplate="body" let-group>
|
||||
<tr>
|
||||
<td>
|
||||
<div class="hash-group">
|
||||
<div class="hash-header">
|
||||
<i class="pi pi-copy"></i>
|
||||
<span class="hash-label">Hash:</span>
|
||||
<span class="hash-value">{{ group.hash }}</span>
|
||||
<span class="file-count">({{ group.files.length }} files)</span>
|
||||
</div>
|
||||
|
||||
<div class="files-list">
|
||||
@for (file of (group.files || []); track file.fullPath) {
|
||||
<div class="file-item-compact">
|
||||
<div class="file-icon">
|
||||
<i class="pi pi-file"></i>
|
||||
</div>
|
||||
<div class="file-details">
|
||||
<div class="filename">{{ file.fileName }}</div>
|
||||
<div class="file-path" [title]="file.fullPath">{{ file.fullPath }}</div>
|
||||
<div class="library-info">
|
||||
<i class="pi pi-database"></i>
|
||||
<span>{{ file.libraryName }}</span>
|
||||
<span class="timestamp">{{ file.timestamp | date:'short' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
|
||||
<ng-template pTemplate="emptymessage">
|
||||
<tr>
|
||||
<td class="empty-message">
|
||||
<div class="empty-content">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<span>No duplicate files detected</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
</div>
|
||||
|
||||
<div class="bottom-fixed-area">
|
||||
<div class="paginator-container">
|
||||
<p-paginator
|
||||
[first]="first"
|
||||
[rows]="rows"
|
||||
[totalRecords]="totalRecords"
|
||||
[showCurrentPageReport]="true"
|
||||
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} duplicate file groups"
|
||||
(onPageChange)="onPageChange($event)">
|
||||
</p-paginator>
|
||||
</div>
|
||||
|
||||
<div class="dialog-actions">
|
||||
<p-button
|
||||
label="Acknowledge"
|
||||
icon="pi pi-check"
|
||||
(click)="acknowledgeAndClose()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
.dialog-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.table-container {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
margin-bottom: 100px;
|
||||
|
||||
::ng-deep .p-datatable {
|
||||
height: 100%;
|
||||
|
||||
.p-datatable-wrapper {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.p-datatable-tbody > tr > td {
|
||||
border: none !important;
|
||||
padding: 0.5rem 0.5rem;
|
||||
}
|
||||
|
||||
.p-datatable-tbody > tr {
|
||||
border: none !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.bottom-fixed-area {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: var(--surface-ground);
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.paginator-container {
|
||||
::ng-deep .p-paginator {
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
}
|
||||
|
||||
.dialog-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.duplicate-files-content {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.hash-group {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 1rem;
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
.hash-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.75rem;
|
||||
padding-bottom: 0.5rem;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
i {
|
||||
color: var(--primary-color);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.hash-label {
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.hash-value {
|
||||
font-family: 'Courier New', monospace;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-size: 1rem;
|
||||
font-weight: 900;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.file-count {
|
||||
background: var(--primary-color);
|
||||
color: white;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 12px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.files-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.file-item-compact {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem;
|
||||
border-radius: 6px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
transition: all 0.2s ease;
|
||||
margin-left: 1rem;
|
||||
}
|
||||
|
||||
.file-icon {
|
||||
background: var(--primary-color);
|
||||
color: white;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
|
||||
i {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.file-details {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.filename {
|
||||
font-family: 'Courier New', monospace;
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
word-break: break-word;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.file-path {
|
||||
font-size: 0.95rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-family: 'Courier New', monospace;
|
||||
word-break: break-all;
|
||||
line-height: 1.2;
|
||||
max-height: 2.4em;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.library-info {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
margin-top: 0.1rem;
|
||||
|
||||
i {
|
||||
color: var(--primary-color);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.timestamp {
|
||||
margin-left: auto;
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
}
|
||||
|
||||
.empty-message {
|
||||
text-align: center !important;
|
||||
padding: 3rem 1rem !important;
|
||||
|
||||
.empty-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
opacity: 0.6;
|
||||
|
||||
i {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
span {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.info-message {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
background: rgba(234, 88, 12, 0.1);
|
||||
border: 1px solid rgba(234, 88, 12, 0.3);
|
||||
border-radius: 0.375rem;
|
||||
color: #fbbf24;
|
||||
|
||||
i {
|
||||
color: #f59e0b;
|
||||
font-size: 1.125rem;
|
||||
margin-top: 0.125rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog';
|
||||
import { TableModule } from 'primeng/table';
|
||||
import { ButtonModule } from 'primeng/button';
|
||||
import { TooltipModule } from 'primeng/tooltip';
|
||||
import { PaginatorModule } from 'primeng/paginator';
|
||||
import { Observable, map } from 'rxjs';
|
||||
import {DuplicateFileNotification} from '../../../shared/websocket/model/duplicate-file-notification.model';
|
||||
import {DuplicateFileService} from '../../../shared/websocket/duplicate-file.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-duplicate-files-dialog',
|
||||
standalone: true,
|
||||
imports: [CommonModule, TableModule, ButtonModule, TooltipModule, PaginatorModule],
|
||||
templateUrl: './duplicate-files-dialog.component.html',
|
||||
styleUrls: ['./duplicate-files-dialog.component.scss']
|
||||
})
|
||||
export class DuplicateFilesDialogComponent implements OnInit {
|
||||
duplicateFiles$: Observable<{ hash: string; files: DuplicateFileNotification[] }[]>;
|
||||
totalRecords = 0;
|
||||
first = 0;
|
||||
rows = 15;
|
||||
|
||||
constructor(
|
||||
public ref: DynamicDialogRef,
|
||||
public config: DynamicDialogConfig,
|
||||
private duplicateFileService: DuplicateFileService
|
||||
) {
|
||||
this.duplicateFiles$ = this.config.data.duplicateFiles$.pipe(
|
||||
map((files: DuplicateFileNotification[] | null) => {
|
||||
if (!files) return [];
|
||||
|
||||
// Group files by hash
|
||||
const groupedFiles = files.reduce((acc, file) => {
|
||||
if (!acc[file.hash]) {
|
||||
acc[file.hash] = [];
|
||||
}
|
||||
acc[file.hash].push(file);
|
||||
return acc;
|
||||
}, {} as { [hash: string]: DuplicateFileNotification[] });
|
||||
|
||||
const groups = Object.entries(groupedFiles).map(([hash, files]) => ({
|
||||
hash,
|
||||
files: files.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
|
||||
}));
|
||||
|
||||
this.totalRecords = groups.length;
|
||||
return groups.slice(this.first, this.first + this.rows);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
ngOnInit() {}
|
||||
|
||||
onPageChange(event: any) {
|
||||
this.first = event.first;
|
||||
this.rows = event.rows;
|
||||
this.duplicateFiles$ = this.config.data.duplicateFiles$.pipe(
|
||||
map((files: DuplicateFileNotification[] | null) => {
|
||||
if (!files) return [];
|
||||
|
||||
const groupedFiles = files.reduce((acc, file) => {
|
||||
if (!acc[file.hash]) {
|
||||
acc[file.hash] = [];
|
||||
}
|
||||
acc[file.hash].push(file);
|
||||
return acc;
|
||||
}, {} as { [hash: string]: DuplicateFileNotification[] });
|
||||
|
||||
const groups = Object.entries(groupedFiles).map(([hash, files]) => ({
|
||||
hash,
|
||||
files: files.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
|
||||
}));
|
||||
|
||||
this.totalRecords = groups.length;
|
||||
return groups.slice(this.first, this.first + this.rows);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
acknowledgeAndClose() {
|
||||
this.duplicateFileService.clearDuplicateFiles();
|
||||
this.ref.close();
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
@if (duplicateFilesCount$ | async; as count) {
|
||||
@if (count > 0) {
|
||||
<div class="flex flex-col p-4 space-y-2 live-border">
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<i class="pi pi-exclamation-triangle text-yellow-500"></i>
|
||||
<span class="font-normal text-zinc-200">{{ count }} duplicate files detected</span>
|
||||
</div>
|
||||
<p-tag [value]="count.toString()" severity="warn" [rounded]="true"></p-tag>
|
||||
</div>
|
||||
<p-button
|
||||
label="View Details"
|
||||
icon="pi pi-list"
|
||||
outlined
|
||||
size="small"
|
||||
severity="info"
|
||||
fluid
|
||||
(click)="openDialog()">
|
||||
</p-button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
.duplicate-files-content {
|
||||
max-height: 500px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.live-border {
|
||||
border: 0.5px solid var(--primary-color);
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import {Component, inject, OnDestroy} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {DialogModule} from 'primeng/dialog';
|
||||
import {ButtonModule} from 'primeng/button';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {TagModule} from 'primeng/tag';
|
||||
import {Observable} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {DuplicateFileService} from '../../../shared/websocket/duplicate-file.service';
|
||||
import {DuplicateFileNotification} from '../../../shared/websocket/model/duplicate-file-notification.model';
|
||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {DuplicateFilesDialogComponent} from './duplicate-files-dialog.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-duplicate-files-notification',
|
||||
standalone: true,
|
||||
imports: [CommonModule, DialogModule, ButtonModule, TableModule, TagModule],
|
||||
templateUrl: './duplicate-files-notification.component.html',
|
||||
styleUrls: ['./duplicate-files-notification.component.scss'],
|
||||
providers: [DialogService]
|
||||
})
|
||||
export class DuplicateFilesNotificationComponent implements OnDestroy {
|
||||
displayDialog = false;
|
||||
|
||||
private duplicateFileService = inject(DuplicateFileService);
|
||||
private ref: DynamicDialogRef | undefined;
|
||||
|
||||
duplicateFiles$ = this.duplicateFileService.duplicateFiles$;
|
||||
duplicateFilesCount$: Observable<number> = this.duplicateFiles$.pipe(
|
||||
map(files => files?.length || 0)
|
||||
);
|
||||
|
||||
constructor(
|
||||
private dialogService: DialogService
|
||||
) {
|
||||
}
|
||||
|
||||
openDialog() {
|
||||
this.ref = this.dialogService.open(DuplicateFilesDialogComponent, {
|
||||
header: 'Duplicate Files Detected',
|
||||
width: '80dvw',
|
||||
height: '75dvh',
|
||||
contentStyle: {overflow: 'hidden'},
|
||||
maximizable: true,
|
||||
modal: true,
|
||||
data: {
|
||||
duplicateFiles$: this.duplicateFiles$
|
||||
}
|
||||
});
|
||||
|
||||
this.ref.onClose.subscribe((result: any) => {
|
||||
if (result) {
|
||||
// Handle any result from dialog if needed
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
closeDialog() {
|
||||
this.displayDialog = false;
|
||||
}
|
||||
|
||||
clearAllDuplicates() {
|
||||
this.duplicateFileService.clearDuplicateFiles();
|
||||
this.closeDialog();
|
||||
}
|
||||
|
||||
removeDuplicate(file: DuplicateFileNotification) {
|
||||
this.duplicateFileService.removeDuplicateFile(file.fullPath, file.libraryId);
|
||||
}
|
||||
|
||||
formatTimestamp(timestamp: string): string {
|
||||
return new Date(timestamp).toLocaleString();
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
if (this.ref) {
|
||||
this.ref.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -1,5 +1,3 @@
|
||||
.live-border {
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--primary-color);
|
||||
border-radius: 0.5rem;
|
||||
border: 0.5px solid var(--primary-color);
|
||||
}
|
||||
|
||||
+1
-3
@@ -1,6 +1,4 @@
|
||||
.live-border {
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--primary-color);
|
||||
border-radius: 0.5rem;
|
||||
border: 0.5px solid var(--primary-color);
|
||||
}
|
||||
|
||||
|
||||
+3
@@ -1,5 +1,8 @@
|
||||
<div class="metadata-progress-box flex gap-4 flex-col w-[25rem] max-h-[60vh] overflow-y-auto">
|
||||
<app-live-notification-box/>
|
||||
@if (hasDuplicateFiles$ | async) {
|
||||
<app-duplicate-files-notification/>
|
||||
}
|
||||
@if (hasActiveTasks$ | async) {
|
||||
<app-live-task-event-box/>
|
||||
}
|
||||
|
||||
+9
-1
@@ -8,6 +8,8 @@ import {map} from 'rxjs/operators';
|
||||
import {AsyncPipe} from '@angular/common';
|
||||
import {BookdropFilesWidgetComponent} from '../../../bookdrop/bookdrop-files-widget-component/bookdrop-files-widget.component';
|
||||
import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service';
|
||||
import {DuplicateFilesNotificationComponent} from '../duplicate-files-notification/duplicate-files-notification.component';
|
||||
import {DuplicateFileService} from '../../../shared/websocket/duplicate-file.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-unified-notification-popover-component',
|
||||
@@ -16,7 +18,8 @@ import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service';
|
||||
LiveTaskEventBoxComponent,
|
||||
MetadataProgressWidgetComponent,
|
||||
AsyncPipe,
|
||||
BookdropFilesWidgetComponent
|
||||
BookdropFilesWidgetComponent,
|
||||
DuplicateFilesNotificationComponent
|
||||
],
|
||||
templateUrl: './unified-notification-popover-component.html',
|
||||
standalone: true,
|
||||
@@ -25,6 +28,7 @@ import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service';
|
||||
export class UnifiedNotificationBoxComponent {
|
||||
metadataProgressService = inject(MetadataProgressService);
|
||||
bookdropFileService = inject(BookdropFileService);
|
||||
duplicateFileService = inject(DuplicateFileService);
|
||||
taskEventService = inject(TaskEventService);
|
||||
|
||||
hasMetadataTasks$ = this.metadataProgressService.activeTasks$.pipe(
|
||||
@@ -33,6 +37,10 @@ export class UnifiedNotificationBoxComponent {
|
||||
|
||||
hasPendingBookdropFiles$ = this.bookdropFileService.hasPendingFiles$;
|
||||
|
||||
hasDuplicateFiles$ = this.duplicateFileService.duplicateFiles$.pipe(
|
||||
map(files => files && files.length > 0)
|
||||
);
|
||||
|
||||
hasActiveTasks$ = this.taskEventService.tasks$.pipe(
|
||||
map(tasks => tasks.length > 0)
|
||||
);
|
||||
|
||||
@@ -31,49 +31,61 @@
|
||||
}
|
||||
|
||||
<div>
|
||||
<div class="flex flex-row items-center justify-between hover:bg-surface-800 rounded-md">
|
||||
<div
|
||||
class="flex flex-row items-center justify-between hover:bg-surface-800 rounded-md cursor-pointer"
|
||||
(click)="triggerLink()"
|
||||
>
|
||||
@if ((item.routerLink && !item.items)) {
|
||||
<a
|
||||
#link
|
||||
(click)="itemClick($event)"
|
||||
[ngClass]="item.class"
|
||||
[routerLink]="item.routerLink" routerLinkActive="active-route"
|
||||
[ngClass]="item.class + ' flex items-center gap-2 w-full'"
|
||||
[routerLink]="item.routerLink"
|
||||
routerLinkActive="active-route"
|
||||
[routerLinkActiveOptions]="item.routerLinkActiveOptions || { paths: 'exact', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored' }"
|
||||
[fragment]="item.fragment" [queryParamsHandling]="item.queryParamsHandling"
|
||||
[fragment]="item.fragment"
|
||||
[queryParamsHandling]="item.queryParamsHandling"
|
||||
[preserveFragment]="item.preserveFragment"
|
||||
[skipLocationChange]="item.skipLocationChange" [replaceUrl]="item.replaceUrl" [state]="item.state"
|
||||
[skipLocationChange]="item.skipLocationChange"
|
||||
[replaceUrl]="item.replaceUrl"
|
||||
[state]="item.state"
|
||||
[queryParams]="item.queryParams"
|
||||
[attr.target]="item.target" tabindex="0" pRipple>
|
||||
[attr.target]="item.target"
|
||||
tabindex="0"
|
||||
pRipple
|
||||
>
|
||||
<i [ngClass]="item.icon" class="layout-menuitem-icon"></i>
|
||||
<span class="layout-menuitem-text w-full truncate">
|
||||
{{ item.label }}
|
||||
</span>
|
||||
{{ item.label }}
|
||||
</span>
|
||||
</a>
|
||||
}
|
||||
|
||||
<span>
|
||||
@if (item.type === 'Library' || item.type === 'Shelf' || item.type === 'magicShelfItem') {
|
||||
@if ((item.type !== 'Library' || (admin || canManipulateLibrary)) && item.label !== 'Unshelved' && item.label !== 'Kobo') {
|
||||
<p-button
|
||||
(click)="entitymenu.toggle($event)"
|
||||
(mouseover)="hovered = true"
|
||||
(mouseleave)="hovered = false"
|
||||
[text]="true"
|
||||
[outlined]="false"
|
||||
[rounded]="true"
|
||||
[label]="hovered ? '' : (item.bookCount$ | async)?.toString() || ''"
|
||||
[icon]="hovered ? 'pi pi-ellipsis-v' : ''"
|
||||
[style.height]="'30px'"
|
||||
[style.display]="'flex'">
|
||||
</p-button>
|
||||
}
|
||||
<p-menu #entitymenu [model]="item.menu" [popup]="true" appendTo="body"></p-menu>
|
||||
}
|
||||
@if (item.type === 'Library' || item.type === 'Shelf' || item.type === 'magicShelfItem') {
|
||||
@if ((item.type !== 'Library' || (admin || canManipulateLibrary)) && item.label !== 'Unshelved' && item.label !== 'Kobo') {
|
||||
<p-button
|
||||
(click)="entitymenu.toggle($event); $event.stopPropagation()"
|
||||
(mouseover)="hovered = true"
|
||||
(mouseleave)="hovered = false"
|
||||
[text]="true"
|
||||
[outlined]="false"
|
||||
[rounded]="true"
|
||||
[label]="hovered ? '' : (item.bookCount$ | async)?.toString() || ''"
|
||||
[icon]="hovered ? 'pi pi-ellipsis-v' : ''"
|
||||
[style.height]="'30px'"
|
||||
[style.display]="'flex'"
|
||||
></p-button>
|
||||
}
|
||||
<p-menu #entitymenu [model]="item.menu" [popup]="true" appendTo="body"></p-menu>
|
||||
}
|
||||
|
||||
@if (item.type === 'Library' && (!admin && !canManipulateLibrary) || item.type === 'All Books' || item.label === 'Unshelved' || item.label === 'Kobo') {
|
||||
<p class="text-[var(--primary-color)] pr-3">
|
||||
{{ (item.bookCount$ | async)?.toString() || '0' }}
|
||||
</p>
|
||||
{{ (item.bookCount$ | async)?.toString() || '0' }}
|
||||
</p>
|
||||
}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div [@children]="isExpanded(key) ? 'expanded' : 'collapsed'" style="overflow: hidden;">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {Component, HostBinding, Input, OnDestroy, OnInit} from '@angular/core';
|
||||
import {Component, ElementRef, HostBinding, Input, OnDestroy, OnInit, ViewChild} from '@angular/core';
|
||||
import {NavigationEnd, Router, RouterLink, RouterLinkActive} from '@angular/router';
|
||||
import {animate, state, style, transition, trigger} from '@angular/animations';
|
||||
import {Subscription} from 'rxjs';
|
||||
@@ -41,38 +41,30 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
|
||||
@Input() index!: number;
|
||||
@Input() @HostBinding('class.layout-root-menuitem') root!: boolean;
|
||||
@Input() parentKey!: string;
|
||||
@ViewChild('linkRef') linkRef!: ElementRef<HTMLAnchorElement>;
|
||||
|
||||
hovered = false;
|
||||
active = false;
|
||||
key: string = "";
|
||||
|
||||
canManipulateLibrary: boolean = false;
|
||||
admin: boolean = false;
|
||||
|
||||
expandedItems = new Set<string>();
|
||||
menuSourceSubscription: Subscription;
|
||||
menuResetSubscription: Subscription;
|
||||
|
||||
expandedItems = new Set<string>();
|
||||
|
||||
toggleExpand(key: string) {
|
||||
if (this.expandedItems.has(key)) {
|
||||
this.expandedItems.delete(key);
|
||||
} else {
|
||||
this.expandedItems.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
isExpanded(key: string): boolean {
|
||||
return this.expandedItems.has(key);
|
||||
}
|
||||
|
||||
constructor(public router: Router, private menuService: MenuService, private userService: UserService, private dialogLauncher: DialogLauncherService) {
|
||||
constructor(
|
||||
public router: Router,
|
||||
private menuService: MenuService,
|
||||
private userService: UserService,
|
||||
private dialogLauncher: DialogLauncherService
|
||||
) {
|
||||
this.userService.userState$.subscribe(userState => {
|
||||
if (userState?.user) {
|
||||
this.canManipulateLibrary = userState.user.permissions.canManipulateLibrary;
|
||||
this.admin = userState.user.permissions.admin;
|
||||
}
|
||||
});
|
||||
|
||||
this.menuSourceSubscription = this.menuService.menuSource$.subscribe(value => {
|
||||
Promise.resolve(null).then(() => {
|
||||
if (value.routeEvent) {
|
||||
@@ -105,6 +97,27 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
if (this.menuSourceSubscription) {
|
||||
this.menuSourceSubscription.unsubscribe();
|
||||
}
|
||||
if (this.menuResetSubscription) {
|
||||
this.menuResetSubscription.unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
toggleExpand(key: string) {
|
||||
if (this.expandedItems.has(key)) {
|
||||
this.expandedItems.delete(key);
|
||||
} else {
|
||||
this.expandedItems.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
isExpanded(key: string): boolean {
|
||||
return this.expandedItems.has(key);
|
||||
}
|
||||
|
||||
updateActiveStateFromRoute() {
|
||||
const activeRoute = this.router.isActive(this.item.routerLink[0], {
|
||||
paths: 'exact',
|
||||
@@ -131,20 +144,6 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
|
||||
this.menuService.onMenuStateChange({key: this.key});
|
||||
}
|
||||
|
||||
@HostBinding('class.active-menuitem')
|
||||
get activeClass() {
|
||||
return this.active && !this.root;
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
if (this.menuSourceSubscription) {
|
||||
this.menuSourceSubscription.unsubscribe();
|
||||
}
|
||||
if (this.menuResetSubscription) {
|
||||
this.menuResetSubscription.unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
openDialog(item: any) {
|
||||
if (item.type === 'library' && this.canManipulateLibrary) {
|
||||
this.dialogLauncher.openLibraryCreatorDialog();
|
||||
@@ -153,4 +152,15 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
|
||||
this.dialogLauncher.openMagicShelfDialog();
|
||||
}
|
||||
}
|
||||
|
||||
triggerLink() {
|
||||
if (this.item.routerLink && !this.item.items && this.linkRef) {
|
||||
this.linkRef.nativeElement.click();
|
||||
}
|
||||
}
|
||||
|
||||
@HostBinding('class.active-menuitem')
|
||||
get activeClass() {
|
||||
return this.active && !this.root;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,6 +178,15 @@
|
||||
</li>
|
||||
}
|
||||
}
|
||||
<li>
|
||||
<button
|
||||
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
|
||||
(click)="navigateToStats(); mobileMenu.hide()"
|
||||
>
|
||||
<i class="pi pi-chart-bar text-surface-100"></i>
|
||||
Charts
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button
|
||||
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
|
||||
|
||||
@@ -24,6 +24,7 @@ import {UnifiedNotificationBoxComponent} from '../../../core/component/unified-n
|
||||
import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service';
|
||||
import {DialogLauncherService} from '../../../dialog-launcher.service';
|
||||
import {TaskEventService} from '../../../shared/websocket/task-event.service';
|
||||
import {DuplicateFileService} from '../../../shared/websocket/duplicate-file.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-topbar',
|
||||
@@ -62,12 +63,14 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
showPulse = false;
|
||||
hasAnyTasks = false;
|
||||
hasPendingBookdropFiles = false;
|
||||
hasDuplicateFiles = false;
|
||||
|
||||
private eventTimer: any;
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
private latestTasks: { [taskId: string]: MetadataBatchProgressNotification } = {};
|
||||
private latestHasPendingFiles = false;
|
||||
private latestHasDuplicateFiles = false;
|
||||
|
||||
constructor(
|
||||
public layoutService: LayoutService,
|
||||
@@ -79,11 +82,13 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
private metadataProgressService: MetadataProgressService,
|
||||
private bookdropFileService: BookdropFileService,
|
||||
private dialogLauncher: DialogLauncherService,
|
||||
private taskEventService: TaskEventService
|
||||
private taskEventService: TaskEventService,
|
||||
private duplicateFileService: DuplicateFileService
|
||||
) {
|
||||
this.subscribeToMetadataProgress();
|
||||
this.subscribeToNotifications();
|
||||
this.subscribeToTaskEvents();
|
||||
this.subscribeToDuplicateFiles();
|
||||
|
||||
this.metadataProgressService.activeTasks$
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
@@ -102,6 +107,15 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
this.updateCompletedTaskCount();
|
||||
this.updateTaskVisibilityWithBookdrop();
|
||||
});
|
||||
|
||||
this.duplicateFileService.duplicateFiles$
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe((duplicateFiles) => {
|
||||
this.latestHasDuplicateFiles = duplicateFiles && duplicateFiles.length > 0;
|
||||
this.hasDuplicateFiles = this.latestHasDuplicateFiles;
|
||||
this.updateCompletedTaskCount();
|
||||
this.updateTaskVisibilityWithDuplicates();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
@@ -174,6 +188,16 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
private subscribeToDuplicateFiles() {
|
||||
this.duplicateFileService.duplicateFiles$
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe((duplicateFiles) => {
|
||||
if (duplicateFiles && duplicateFiles.length > 0) {
|
||||
this.triggerPulseEffect();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private triggerPulseEffect() {
|
||||
this.showPulse = true;
|
||||
clearTimeout(this.eventTimer);
|
||||
@@ -185,7 +209,8 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
private updateCompletedTaskCount() {
|
||||
const completedMetadataTasks = Object.values(this.latestTasks).filter(task => task.status === 'COMPLETED').length;
|
||||
const bookdropFileTaskCount = this.latestHasPendingFiles ? 1 : 0;
|
||||
this.completedTaskCount = completedMetadataTasks + bookdropFileTaskCount;
|
||||
const duplicateFileTaskCount = this.latestHasDuplicateFiles ? 1 : 0;
|
||||
this.completedTaskCount = completedMetadataTasks + bookdropFileTaskCount + duplicateFileTaskCount;
|
||||
}
|
||||
|
||||
private updateTaskVisibility(tasks: { [taskId: string]: MetadataBatchProgressNotification }) {
|
||||
@@ -196,6 +221,11 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
|
||||
private updateTaskVisibilityWithBookdrop() {
|
||||
this.hasActiveOrCompletedTasks = this.hasActiveOrCompletedTasks || this.hasPendingBookdropFiles;
|
||||
this.updateTaskVisibilityWithDuplicates();
|
||||
}
|
||||
|
||||
private updateTaskVisibilityWithDuplicates() {
|
||||
this.hasActiveOrCompletedTasks = this.hasActiveOrCompletedTasks || this.hasDuplicateFiles;
|
||||
}
|
||||
|
||||
get iconClass(): string {
|
||||
@@ -208,7 +238,7 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
get iconColor(): string {
|
||||
if (this.progressHighlight) return 'yellow';
|
||||
if (this.showPulse) return 'red';
|
||||
if (this.completedTaskCount > 0 || this.hasPendingBookdropFiles) return 'orange';
|
||||
if (this.completedTaskCount > 0 || this.hasPendingBookdropFiles || this.hasDuplicateFiles) return 'orange';
|
||||
return 'inherit';
|
||||
}
|
||||
|
||||
@@ -218,7 +248,7 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
|
||||
get shouldShowNotificationBadge(): boolean {
|
||||
return (
|
||||
(this.completedTaskCount > 0 || this.hasPendingBookdropFiles) &&
|
||||
(this.completedTaskCount > 0 || this.hasPendingBookdropFiles || this.hasDuplicateFiles) &&
|
||||
!this.progressHighlight &&
|
||||
!this.showPulse
|
||||
);
|
||||
|
||||
+18
-14
@@ -22,10 +22,10 @@
|
||||
<div class="form-row">
|
||||
<label class="label"></label>
|
||||
<div class="input-container">
|
||||
@if (!book.metadata!['coverLocked']) {
|
||||
@if (!metadataForm.get('coverLocked')?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata!['coverLocked']) {
|
||||
@if (metadataForm.get('coverLocked')?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="warn"></p-button>
|
||||
}
|
||||
<p-image
|
||||
@@ -65,13 +65,14 @@
|
||||
<div class="form-row">
|
||||
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
|
||||
<div class="input-container">
|
||||
@if (!book.metadata![field.lockedKey]) {
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata![field.lockedKey]) {
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
|
||||
}
|
||||
<input pSize="small" fluid pInputText id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"/>
|
||||
<input pSize="small" fluid pInputText id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"
|
||||
[disabled]="metadataForm.get(field.lockedKey)?.value"/>
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
|
||||
[outlined]="true"
|
||||
@@ -93,10 +94,10 @@
|
||||
<div class="form-row">
|
||||
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
|
||||
<div class="input-container">
|
||||
@if (!book.metadata![field.lockedKey]) {
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata![field.lockedKey]) {
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
|
||||
}
|
||||
<div class="w-full px-4">
|
||||
@@ -110,7 +111,8 @@
|
||||
[suggestions]="getFiltered(field.controlName)"
|
||||
(completeMethod)="filterItems($event, field.controlName)"
|
||||
(onKeyUp)="onAutoCompleteKeyUp(field.controlName, $event)"
|
||||
(onSelect)="onAutoCompleteSelect(field.controlName, $event)">
|
||||
(onSelect)="onAutoCompleteSelect(field.controlName, $event)"
|
||||
[disabled]="metadataForm.get(field.lockedKey)?.value">
|
||||
</p-autoComplete>
|
||||
</div>
|
||||
<p-button
|
||||
@@ -142,13 +144,14 @@
|
||||
<div class="form-row">
|
||||
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
|
||||
<div class="input-container">
|
||||
@if (!book.metadata![field.lockedKey]) {
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata![field.lockedKey]) {
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
|
||||
}
|
||||
<textarea rows="3" pTextarea id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"></textarea>
|
||||
<textarea rows="3" pTextarea id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"
|
||||
[disabled]="metadataForm.get(field.lockedKey)?.value"></textarea>
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
|
||||
[outlined]="true"
|
||||
@@ -170,13 +173,14 @@
|
||||
<div class="form-row">
|
||||
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
|
||||
<div class="input-container">
|
||||
@if (!book.metadata![field.lockedKey]) {
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
|
||||
}
|
||||
@if (book.metadata![field.lockedKey]) {
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
|
||||
}
|
||||
<input pInputText pSize="small" id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"/>
|
||||
<input pInputText pSize="small" id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"
|
||||
[disabled]="metadataForm.get(field.lockedKey)?.value"/>
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
|
||||
[outlined]="true"
|
||||
|
||||
+34
-25
@@ -265,31 +265,40 @@ export class MetadataPickerComponent implements OnInit {
|
||||
coverLocked: metadata.coverLocked || false,
|
||||
});
|
||||
|
||||
if (metadata.titleLocked) this.metadataForm.get('title')?.disable();
|
||||
if (metadata.subtitleLocked) this.metadataForm.get('subtitle')?.disable();
|
||||
if (metadata.authorsLocked) this.metadataForm.get('authors')?.disable();
|
||||
if (metadata.categoriesLocked) this.metadataForm.get('categories')?.disable();
|
||||
if (metadata.publisherLocked) this.metadataForm.get('publisher')?.disable();
|
||||
if (metadata.publishedDateLocked) this.metadataForm.get('publishedDate')?.disable();
|
||||
if (metadata.languageLocked) this.metadataForm.get('language')?.disable();
|
||||
if (metadata.isbn10Locked) this.metadataForm.get('isbn10')?.disable();
|
||||
if (metadata.isbn13Locked) this.metadataForm.get('isbn13')?.disable();
|
||||
if (metadata.asinLocked) this.metadataForm.get('asin')?.disable();
|
||||
if (metadata.personalRatingLocked) this.metadataForm.get('personalRating')?.disable();
|
||||
if (metadata.amazonReviewCountLocked) this.metadataForm.get('amazonReviewCount')?.disable();
|
||||
if (metadata.amazonRatingLocked) this.metadataForm.get('amazonRating')?.disable();
|
||||
if (metadata.googleIdLocked) this.metadataForm.get('googleIdCount')?.disable();
|
||||
if (metadata.goodreadsReviewCountLocked) this.metadataForm.get('goodreadsReviewCount')?.disable();
|
||||
if (metadata.goodreadsRatingLocked) this.metadataForm.get('goodreadsRating')?.disable();
|
||||
if (metadata.hardcoverIdLocked) this.metadataForm.get('hardcoverId')?.disable();
|
||||
if (metadata.hardcoverReviewCountLocked) this.metadataForm.get('hardcoverReviewCount')?.disable();
|
||||
if (metadata.hardcoverRatingLocked) this.metadataForm.get('hardcoverRating')?.disable();
|
||||
if (metadata.googleIdLocked) this.metadataForm.get('googleId')?.disable();
|
||||
if (metadata.pageCountLocked) this.metadataForm.get('pageCount')?.disable();
|
||||
if (metadata.descriptionLocked) this.metadataForm.get('description')?.disable();
|
||||
if (metadata.seriesNameLocked) this.metadataForm.get('seriesName')?.disable();
|
||||
if (metadata.seriesNumberLocked) this.metadataForm.get('seriesNumber')?.disable();
|
||||
if (metadata.seriesTotalLocked) this.metadataForm.get('seriesTotal')?.disable();
|
||||
// Always enable all fields before applying locked state
|
||||
Object.keys(this.metadataForm.controls).forEach((key) => {
|
||||
if (!key.endsWith('Locked')) {
|
||||
this.metadataForm.get(key)?.enable({emitEvent: false});
|
||||
}
|
||||
});
|
||||
|
||||
if (metadata.titleLocked) this.metadataForm.get('title')?.disable({emitEvent: false});
|
||||
if (metadata.subtitleLocked) this.metadataForm.get('subtitle')?.disable({emitEvent: false});
|
||||
if (metadata.authorsLocked) this.metadataForm.get('authors')?.disable({emitEvent: false});
|
||||
if (metadata.categoriesLocked) this.metadataForm.get('categories')?.disable({emitEvent: false});
|
||||
if (metadata.publisherLocked) this.metadataForm.get('publisher')?.disable({emitEvent: false});
|
||||
if (metadata.publishedDateLocked) this.metadataForm.get('publishedDate')?.disable({emitEvent: false});
|
||||
if (metadata.languageLocked) this.metadataForm.get('language')?.disable({emitEvent: false});
|
||||
if (metadata.isbn10Locked) this.metadataForm.get('isbn10')?.disable({emitEvent: false});
|
||||
if (metadata.isbn13Locked) this.metadataForm.get('isbn13')?.disable({emitEvent: false});
|
||||
if (metadata.asinLocked) this.metadataForm.get('asin')?.disable({emitEvent: false});
|
||||
if (metadata.personalRatingLocked) this.metadataForm.get('personalRating')?.disable({emitEvent: false});
|
||||
if (metadata.amazonReviewCountLocked) this.metadataForm.get('amazonReviewCount')?.disable({emitEvent: false});
|
||||
if (metadata.amazonRatingLocked) this.metadataForm.get('amazonRating')?.disable({emitEvent: false});
|
||||
if (metadata.googleIdLocked) this.metadataForm.get('googleIdCount')?.disable({emitEvent: false});
|
||||
if (metadata.comicvineIdLocked) this.metadataForm.get('comicvineId')?.disable({emitEvent: false});
|
||||
if (metadata.goodreadsIdLocked) this.metadataForm.get('goodreadsId')?.disable({emitEvent: false});
|
||||
if (metadata.goodreadsReviewCountLocked) this.metadataForm.get('goodreadsReviewCount')?.disable({emitEvent: false});
|
||||
if (metadata.goodreadsRatingLocked) this.metadataForm.get('goodreadsRating')?.disable({emitEvent: false});
|
||||
if (metadata.hardcoverIdLocked) this.metadataForm.get('hardcoverId')?.disable({emitEvent: false});
|
||||
if (metadata.hardcoverReviewCountLocked) this.metadataForm.get('hardcoverReviewCount')?.disable({emitEvent: false});
|
||||
if (metadata.hardcoverRatingLocked) this.metadataForm.get('hardcoverRating')?.disable({emitEvent: false});
|
||||
if (metadata.googleIdLocked) this.metadataForm.get('googleId')?.disable({emitEvent: false});
|
||||
if (metadata.pageCountLocked) this.metadataForm.get('pageCount')?.disable({emitEvent: false});
|
||||
if (metadata.descriptionLocked) this.metadataForm.get('description')?.disable({emitEvent: false});
|
||||
if (metadata.seriesNameLocked) this.metadataForm.get('seriesName')?.disable({emitEvent: false});
|
||||
if (metadata.seriesNumberLocked) this.metadataForm.get('seriesNumber')?.disable({emitEvent: false});
|
||||
if (metadata.seriesTotalLocked) this.metadataForm.get('seriesTotal')?.disable({emitEvent: false});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+16
-23
@@ -46,7 +46,7 @@
|
||||
<p-divider layout="vertical"/>
|
||||
|
||||
<p-button
|
||||
label="Lock Metadata"
|
||||
label="Lock All"
|
||||
icon="pi pi-lock"
|
||||
severity="warn"
|
||||
[outlined]="true"
|
||||
@@ -54,7 +54,7 @@
|
||||
</p-button>
|
||||
|
||||
<p-button
|
||||
label="Unlock Metadata"
|
||||
label="Unlock All"
|
||||
icon="pi pi-lock-open"
|
||||
severity="success"
|
||||
[outlined]="true"
|
||||
@@ -64,37 +64,30 @@
|
||||
<p-divider layout="vertical"/>
|
||||
|
||||
<p-button
|
||||
label="Previous"
|
||||
icon="pi pi-angle-left"
|
||||
severity="secondary"
|
||||
[outlined]="true"
|
||||
(click)="previous()"
|
||||
[disabled]="currentIndex === 0">
|
||||
</p-button>
|
||||
|
||||
<p-button
|
||||
[label]="isLast ? 'Reject & Finish' : 'Reject & Next'"
|
||||
[icon]="isLast ? 'pi pi-times-circle' : 'pi pi-angle-right'"
|
||||
iconPos="right"
|
||||
severity="danger"
|
||||
[outlined]="true"
|
||||
(click)="onReject()">
|
||||
</p-button>
|
||||
|
||||
<p-button
|
||||
[label]="isLast ? 'Save & Finish' : 'Save & Next'"
|
||||
[icon]="isLast ? 'pi pi-check-circle' : 'pi pi-angle-right'"
|
||||
label="Accept & Save"
|
||||
icon="pi pi-check-circle"
|
||||
iconPos="right"
|
||||
severity="success"
|
||||
[outlined]="true"
|
||||
(click)="onSave(currentProposal!)">
|
||||
</p-button>
|
||||
|
||||
<p-divider layout="vertical"/>
|
||||
|
||||
<p-button
|
||||
[label]="isLast ? 'Finish & Close' : 'Next'"
|
||||
[icon]="isLast ? 'pi pi-check-circle' : 'pi pi-angle-right'"
|
||||
iconPos="right"
|
||||
severity="info"
|
||||
[outlined]="true"
|
||||
(click)="onNext()">
|
||||
</p-button>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="p-4 h-full flex items-center justify-center">
|
||||
<p-progressSpinner styleClass="w-8 h-8" strokeWidth="4"></p-progressSpinner>
|
||||
<p-progressSpinner class="w-8 h-8" strokeWidth="4"></p-progressSpinner>
|
||||
</div>
|
||||
}
|
||||
|
||||
+1
-46
@@ -93,59 +93,22 @@ export class MetadataReviewDialogComponent implements OnInit {
|
||||
return this.proposals[this.currentIndex] ?? null;
|
||||
}
|
||||
|
||||
onReject(): void {
|
||||
const currentProposal = this.currentProposal;
|
||||
if (!currentProposal) return;
|
||||
|
||||
this.metadataTaskService.updateProposalStatus(currentProposal.taskId, currentProposal.proposalId, 'REJECTED').subscribe({
|
||||
next: () => {
|
||||
if (this.isLast) {
|
||||
this.metadataTaskService.deleteTask(currentProposal.taskId).subscribe(() => {
|
||||
this.progressService.clearTask(currentProposal.taskId);
|
||||
this.dialogRef.close();
|
||||
});
|
||||
} else {
|
||||
this.next();
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
if (this.isLast) {
|
||||
this.dialogRef.close();
|
||||
} else {
|
||||
this.next();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onSave(updatedFields: Partial<FetchedProposal>): void {
|
||||
const currentProposal = this.currentProposal;
|
||||
if (!currentProposal) return;
|
||||
|
||||
this.pickerComponent.onSave();
|
||||
|
||||
this.metadataTaskService.updateProposalStatus(currentProposal.taskId, currentProposal.proposalId, 'ACCEPTED').subscribe({
|
||||
next: () => {
|
||||
if (this.isLast) {
|
||||
this.metadataTaskService.deleteTask(currentProposal.taskId).subscribe(() => {
|
||||
this.progressService.clearTask(currentProposal.taskId);
|
||||
this.dialogRef.close();
|
||||
});
|
||||
} else {
|
||||
this.next();
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
if (this.isLast) {
|
||||
this.dialogRef.close();
|
||||
} else {
|
||||
this.next();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
next(): void {
|
||||
onNext(): void {
|
||||
const nextIndex = this.currentIndex + 1;
|
||||
if (nextIndex >= this.proposals.length) {
|
||||
this.dialogRef.close();
|
||||
@@ -155,14 +118,6 @@ export class MetadataReviewDialogComponent implements OnInit {
|
||||
}
|
||||
}
|
||||
|
||||
previous(): void {
|
||||
const prevIndex = this.currentIndex - 1;
|
||||
if (prevIndex >= 0) {
|
||||
this.currentIndex = prevIndex;
|
||||
this.currentIndexSubject.next(prevIndex);
|
||||
}
|
||||
}
|
||||
|
||||
lockAllMetadata(): void {
|
||||
this.pickerComponent?.lockAll();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {BehaviorSubject} from 'rxjs';
|
||||
import {DuplicateFileNotification} from './model/duplicate-file-notification.model';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class DuplicateFileService {
|
||||
private duplicateFiles: DuplicateFileNotification[] = [];
|
||||
private duplicateFilesSubject = new BehaviorSubject<DuplicateFileNotification[]>([]);
|
||||
|
||||
duplicateFiles$ = this.duplicateFilesSubject.asObservable();
|
||||
|
||||
addDuplicateFile(notification: DuplicateFileNotification) {
|
||||
const exists = this.duplicateFiles.some(file =>
|
||||
file.fullPath === notification.fullPath && file.libraryId === notification.libraryId
|
||||
);
|
||||
|
||||
if (!exists) {
|
||||
this.duplicateFiles.unshift(notification);
|
||||
this.duplicateFilesSubject.next([...this.duplicateFiles]);
|
||||
}
|
||||
}
|
||||
|
||||
clearDuplicateFiles() {
|
||||
this.duplicateFiles = [];
|
||||
this.duplicateFilesSubject.next([]);
|
||||
}
|
||||
|
||||
removeDuplicateFile(fullPath: string, libraryId: number) {
|
||||
this.duplicateFiles = this.duplicateFiles.filter(file =>
|
||||
!(file.fullPath === fullPath && file.libraryId === libraryId)
|
||||
);
|
||||
this.duplicateFilesSubject.next([...this.duplicateFiles]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export interface DuplicateFileNotification {
|
||||
libraryId: number;
|
||||
libraryName: string;
|
||||
fileId: number;
|
||||
fileName: string;
|
||||
fullPath: string;
|
||||
timestamp: string;
|
||||
hash: string;
|
||||
}
|
||||
|
||||
@@ -18,8 +18,8 @@ export class ChartConfigService {
|
||||
private readonly defaultCharts: ChartConfig[] = [
|
||||
{id: 'readingStatus', name: 'Reading Status', enabled: true, category: 'small', order: 0},
|
||||
{id: 'bookFormats', name: 'Book Formats', enabled: true, category: 'small', order: 1},
|
||||
{id: 'languageDistribution', name: 'Language Distribution', enabled: true, category: 'small', order: 2},
|
||||
{id: 'bookMetadataScore', name: 'Book Metadata Score', enabled: true, category: 'small', order: 3},
|
||||
{id: 'bookMetadataScore', name: 'Book Metadata Score', enabled: true, category: 'small', order: 2},
|
||||
{id: 'readingHeatmap', name: 'Books Finished per Month', category: 'small', enabled: true, order: 3},
|
||||
{id: 'topAuthors', name: 'Top 25 Authors', enabled: true, category: 'large', order: 4},
|
||||
{id: 'topCategories', name: 'Top 25 Categories', enabled: true, category: 'large', order: 5},
|
||||
{id: 'monthlyReadingPatterns', name: 'Monthly Reading Patterns', enabled: true, category: 'large', order: 6},
|
||||
@@ -33,7 +33,7 @@ export class ChartConfigService {
|
||||
{id: 'readingDNA', name: 'Reading DNA Profile', enabled: true, category: 'large', order: 14},
|
||||
{id: 'readingHabits', name: 'Reading Habits Analysis', enabled: true, category: 'large', order: 15},
|
||||
{id: 'publicationYear', name: 'Publication Year Timeline', enabled: true, category: 'full-width', order: 16},
|
||||
{id: 'finishedBooksTimeline', name: 'Books Finished Timeline', enabled: true, category: 'full-width', order: 17}
|
||||
{id: 'languageDistribution', name: 'Language Distribution', enabled: true, category: 'small', order: 17}
|
||||
];
|
||||
|
||||
private chartsConfigSubject = new BehaviorSubject<ChartConfig[]>(this.loadConfig());
|
||||
|
||||
-248
@@ -1,248 +0,0 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData, ChartType} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
|
||||
interface FinishedBooksStats {
|
||||
yearMonth: string;
|
||||
count: number;
|
||||
year: number;
|
||||
month: number;
|
||||
}
|
||||
|
||||
const CHART_COLORS = {
|
||||
primary: '#EF476F',
|
||||
primaryBackground: 'rgba(239, 71, 111, 0.1)',
|
||||
border: '#ffffff'
|
||||
} as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
borderColor: CHART_COLORS.primary,
|
||||
backgroundColor: CHART_COLORS.primaryBackground,
|
||||
borderWidth: 2,
|
||||
pointBackgroundColor: CHART_COLORS.primary,
|
||||
pointBorderColor: CHART_COLORS.border,
|
||||
pointBorderWidth: 2,
|
||||
pointRadius: 4,
|
||||
pointHoverRadius: 6,
|
||||
fill: true,
|
||||
tension: 0.4
|
||||
} as const;
|
||||
|
||||
type FinishedBooksChartData = ChartData<'line', number[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class FinishedBooksTimelineChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly finishedBooksChartType = 'line' as const;
|
||||
|
||||
public readonly finishedBooksChartOptions: ChartConfiguration['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: true,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
position: 'nearest',
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
return context[0].label; // Already formatted as "Month Year"
|
||||
},
|
||||
label: this.formatTooltipLabel.bind(this)
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: true,
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
size: 10,
|
||||
weight: 'bold'
|
||||
},
|
||||
align: 'top',
|
||||
offset: 8,
|
||||
formatter: (value: number) => value.toString()
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
intersect: false,
|
||||
mode: 'point'
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
maxRotation: 45,
|
||||
callback: function (value, index, values) {
|
||||
const totalLabels = values.length;
|
||||
const skipInterval = totalLabels > 24 ? Math.ceil(totalLabels / 12) : totalLabels > 12 ? 2 : 1;
|
||||
return index % skipInterval === 0 ? this.getLabelForValue(value as number) : '';
|
||||
}
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.1)'},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Month',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
},
|
||||
stepSize: 1
|
||||
},
|
||||
grid: {color: 'rgba(255, 255, 255, 0.05)'},
|
||||
title: {
|
||||
display: true,
|
||||
text: 'Books Finished',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly finishedBooksChartDataSubject = new BehaviorSubject<FinishedBooksChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: 'Books Finished',
|
||||
data: [],
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly finishedBooksChartData$: Observable<FinishedBooksChartData> =
|
||||
this.finishedBooksChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing finished books stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateFinishedBooksStats();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(stats: FinishedBooksStats[]): void {
|
||||
try {
|
||||
const labels = stats.map(s => {
|
||||
const [year, month] = s.yearMonth.split('-');
|
||||
const monthName = new Date(parseInt(year), parseInt(month) - 1).toLocaleString('default', { month: 'short' });
|
||||
return `${monthName} ${year}`;
|
||||
});
|
||||
const dataValues = stats.map(s => s.count);
|
||||
|
||||
this.finishedBooksChartDataSubject.next({
|
||||
labels,
|
||||
datasets: [{
|
||||
label: 'Books Finished',
|
||||
data: dataValues,
|
||||
...CHART_DEFAULTS
|
||||
}]
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating chart data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private calculateFinishedBooksStats(): FinishedBooksStats[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
return this.processFinishedBooksStats(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: any): boolean {
|
||||
return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0;
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processFinishedBooksStats(books: Book[]): FinishedBooksStats[] {
|
||||
const yearMonthMap = new Map<string, number>();
|
||||
|
||||
books.forEach(book => {
|
||||
if (book.dateFinished) {
|
||||
const finishedDate = new Date(book.dateFinished);
|
||||
const yearMonth = `${finishedDate.getFullYear()}-${(finishedDate.getMonth() + 1).toString().padStart(2, '0')}`;
|
||||
yearMonthMap.set(yearMonth, (yearMonthMap.get(yearMonth) || 0) + 1);
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(yearMonthMap.entries())
|
||||
.filter(([yearMonth, count]) => count > 0)
|
||||
.map(([yearMonth, count]) => ({
|
||||
yearMonth,
|
||||
count,
|
||||
year: parseInt(yearMonth.split('-')[0]),
|
||||
month: parseInt(yearMonth.split('-')[1])
|
||||
}))
|
||||
.sort((a, b) => a.yearMonth.localeCompare(b.yearMonth));
|
||||
}
|
||||
|
||||
private formatTooltipLabel(context: any): string {
|
||||
const value = context.parsed.y;
|
||||
return `${value} book${value === 1 ? '' : 's'} finished`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, EMPTY, Observable, Subject} from 'rxjs';
|
||||
import {map, takeUntil, catchError, filter, first, switchMap} from 'rxjs/operators';
|
||||
import {ChartConfiguration, ChartData} from 'chart.js';
|
||||
|
||||
import {LibraryFilterService} from './library-filter.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
|
||||
interface MatrixDataPoint {
|
||||
x: number; // month (0-11)
|
||||
y: number; // year index
|
||||
v: number; // book count
|
||||
}
|
||||
|
||||
interface YearMonthData {
|
||||
year: number;
|
||||
month: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
|
||||
type HeatmapChartData = ChartData<'matrix', MatrixDataPoint[], string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ReadingHeatmapChartService implements OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryFilterService = inject(LibraryFilterService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public readonly heatmapChartType = 'matrix' as const;
|
||||
|
||||
private yearLabels: string[] = [];
|
||||
private maxBookCount = 1;
|
||||
|
||||
public readonly heatmapChartOptions: ChartConfiguration['options'] = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
layout: {
|
||||
padding: {
|
||||
top: 20
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
legend: {display: false},
|
||||
tooltip: {
|
||||
enabled: true,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.9)',
|
||||
titleColor: '#ffffff',
|
||||
bodyColor: '#ffffff',
|
||||
borderColor: '#ffffff',
|
||||
borderWidth: 1,
|
||||
cornerRadius: 6,
|
||||
displayColors: false,
|
||||
padding: 12,
|
||||
titleFont: {size: 14, weight: 'bold'},
|
||||
bodyFont: {size: 13},
|
||||
callbacks: {
|
||||
title: (context) => {
|
||||
const point = context[0].raw as MatrixDataPoint;
|
||||
const year = this.yearLabels[point.y];
|
||||
const month = MONTH_NAMES[point.x];
|
||||
return `${month} ${year}`;
|
||||
},
|
||||
label: (context) => {
|
||||
const point = context.raw as MatrixDataPoint;
|
||||
return `${point.v} book${point.v === 1 ? '' : 's'} read`;
|
||||
}
|
||||
}
|
||||
},
|
||||
datalabels: {
|
||||
display: true,
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 10,
|
||||
weight: 'bold'
|
||||
},
|
||||
formatter: (value: MatrixDataPoint) => value.v > 0 ? value.v.toString() : ''
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
type: 'linear',
|
||||
position: 'bottom',
|
||||
ticks: {
|
||||
stepSize: 1,
|
||||
callback: (value) => MONTH_NAMES[value as number] || '',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {display: false},
|
||||
},
|
||||
y: {
|
||||
type: 'linear',
|
||||
ticks: {
|
||||
stepSize: 1,
|
||||
callback: (value) => this.yearLabels[value as number] || '',
|
||||
color: '#ffffff',
|
||||
font: {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11
|
||||
}
|
||||
},
|
||||
grid: {display: false},
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private readonly heatmapChartDataSubject = new BehaviorSubject<HeatmapChartData>({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: 'Books Read',
|
||||
data: []
|
||||
}]
|
||||
});
|
||||
|
||||
public readonly heatmapChartData$: Observable<HeatmapChartData> =
|
||||
this.heatmapChartDataSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
switchMap(() =>
|
||||
this.libraryFilterService.selectedLibrary$.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
),
|
||||
catchError((error) => {
|
||||
console.error('Error processing reading heatmap stats:', error);
|
||||
return EMPTY;
|
||||
})
|
||||
)
|
||||
.subscribe(() => {
|
||||
const stats = this.calculateHeatmapData();
|
||||
this.updateChartData(stats);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private updateChartData(yearMonthData: YearMonthData[]): void {
|
||||
const currentYear = new Date().getFullYear();
|
||||
const currentMonth = new Date().getMonth();
|
||||
const years = Array.from({length: 10}, (_, i) => currentYear - 9 + i);
|
||||
|
||||
this.yearLabels = years.map(String);
|
||||
this.maxBookCount = Math.max(1, ...yearMonthData.map(d => d.count));
|
||||
|
||||
const heatmapData: MatrixDataPoint[] = [];
|
||||
|
||||
years.forEach((year, yearIndex) => {
|
||||
const maxMonth = year === currentYear ? currentMonth : 11;
|
||||
|
||||
for (let month = 0; month <= maxMonth; month++) {
|
||||
const dataPoint = yearMonthData.find(d => d.year === year && d.month === month + 1);
|
||||
heatmapData.push({
|
||||
x: month,
|
||||
y: yearIndex,
|
||||
v: dataPoint?.count || 0
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (this.heatmapChartOptions?.scales?.['y']) {
|
||||
(this.heatmapChartOptions.scales['y'] as any).max = years.length - 0.5;
|
||||
}
|
||||
|
||||
this.heatmapChartDataSubject.next({
|
||||
labels: [],
|
||||
datasets: [{
|
||||
label: 'Books Read',
|
||||
data: heatmapData,
|
||||
backgroundColor: (context) => {
|
||||
const point = context.raw as MatrixDataPoint;
|
||||
if (!point?.v) return 'rgba(255, 255, 255, 0.05)';
|
||||
|
||||
const intensity = point.v / this.maxBookCount;
|
||||
const alpha = Math.max(0.2, Math.min(1.0, intensity * 0.8 + 0.2));
|
||||
return `rgba(239, 71, 111, ${alpha})`;
|
||||
},
|
||||
borderColor: 'rgba(255, 255, 255, 0.2)',
|
||||
borderWidth: 1,
|
||||
width: ({chart}) => (chart.chartArea?.width || 0) / 12 - 1,
|
||||
height: ({chart}) => (chart.chartArea?.height || 0) / years.length - 1
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
private calculateHeatmapData(): YearMonthData[] {
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedLibraryId = this.libraryFilterService.getCurrentSelectedLibrary();
|
||||
|
||||
if (!this.isValidBookState(currentState)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredBooks = this.filterBooksByLibrary(currentState.books!, selectedLibraryId);
|
||||
return this.processHeatmapData(filteredBooks);
|
||||
}
|
||||
|
||||
private isValidBookState(state: any): boolean {
|
||||
return state?.loaded && state?.books && Array.isArray(state.books) && state.books.length > 0;
|
||||
}
|
||||
|
||||
private filterBooksByLibrary(books: Book[], selectedLibraryId: string | number | null): Book[] {
|
||||
return selectedLibraryId
|
||||
? books.filter(book => book.libraryId === selectedLibraryId)
|
||||
: books;
|
||||
}
|
||||
|
||||
private processHeatmapData(books: Book[]): YearMonthData[] {
|
||||
const yearMonthMap = new Map<string, number>();
|
||||
const currentYear = new Date().getFullYear();
|
||||
const startYear = currentYear - 9;
|
||||
|
||||
books
|
||||
.filter(book => book.dateFinished)
|
||||
.forEach(book => {
|
||||
const finishedDate = new Date(book.dateFinished!);
|
||||
const year = finishedDate.getFullYear();
|
||||
|
||||
if (year >= startYear && year <= currentYear) {
|
||||
const month = finishedDate.getMonth() + 1;
|
||||
const key = `${year}-${month}`;
|
||||
yearMonthMap.set(key, (yearMonthMap.get(key) || 0) + 1);
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(yearMonthMap.entries())
|
||||
.map(([key, count]) => {
|
||||
const [year, month] = key.split('-').map(Number);
|
||||
return {year, month, count};
|
||||
})
|
||||
.sort((a, b) => a.year - b.year || a.month - b.month);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// ...existing code...
|
||||
|
||||
private processFinishedBooksStats(books: Book[]): FinishedBooksStats[] {
|
||||
const yearMonthMap = new Map<string, number>();
|
||||
|
||||
books.forEach(book => {
|
||||
if (book.dateFinished) {
|
||||
const finishedDate = new Date(book.dateFinished);
|
||||
const yearMonth = `${finishedDate.getFullYear()}-${(finishedDate.getMonth() + 1).toString().padStart(2, '0')}`;
|
||||
yearMonthMap.set(yearMonth, (yearMonthMap.get(yearMonth) || 0) + 1);
|
||||
}
|
||||
});
|
||||
|
||||
// Get the range of months
|
||||
const monthsWithData = Array.from(yearMonthMap.keys()).sort();
|
||||
|
||||
if (monthsWithData.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Fill in all missing months between first and last data points
|
||||
const startDate = this.parseYearMonth(monthsWithData[0]);
|
||||
const endDate = this.parseYearMonth(monthsWithData[monthsWithData.length - 1]);
|
||||
|
||||
const completeStats: FinishedBooksStats[] = [];
|
||||
let currentDate = new Date(startDate.year, startDate.month - 1, 1);
|
||||
const endDateObj = new Date(endDate.year, endDate.month - 1, 1);
|
||||
|
||||
while (currentDate <= endDateObj) {
|
||||
const year = currentDate.getFullYear();
|
||||
const month = currentDate.getMonth() + 1;
|
||||
const yearMonth = `${year}-${month.toString().padStart(2, '0')}`;
|
||||
|
||||
completeStats.push({
|
||||
yearMonth,
|
||||
count: yearMonthMap.get(yearMonth) || 0,
|
||||
year,
|
||||
month
|
||||
});
|
||||
|
||||
// Move to next month
|
||||
currentDate.setMonth(currentDate.getMonth() + 1);
|
||||
}
|
||||
|
||||
return completeStats.sort((a, b) => a.yearMonth.localeCompare(b.yearMonth));
|
||||
}
|
||||
|
||||
private parseYearMonth(yearMonthStr: string): { year: number, month: number } {
|
||||
const [year, month] = yearMonthStr.split('-').map(Number);
|
||||
return { year, month };
|
||||
}
|
||||
|
||||
// ...existing code...
|
||||
|
||||
@@ -4,25 +4,28 @@
|
||||
<div class="library-filter">
|
||||
<div class="select-row">
|
||||
<label for="library-dropdown">Library Statistics</label>
|
||||
<p-select
|
||||
id="library-dropdown"
|
||||
[options]="libraryOptions"
|
||||
[(ngModel)]="selectedLibrary"
|
||||
optionLabel="name"
|
||||
size="small"
|
||||
placeholder="Select a library"
|
||||
(onChange)="onLibraryChange()"
|
||||
appendTo="body"
|
||||
[style]="{'min-width': '200px'}"
|
||||
class="library-dropdown">
|
||||
</p-select>
|
||||
<div class="flex w-full gap-2 align-items-center">
|
||||
<p-select
|
||||
fluid
|
||||
id="library-dropdown"
|
||||
[options]="libraryOptions"
|
||||
[(ngModel)]="selectedLibrary"
|
||||
optionLabel="name"
|
||||
size="small"
|
||||
placeholder="Select a library"
|
||||
(onChange)="onLibraryChange()"
|
||||
appendTo="body"
|
||||
[style]="{'min-width': '200px'}"
|
||||
class="library-dropdown">
|
||||
</p-select>
|
||||
|
||||
<p-button
|
||||
outlined
|
||||
size="small"
|
||||
(onClick)="toggleConfigPanel()"
|
||||
icon="pi pi-cog">
|
||||
</p-button>
|
||||
<p-button
|
||||
outlined
|
||||
size="small"
|
||||
(onClick)="toggleConfigPanel()"
|
||||
icon="pi pi-cog">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="library-totals" role="status" aria-live="polite">
|
||||
@@ -184,7 +187,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('bookFormats') {
|
||||
<h3>Book Formats</h3>
|
||||
<div class="chart-wrapper book-type-chart">
|
||||
@@ -195,7 +197,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('languageDistribution') {
|
||||
<h3>Language Distribution</h3>
|
||||
<div class="chart-wrapper language-chart">
|
||||
@@ -206,7 +207,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('bookMetadataScore') {
|
||||
<h3>Book Metadata Score</h3>
|
||||
<div class="chart-wrapper quality-chart">
|
||||
@@ -217,7 +217,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('topAuthors') {
|
||||
<h3>Top 25 Authors (with Reading Breakdown)</h3>
|
||||
<div class="chart-wrapper author-chart">
|
||||
@@ -228,7 +227,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('topCategories') {
|
||||
<h3>Top 25 Categories (with Reading Breakdown)</h3>
|
||||
<div class="chart-wrapper completion-chart">
|
||||
@@ -239,7 +237,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('topBooksBySize') {
|
||||
<h3>Top 20 Largest Books by File Size</h3>
|
||||
<div class="chart-wrapper book-size-chart">
|
||||
@@ -250,7 +247,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('monthlyReadingPatterns') {
|
||||
<h3>Monthly Reading Patterns</h3>
|
||||
<div class="chart-wrapper monthly-patterns-chart">
|
||||
@@ -261,7 +257,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('readingProgress') {
|
||||
<h3>Reading Progress</h3>
|
||||
<div class="chart-wrapper progress-chart">
|
||||
@@ -272,7 +267,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('externalRating') {
|
||||
<h3>External Rating Distribution</h3>
|
||||
<div class="chart-wrapper rating-chart">
|
||||
@@ -283,7 +277,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('personalRating') {
|
||||
<h3>Personal Rating Distribution</h3>
|
||||
<div class="chart-wrapper personal-rating-chart">
|
||||
@@ -294,7 +287,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('pageCount') {
|
||||
<h3>Page Count Distribution</h3>
|
||||
<div class="chart-wrapper page-count-chart">
|
||||
@@ -305,7 +297,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('readingVelocityTimeline') {
|
||||
<h3>Reading Velocity Timeline</h3>
|
||||
<div class="chart-wrapper velocity-timeline-chart">
|
||||
@@ -316,7 +307,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('topSeries') {
|
||||
<h3>Top 20 Series by Book Count</h3>
|
||||
<div class="chart-wrapper top-series-chart">
|
||||
@@ -327,7 +317,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('publicationYear') {
|
||||
<h3>Publication Year Timeline</h3>
|
||||
<div class="chart-wrapper year-chart">
|
||||
@@ -339,19 +328,6 @@
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('finishedBooksTimeline') {
|
||||
<h3>Books Finished Timeline (Per Month)</h3>
|
||||
<div class="chart-wrapper finished-books-timeline-chart">
|
||||
<canvas baseChart
|
||||
[data]="(finishedBooksTimelineChartService.finishedBooksChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="finishedBooksTimelineChartService.finishedBooksChartOptions"
|
||||
[type]="finishedBooksTimelineChartService.finishedBooksChartType"
|
||||
[plugins]="[ChartDataLabels]">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('readingDNA') {
|
||||
<h3>Your Reading DNA Profile</h3>
|
||||
<div class="chart-description">
|
||||
@@ -384,7 +360,6 @@
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@case ('readingHabits') {
|
||||
<h3>Reading Habits Analysis</h3>
|
||||
<div class="chart-description">
|
||||
@@ -417,6 +392,16 @@
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@case ('readingHeatmap') {
|
||||
<h3>Books Finished per Month</h3>
|
||||
<div class="chart-wrapper reading-heatmap-chart">
|
||||
<canvas baseChart
|
||||
[data]="(readingHeatmapChartService.heatmapChartData$ | async) ?? {labels: [], datasets: []}"
|
||||
[options]="readingHeatmapChartService.heatmapChartOptions"
|
||||
[type]="readingHeatmapChartService.heatmapChartType">
|
||||
</canvas>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -530,6 +530,10 @@
|
||||
height: 400px;
|
||||
}
|
||||
|
||||
&.reading-heatmap-chart {
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
&.reading-profile-radar-chart,
|
||||
&.reading-dna-chart,
|
||||
&.reading-habits-chart {
|
||||
@@ -889,7 +893,11 @@
|
||||
height: 280px;
|
||||
}
|
||||
|
||||
&.reading-profile-radar-chart,
|
||||
&.reading-heatmap-chart {
|
||||
height: 250px;
|
||||
}
|
||||
|
||||
.reading-profile-radar-chart,
|
||||
&.reading-dna-chart,
|
||||
&.reading-habits-chart {
|
||||
height: 350px;
|
||||
@@ -974,6 +982,10 @@
|
||||
height: 250px;
|
||||
}
|
||||
|
||||
&.reading-heatmap-chart {
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
.reading-profile-radar-chart,
|
||||
&.reading-dna-chart,
|
||||
&.reading-habits-chart {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {Component, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
|
||||
import {BaseChartDirective} from 'ng2-charts';
|
||||
import {Chart, registerables, Tooltip} from 'chart.js';
|
||||
import 'chartjs-chart-matrix';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {catchError, map, of, startWith, Subject, takeUntil} from 'rxjs';
|
||||
@@ -23,12 +24,13 @@ import {BookSizeChartService} from './charts-service/book-size-chart.service';
|
||||
import {ReadingVelocityTimelineChartService} from './charts-service/reading-velocity-timeline-chart.service';
|
||||
import {MonthlyReadingPatternsChartService} from './charts-service/monthly-reading-patterns-chart.service';
|
||||
import {TopSeriesChartService} from './charts-service/top-series-chart.service';
|
||||
import {FinishedBooksTimelineChartService} from './charts-service/finished-books-timeline-chart.service';
|
||||
import ChartDataLabels from 'chartjs-plugin-datalabels';
|
||||
import {ReadingDNAChartService} from './charts-service/reading-dna-chart.service';
|
||||
import {ReadingHabitsChartService} from './charts-service/reading-habits-chart.service';
|
||||
import {ChartConfigService, ChartConfig} from './charts-service/chart-config.service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {ReadingHeatmapChartService} from './charts-service/reading-heatmap-chart.service';
|
||||
import {MatrixController, MatrixElement} from 'chartjs-chart-matrix';
|
||||
|
||||
@Component({
|
||||
selector: 'app-stats-component',
|
||||
@@ -65,10 +67,10 @@ export class StatsComponent implements OnInit, OnDestroy {
|
||||
protected readonly readingVelocityTimelineChartService = inject(ReadingVelocityTimelineChartService);
|
||||
protected readonly monthlyReadingPatternsChartService = inject(MonthlyReadingPatternsChartService);
|
||||
protected readonly topSeriesChartService = inject(TopSeriesChartService);
|
||||
protected readonly finishedBooksTimelineChartService = inject(FinishedBooksTimelineChartService);
|
||||
protected readonly readingDNAChartService = inject(ReadingDNAChartService);
|
||||
protected readonly readingHabitsChartService = inject(ReadingHabitsChartService);
|
||||
protected readonly chartConfigService = inject(ChartConfigService);
|
||||
protected readonly readingHeatmapChartService = inject(ReadingHeatmapChartService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
public isLoading = true;
|
||||
@@ -94,7 +96,8 @@ export class StatsComponent implements OnInit, OnDestroy {
|
||||
public readonly totalSize$ = this.librariesSummaryService.getFormattedSize().pipe(catchError(() => of('0 KB')));
|
||||
|
||||
ngOnInit(): void {
|
||||
Chart.register(...registerables, Tooltip, ChartDataLabels);
|
||||
Chart.register(...registerables, Tooltip, ChartDataLabels, MatrixController, MatrixElement);
|
||||
// Register matrix chart - it's automatically registered when imported
|
||||
Chart.defaults.plugins.legend.labels.font = {
|
||||
family: "'Inter', sans-serif",
|
||||
size: 11.5,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
apiVersion: v2
|
||||
name: booklore
|
||||
description: A Helm chart for [Booklore](https://github.com/booklore-app/booklore)
|
||||
|
||||
# A chart can be either an 'application' or a 'library' chart.
|
||||
#
|
||||
# Application charts are a collection of templates that can be packaged into versioned archives
|
||||
# to be deployed.
|
||||
#
|
||||
# Library charts provide useful utilities or functions for the chart developer. They're included as
|
||||
# a dependency of application charts to inject those utilities and functions into the rendering
|
||||
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
|
||||
type: application
|
||||
|
||||
# This is the chart version. This version number should be incremented each time you make changes
|
||||
# to the chart and its templates, including the app version.
|
||||
# Versions are expected to follow Semantic Versioning (https://semver.org/)
|
||||
version: 0.1.0
|
||||
|
||||
# This is the version number of the application being deployed. This version number should be
|
||||
# incremented each time you make changes to the application. Versions are not expected to
|
||||
# follow Semantic Versioning. They should reflect the version the application is using.
|
||||
# It is recommended to use it with quotes.
|
||||
appVersion: "0.38.2"
|
||||
|
||||
dependencies:
|
||||
- name: mariadb
|
||||
version: 22.0.*
|
||||
repository: oci://registry-1.docker.io/bitnamicharts
|
||||
@@ -0,0 +1,62 @@
|
||||
{{/*
|
||||
Expand the name of the chart.
|
||||
*/}}
|
||||
{{- define "booklore.name" -}}
|
||||
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Create a default fully qualified app name.
|
||||
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
|
||||
If release name contains chart name it will be used as a full name.
|
||||
*/}}
|
||||
{{- define "booklore.fullname" -}}
|
||||
{{- if .Values.fullnameOverride }}
|
||||
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
|
||||
{{- else }}
|
||||
{{- $name := default .Chart.Name .Values.nameOverride }}
|
||||
{{- if contains $name .Release.Name }}
|
||||
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
|
||||
{{- else }}
|
||||
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Create chart name and version as used by the chart label.
|
||||
*/}}
|
||||
{{- define "booklore.chart" -}}
|
||||
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Common labels
|
||||
*/}}
|
||||
{{- define "booklore.labels" -}}
|
||||
helm.sh/chart: {{ include "booklore.chart" . }}
|
||||
{{ include "booklore.selectorLabels" . }}
|
||||
{{- if .Chart.AppVersion }}
|
||||
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
|
||||
{{- end }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Selector labels
|
||||
*/}}
|
||||
{{- define "booklore.selectorLabels" -}}
|
||||
app.kubernetes.io/name: {{ include "booklore.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Create the name of the service account to use
|
||||
*/}}
|
||||
{{- define "booklore.serviceAccountName" -}}
|
||||
{{- if .Values.serviceAccount.create }}
|
||||
{{- default (include "booklore.fullname" .) .Values.serviceAccount.name }}
|
||||
{{- else }}
|
||||
{{- default "default" .Values.serviceAccount.name }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,141 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "booklore.fullname" . }}
|
||||
labels:
|
||||
{{- include "booklore.labels" . | nindent 4 }}
|
||||
spec:
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "booklore.selectorLabels" . | nindent 6 }}
|
||||
template:
|
||||
metadata:
|
||||
{{- with .Values.podAnnotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
labels:
|
||||
{{- include "booklore.labels" . | nindent 8 }}
|
||||
{{- with .Values.podLabels }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
{{- with .Values.imagePullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
serviceAccountName: {{ include "booklore.serviceAccountName" . }}
|
||||
{{- with .Values.podSecurityContext }}
|
||||
securityContext:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
initContainers:
|
||||
- name: wait-for-database
|
||||
image: busybox:1.36
|
||||
command:
|
||||
- /bin/sh
|
||||
- -c
|
||||
- |
|
||||
echo "Waiting for database on port {{ .Values.mariadb.primary.service.ports.mysql }}..."
|
||||
until nc -z -v -w5 {{ .Release.Name }}-mariadb {{ .Values.mariadb.primary.service.ports.mysql }}; do
|
||||
echo "Waiting for database..."
|
||||
sleep 2
|
||||
done
|
||||
echo "Database is available!"
|
||||
resources:
|
||||
requests:
|
||||
cpu: 10m
|
||||
memory: 16Mi
|
||||
limits:
|
||||
cpu: 50m
|
||||
memory: 32Mi
|
||||
containers:
|
||||
- name: {{ .Chart.Name }}
|
||||
{{- with .Values.securityContext }}
|
||||
securityContext:
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: {{ .Values.service.port }}
|
||||
#protocol: TCP
|
||||
env:
|
||||
- name: BOOKLORE_PORT
|
||||
value: "6060"
|
||||
- name: DATABASE_URL
|
||||
value: jdbc:mariadb://{{ .Release.Name }}-mariadb:{{ .Values.mariadb.primary.service.ports.mysql }}/{{ .Values.mariadb.auth.database }}
|
||||
- name: DATABASE_USERNAME
|
||||
value: {{ .Values.mariadb.auth.username }}
|
||||
- name: DATABASE_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
{{- if .Values.mariadb.auth.existingSecret }}
|
||||
name: {{ .Values.mariadb.auth.existingSecret }}
|
||||
{{- else }}
|
||||
name: {{ .Release.Name }}-mariadb
|
||||
{{- end }}
|
||||
key: mariadb-password
|
||||
{{- with .Values.livenessProbe }}
|
||||
livenessProbe:
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- with .Values.readinessProbe }}
|
||||
readinessProbe:
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- with .Values.resources }}
|
||||
resources:
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- if (or .Values.persistence.dataVolume.enabled .Values.persistence.booksVolume.enabled .Values.extraVolumeMounts) }}
|
||||
volumeMounts:
|
||||
{{- if .Values.persistence.dataVolume.enabled }}
|
||||
- name: data
|
||||
mountPath: /app/data
|
||||
{{- end }}
|
||||
{{- if .Values.persistence.booksVolume.enabled }}
|
||||
- name: books
|
||||
mountPath: /books
|
||||
{{- end }}
|
||||
{{- with .Values.extraVolumeMounts }}
|
||||
{{- toYaml . | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if (or .Values.persistence.dataVolume.enabled .Values.persistence.booksVolume.enabled .Values.extraVolumes) }}
|
||||
volumes:
|
||||
{{- if .Values.persistence.dataVolume.enabled }}
|
||||
- name: data
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ if .Values.persistence.dataVolume.existingClaim }}
|
||||
{{- .Values.persistence.dataVolume.existingClaim }}
|
||||
{{ else }}
|
||||
{{- include "booklore.fullname" . }}-data
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.persistence.booksVolume.enabled }}
|
||||
- name: books
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ if .Values.persistence.booksVolume.existingClaim }}
|
||||
{{- .Values.persistence.booksVolume.existingClaim }}
|
||||
{{ else }}
|
||||
{{- include "booklore.fullname" . }}-books
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- with .Values.extraVolumes }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
{{- with .Values.nodeSelector }}
|
||||
nodeSelector:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.affinity }}
|
||||
affinity:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- with .Values.tolerations }}
|
||||
tolerations:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,43 @@
|
||||
{{- if .Values.ingress.enabled -}}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: {{ include "booklore.fullname" . }}
|
||||
labels:
|
||||
{{- include "booklore.labels" . | nindent 4 }}
|
||||
{{- with .Values.ingress.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
{{- with .Values.ingress.className }}
|
||||
ingressClassName: {{ . }}
|
||||
{{- end }}
|
||||
{{- if .Values.ingress.tls }}
|
||||
tls:
|
||||
{{- range .Values.ingress.tls }}
|
||||
- hosts:
|
||||
{{- range .hosts }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
secretName: {{ .secretName }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
rules:
|
||||
{{- range .Values.ingress.hosts }}
|
||||
- host: {{ .host | quote }}
|
||||
http:
|
||||
paths:
|
||||
{{- range .paths }}
|
||||
- path: {{ .path }}
|
||||
{{- with .pathType }}
|
||||
pathType: {{ . }}
|
||||
{{- end }}
|
||||
backend:
|
||||
service:
|
||||
name: {{ include "booklore.fullname" $ }}
|
||||
port:
|
||||
number: {{ $.Values.service.port }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,33 @@
|
||||
{{- if (and .Values.persistence.dataVolume.enabled (not .Values.persistence.dataVolume.existingClaim)) }}
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
annotations:
|
||||
helm.sh/resource-policy: keep
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ include "booklore.fullname" . }}
|
||||
name: {{ include "booklore.fullname" . }}-data
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: {{ .Values.persistence.dataVolume.size }}
|
||||
{{- end }}
|
||||
---
|
||||
{{- if (and .Values.persistence.booksVolume.enabled (not .Values.persistence.booksVolume.existingClaim)) }}
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
annotations:
|
||||
helm.sh/resource-policy: keep
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ include "booklore.fullname" . }}
|
||||
name: {{ include "booklore.fullname" . }}-books
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: {{ .Values.persistence.booksVolume.size }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,15 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "booklore.fullname" . }}
|
||||
labels:
|
||||
{{- include "booklore.labels" . | nindent 4 }}
|
||||
spec:
|
||||
type: {{ .Values.service.type }}
|
||||
ports:
|
||||
- port: {{ .Values.service.port }}
|
||||
targetPort: http
|
||||
protocol: TCP
|
||||
name: http
|
||||
selector:
|
||||
{{- include "booklore.selectorLabels" . | nindent 4 }}
|
||||
@@ -0,0 +1,13 @@
|
||||
{{- if .Values.serviceAccount.create -}}
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: {{ include "booklore.serviceAccountName" . }}
|
||||
labels:
|
||||
{{- include "booklore.labels" . | nindent 4 }}
|
||||
{{- with .Values.serviceAccount.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
automountServiceAccountToken: {{ .Values.serviceAccount.automount }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,121 @@
|
||||
# Default values for booklore.
|
||||
# This is a YAML-formatted file.
|
||||
# Declare variables to be passed into your templates.
|
||||
|
||||
mariadb:
|
||||
enabled: true
|
||||
image:
|
||||
tag: 11.8.3
|
||||
auth:
|
||||
database: booklore
|
||||
username: booklore-user
|
||||
|
||||
# This sets the container image more information can be found here: https://kubernetes.io/docs/concepts/containers/images/
|
||||
image:
|
||||
repository: booklore/booklore
|
||||
# This sets the pull policy for images.
|
||||
pullPolicy: IfNotPresent
|
||||
# Overrides the image tag whose default is the chart appVersion.
|
||||
tag: latest
|
||||
|
||||
# This is for the secrets for pulling an image from a private repository more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
|
||||
imagePullSecrets: []
|
||||
# This is to override the chart name.
|
||||
nameOverride: ""
|
||||
fullnameOverride: ""
|
||||
|
||||
# This section builds out the service account more information can be found here: https://kubernetes.io/docs/concepts/security/service-accounts/
|
||||
serviceAccount:
|
||||
# Specifies whether a service account should be created
|
||||
create: true
|
||||
# Automatically mount a ServiceAccount's API credentials?
|
||||
automount: true
|
||||
# Annotations to add to the service account
|
||||
annotations: {}
|
||||
# The name of the service account to use.
|
||||
# If not set and create is true, a name is generated using the fullname template
|
||||
name: ""
|
||||
|
||||
# This is for setting Kubernetes Annotations to a Pod.
|
||||
# For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/
|
||||
podAnnotations: {}
|
||||
# This is for setting Kubernetes Labels to a Pod.
|
||||
# For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/
|
||||
podLabels: {}
|
||||
|
||||
podSecurityContext: {}
|
||||
# fsGroup: 2000
|
||||
|
||||
securityContext: {}
|
||||
# capabilities:
|
||||
# drop:
|
||||
# - ALL
|
||||
# readOnlyRootFilesystem: true
|
||||
# runAsNonRoot: true
|
||||
# runAsUser: 1000
|
||||
|
||||
# This is for setting up a service more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/
|
||||
service:
|
||||
# This sets the service type more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
|
||||
type: ClusterIP
|
||||
# This sets the ports more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#field-spec-ports
|
||||
port: 6060
|
||||
|
||||
# This block is for setting up the ingress for more information can be found here: https://kubernetes.io/docs/concepts/services-networking/ingress/
|
||||
ingress:
|
||||
enabled: false
|
||||
className: ""
|
||||
annotations: {}
|
||||
# kubernetes.io/ingress.class: nginx
|
||||
# kubernetes.io/tls-acme: "true"
|
||||
hosts:
|
||||
- host: chart-example.local
|
||||
paths:
|
||||
- path: /
|
||||
pathType: ImplementationSpecific
|
||||
tls: []
|
||||
# - secretName: chart-example-tls
|
||||
# hosts:
|
||||
# - chart-example.local
|
||||
|
||||
resources: {}
|
||||
# We usually recommend not to specify default resources and to leave this as a conscious
|
||||
# choice for the user. This also increases chances charts run on environments with little
|
||||
# resources, such as Minikube. If you do want to specify resources, uncomment the following
|
||||
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
|
||||
# limits:
|
||||
# cpu: 100m
|
||||
# memory: 128Mi
|
||||
# requests:
|
||||
# cpu: 100m
|
||||
# memory: 128Mi
|
||||
|
||||
# # This is to setup the liveness and readiness probes more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
|
||||
livenessProbe:
|
||||
tcpSocket:
|
||||
port: http
|
||||
readinessProbe:
|
||||
tcpSocket:
|
||||
port: http
|
||||
|
||||
# If you want to bring your own persistence (such as a hostPath),
|
||||
# disable these and do so in extraVolumes/extraVolumeMounts
|
||||
persistence:
|
||||
dataVolume:
|
||||
enabled: true
|
||||
size: 100Mi
|
||||
existingClaim: ""
|
||||
booksVolume:
|
||||
enabled: true
|
||||
size: 10Gi
|
||||
existingClaim: ""
|
||||
|
||||
extraVolumes: []
|
||||
|
||||
extraVolumeMounts: []
|
||||
|
||||
nodeSelector: {}
|
||||
|
||||
tolerations: []
|
||||
|
||||
affinity: {}
|
||||
@@ -1,32 +0,0 @@
|
||||
# Docker Image Version
|
||||
# This determines which version of the Booklore image to pull from GitHub Container Registry (GHCR).
|
||||
# Use "latest" for the most recent version or specify a tag like "v1.0.0".
|
||||
BOOKLORE_IMAGE_TAG=latest
|
||||
|
||||
# User and Timezone Settings
|
||||
# PUID and PGID define the user/group running the container.
|
||||
# Avoid using "user" property because system won't work with it.
|
||||
# TZ sets the timezone for correct time-related operations.
|
||||
PUID=1000 # Default user ID (Check with `id -u` on Linux/Mac)
|
||||
PGID=1000 # Default group ID (Check with `id -g` on Linux/Mac)
|
||||
TZ=Etc/UTC # Change this to your timezone (e.g., America/New_York, Asia/Kolkata)
|
||||
|
||||
# Database Credentials (Replace with a secure password)
|
||||
# This password is used by MariaDB. Make sure to keep it secure.
|
||||
MYSQL_ROOT_PASSWORD=super_secure_password
|
||||
MYSQL_DATABASE=booklore
|
||||
MYSQL_USER=booklore
|
||||
MYSQL_PASSWORD=your_secure_password
|
||||
|
||||
# Paths for Docker Volumes (Update these paths as per your system)
|
||||
# These paths store persistent data for Booklore and MariaDB.
|
||||
# Replace "/path/to/..." with actual directories on your system.
|
||||
BOOKLORE_DATA_PATH=/path/to/booklore/data # Example: /home/user/booklore/data (Stores app-related data)
|
||||
BOOKLORE_BOOKS_PATH=/path/to/booklore/books # Example: /home/user/booklore/books (Stores book files)
|
||||
MARIADB_CONFIG_PATH=/path/to/mariadb/config # Example: /home/user/booklore/mariadb/config (Stores database config)
|
||||
|
||||
# How to find your correct paths?
|
||||
# 1. Choose a location where you want to store persistent data.
|
||||
# 2. Create the required folders if they don’t exist.
|
||||
# 3. Use `pwd` in your terminal inside those directories to get the full path.
|
||||
# 4. Replace `/path/to/...` above with your actual paths.
|
||||
@@ -1,33 +1,48 @@
|
||||
name: booklore
|
||||
services:
|
||||
booklore:
|
||||
image: booklore/booklore:${BOOKLORE_IMAGE_TAG}
|
||||
container_name: booklore_server
|
||||
env_file:
|
||||
- .env
|
||||
# Official Docker Hub image:
|
||||
image: booklore/booklore:latest
|
||||
# Or the GHCR image:
|
||||
# image: ghcr.io/booklore-app/booklore:latest
|
||||
container_name: booklore
|
||||
environment:
|
||||
- DATABASE_URL=jdbc:mariadb://mariadb:3306/${MYSQL_DATABASE}
|
||||
- DATABASE_USERNAME=${MYSQL_USER}
|
||||
- DATABASE_PASSWORD=${MYSQL_PASSWORD}
|
||||
- USER_ID=0 # Modify this if the volume's ownership is not root
|
||||
- GROUP_ID=0 # Modify this if the volume's ownership is not root
|
||||
- TZ=Etc/UTC
|
||||
- DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore # Only modify this if you're familiar with JDBC and your database setup
|
||||
- DATABASE_USERNAME=booklore # Must match MYSQL_USER defined in the mariadb container
|
||||
- DATABASE_PASSWORD=your_secure_password # Use a strong password; must match MYSQL_PASSWORD defined in the mariadb container
|
||||
- BOOKLORE_PORT=6060 # Port BookLore listens on inside the container; must match container port below
|
||||
- SWAGGER_ENABLED=false # Enable or disable Swagger UI (API docs). Set to 'true' to allow access; 'false' to block access (recommended for production).
|
||||
depends_on:
|
||||
mariadb:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "6060:6060"
|
||||
- "6060:6060" # HostPort:ContainerPort → Keep both numbers the same, and also ensure the container port matches BOOKLORE_PORT, no exceptions.
|
||||
# All three (host port, container port, BOOKLORE_PORT) must be identical for BookLore to function properly.
|
||||
# Example: To expose on host port 7070, set BOOKLORE_PORT=7070 and use "7070:7070".
|
||||
volumes:
|
||||
- ${BOOKLORE_DATA_PATH}:/app/data
|
||||
- ${BOOKLORE_BOOKS_PATH}:/books
|
||||
- ./data:/app/data # Application data (settings, metadata, cache, etc.). Persist this folder to retain your library state across container restarts.
|
||||
- ./books:/books # Primary book library folder. Mount your collection here so BookLore can access and organize your books.
|
||||
- ./bookdrop:/bookdrop # BookDrop folder. Files placed here are automatically detected and prepared for import.
|
||||
restart: unless-stopped
|
||||
|
||||
mariadb:
|
||||
image: lscr.io/linuxserver/mariadb:11.4
|
||||
container_name: booklore_mariadb
|
||||
env_file:
|
||||
- .env
|
||||
image: lscr.io/linuxserver/mariadb:11.4.5
|
||||
container_name: mariadb
|
||||
environment:
|
||||
- PUID=1000
|
||||
- PGID=1000
|
||||
- TZ=Etc/UTC
|
||||
- MYSQL_ROOT_PASSWORD=super_secure_password # Use a strong password for the database's root user, should be different from MYSQL_PASSWORD
|
||||
- MYSQL_DATABASE=booklore
|
||||
- MYSQL_USER=booklore # Must match DATABASE_USERNAME defined in the booklore container
|
||||
- MYSQL_PASSWORD=your_secure_password # Use a strong password; must match DATABASE_PASSWORD defined in the booklore container
|
||||
volumes:
|
||||
- ${MARIADB_CONFIG_PATH}:/config
|
||||
- ./config:/config
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "mariadb-admin", "ping", "-h", "localhost"]
|
||||
interval: 10s
|
||||
test: [ "CMD", "mariadb-admin", "ping", "-h", "localhost" ]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
retries: 10
|
||||
Reference in New Issue
Block a user