From 25ee5103797f077a5badf5385ee1ead8644f5e48 Mon Sep 17 00:00:00 2001
From: "aditya.chandel" <>
Date: Fri, 23 May 2025 22:32:02 -0600
Subject: [PATCH 01/10] Refine handling of file create/delete events in library
watcher
---
.../booklore/model/entity/BookEntity.java | 9 ++
.../service/LibraryProcessingService.java | 145 ++++++++++++------
.../service/monitoring/MonitoringService.java | 5 +-
.../service/monitoring/MonitoringTask.java | 2 +-
.../booklore/util/FileUtils.java | 5 +-
5 files changed, 117 insertions(+), 49 deletions(-)
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java
index 6d3b13fb8..8870dcd9c 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java
@@ -6,6 +6,8 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import jakarta.persistence.*;
import lombok.*;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
@@ -60,4 +62,11 @@ public class BookEntity {
@Column(name = "similar_books_json", columnDefinition = "TEXT")
private List similarBooksJson;
+ public Path getFullFilePath() {
+ if (libraryPath == null || libraryPath.getPath() == null || fileSubPath == null || fileName == null) {
+ throw new IllegalStateException("Cannot construct file path: missing library path, file subpath, or file name");
+ }
+
+ return Paths.get(libraryPath.getPath(), fileSubPath, fileName);
+ }
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java
index 660e668e0..3fea7d668 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java
@@ -18,12 +18,15 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionTemplate;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.Set;
+import java.util.concurrent.*;
import java.util.stream.Collectors;
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
@@ -39,6 +42,11 @@ public class LibraryProcessingService {
private final EpubProcessor epubProcessor;
private final BookRepository bookRepository;
private final EntityManager entityManager;
+ private final TransactionTemplate transactionTemplate;
+
+ private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
+ private final Map> deletionTasks = new ConcurrentHashMap<>();
+ private static final int DELETE_DEBOUNCE_SECONDS = 3;
@Transactional
public void processLibrary(long libraryId) throws IOException {
@@ -51,18 +59,34 @@ public class LibraryProcessingService {
@Transactional
public void processFile(WatchEvent.Kind> eventKind, long libraryId, String libraryPath, String filePath) {
- LibraryEntity libraryEntity = libraryRepository.findById(libraryId)
- .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
-
+ LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
Path path = Paths.get(filePath);
String fileName = path.getFileName().toString();
-
if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {
+ ScheduledFuture> scheduledDeletion = deletionTasks.remove(filePath);
+ if (scheduledDeletion != null) {
+ scheduledDeletion.cancel(false);
+ log.debug("Cancelled scheduled deletion for file: {}", filePath);
+ }
+
notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath));
LibraryPathEntity libraryPathEntity = getLibraryPathEntityForFile(libraryEntity, libraryPath);
libraryPathEntity = entityManager.merge(libraryPathEntity);
+ LibraryPathEntity finalLibraryPathEntity = libraryPathEntity;
+ bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
+ .ifPresent(existingBook -> {
+ Path newFullPath = path;
+ Path oldFullPath = existingBook.getFullFilePath();
+ if (!newFullPath.equals(oldFullPath)) {
+ existingBook.setLibraryPath(finalLibraryPathEntity);
+ existingBook.setFileSubPath(FileUtils.getRelativeSubPath(finalLibraryPathEntity.getPath(), newFullPath));
+ bookRepository.save(existingBook);
+ log.debug("Updated path for moved book: {}", fileName);
+ }
+ });
+
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
@@ -75,11 +99,33 @@ public class LibraryProcessingService {
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath));
} else if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {
- bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
- .ifPresent(bookEntity -> {
- deleteRemovedBooks(List.of(bookEntity));
- notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(bookEntity.getId()));
- });
+ ScheduledFuture> scheduledDeletion = deletionTasks.putIfAbsent(filePath, scheduler.schedule(() -> {
+ try {
+ boolean fileStillExists = libraryEntity.getLibraryPaths().stream()
+ .anyMatch(lp -> {
+ Path fullPath = Path.of(lp.getPath()).resolve(fileName);
+ return Files.exists(fullPath);
+ });
+ if (!fileStillExists) {
+ transactionTemplate.executeWithoutResult(status -> {
+ bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
+ .ifPresent(bookEntity -> {
+ deleteRemovedBooks(List.of(bookEntity.getId()));
+ notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(bookEntity.getId()));
+ log.debug("Deleted book after debounce: {}", fileName);
+ });
+ });
+ } else {
+ log.debug("File '{}' detected to still exist after debounce, skipping delete.", fileName);
+ }
+ } catch (Exception e) {
+ log.error("Error during delayed deletion of file: {}", filePath, e);
+ } finally {
+ deletionTasks.remove(filePath);
+ }
+ }, DELETE_DEBOUNCE_SECONDS, TimeUnit.SECONDS));
+
+ // If scheduledDeletion != null, it means a task was already scheduled, so we skip scheduling again
}
}
@@ -103,23 +149,58 @@ public class LibraryProcessingService {
public void rescanLibrary(long libraryId) throws IOException {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName()));
- processLibraryFiles(getUnProcessedFiles(libraryEntity));
- deleteRemovedBooks(getRemovedBooks(libraryEntity));
+ detectMovedBooksAndUpdatePaths(libraryEntity);
+ deleteRemovedBooks(detectDeletedBookIds(libraryEntity));
+ processLibraryFiles(detectNewBookPaths(libraryEntity));
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
}
- @Transactional
- protected void deleteRemovedBooks(List removedBookEntities) {
- if (!removedBookEntities.isEmpty()) {
- entityManager.flush();
- entityManager.clear();
- Set bookIds = removedBookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet());
- bookRepository.deleteByIdIn(bookIds);
- notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
- log.info("Books removed: {}", bookIds);
+ void detectMovedBooksAndUpdatePaths(LibraryEntity libraryEntity) throws IOException {
+ List currentLibraryFiles = getLibraryFiles(libraryEntity);
+ Map currentFileMap = currentLibraryFiles.stream()
+ .collect(Collectors.toMap(LibraryFile::getFileName, LibraryFile::getFullPath, (existing, replacement) -> existing));
+ for (BookEntity book : libraryEntity.getBookEntities()) {
+ Path existingPath = book.getFullFilePath();
+ Path updatedPath = currentFileMap.get(book.getFileName());
+ if (updatedPath != null && !updatedPath.equals(existingPath)) {
+ log.info("Detected moved book: '{}' from '{}' to '{}'", book.getFileName(), existingPath, updatedPath);
+ libraryEntity.getLibraryPaths().stream()
+ .filter(lp -> updatedPath.startsWith(Path.of(lp.getPath())))
+ .findFirst()
+ .ifPresent(matchingPath -> {
+ book.setLibraryPath(matchingPath);
+ book.setFileSubPath(FileUtils.getRelativeSubPath(matchingPath.getPath(), updatedPath));
+ });
+ }
}
}
+ public List detectDeletedBookIds(LibraryEntity libraryEntity) throws IOException {
+ Set currentFileNames = getLibraryFiles(libraryEntity).stream()
+ .map(LibraryFile::getFileName)
+ .collect(Collectors.toSet());
+ return libraryEntity.getBookEntities().stream()
+ .filter(book -> !currentFileNames.contains(book.getFileName()))
+ .map(BookEntity::getId)
+ .collect(Collectors.toList());
+ }
+
+ public List detectNewBookPaths(LibraryEntity libraryEntity) throws IOException {
+ Set existingFileNames = libraryEntity.getBookEntities().stream()
+ .map(BookEntity::getFileName)
+ .collect(Collectors.toSet());
+ return getLibraryFiles(libraryEntity).stream()
+ .filter(file -> !existingFileNames.contains(file.getFileName()))
+ .collect(Collectors.toList());
+ }
+
+ @Transactional
+ protected void deleteRemovedBooks(List bookIds) {
+ bookRepository.deleteByIdIn(bookIds);
+ notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
+ log.info("Books removed: {}", bookIds);
+ }
+
@Transactional
protected void processLibraryFiles(List libraryFiles) {
for (LibraryFile libraryFile : libraryFiles) {
@@ -143,30 +224,6 @@ public class LibraryProcessingService {
return null;
}
- @Transactional
- protected List getRemovedBooks(LibraryEntity libraryEntity) throws IOException {
- List libraryFiles = getLibraryFiles(libraryEntity);
- List bookEntities = libraryEntity.getBookEntities();
- Set libraryFilePaths = libraryFiles.stream()
- .map(LibraryFile::getFileName)
- .collect(Collectors.toSet());
- return bookEntities.stream()
- .filter(book -> !libraryFilePaths.contains(book.getFileName()))
- .collect(Collectors.toList());
- }
-
- @Transactional
- protected List getUnProcessedFiles(LibraryEntity libraryEntity) throws IOException {
- List libraryFiles = getLibraryFiles(libraryEntity);
- List bookEntities = libraryEntity.getBookEntities();
- Set processedPaths = bookEntities.stream()
- .map(BookEntity::getFileName)
- .collect(Collectors.toSet());
- return libraryFiles.stream()
- .filter(libraryFile -> !processedPaths.contains(libraryFile.getFileName()))
- .collect(Collectors.toList());
- }
-
private List getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
List libraryFiles = new ArrayList<>();
for (LibraryPathEntity libraryPathEntity : libraryEntity.getLibraryPaths()) {
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java
index cac814f50..9bc664c35 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java
@@ -84,7 +84,7 @@ public class MonitoringService {
if (!eventQueue.offer(event)) {
log.warn("Event queue is full, dropping event: {}", event.getFilePath());
} else {
- log.info("Queued file change event: {} ({} in queue)", event.getFilePath(), eventQueue.size());
+ log.debug("Queued file change event: {} ({} in queue)", event.getFilePath(), eventQueue.size());
}
}
@@ -113,8 +113,7 @@ public class MonitoringService {
} catch (InvalidDataAccessApiUsageException e) {
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
}
- log.info("Processed file change event for library {}: {} (from folder: {}) with kind: {}",
- libraryId, filePath, watchedFolder, event.getEventKind());
+ log.debug("Processed file change event for library {}: {} (from folder: {}) with kind: {}", libraryId, filePath, watchedFolder, event.getEventKind());
} else {
log.warn("No libraryId found for watched folder: {}", watchedFolder);
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java
index 4e62627be..7c4cf65f5 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringTask.java
@@ -40,7 +40,7 @@ public class MonitoringTask {
Path fullPath = directory.resolve(fileName);
if (isPdfOrEpub(fileName) && (kind == StandardWatchEventKinds.ENTRY_CREATE || kind == StandardWatchEventKinds.ENTRY_DELETE)) {
- log.info("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", kind, fileName, fullPath, directory);
+ log.debug("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", kind, fileName, fullPath, directory);
eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, directory));
}
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java
index 9b94dc21a..b79261ab0 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java
@@ -14,7 +14,10 @@ public class FileUtils {
private static final String FILE_NOT_FOUND_MESSAGE = "File does not exist: ";
public static String getBookFullPath(BookEntity bookEntity) {
- return String.format("%s/%s/%s", bookEntity.getLibraryPath().getPath(), bookEntity.getFileSubPath(), bookEntity.getFileName());
+ return Path.of(bookEntity.getLibraryPath().getPath(), bookEntity.getFileSubPath(), bookEntity.getFileName())
+ .normalize()
+ .toString()
+ .replace("\\", "/");
}
public static String getRelativeSubPath(String basePath, Path fullFilePath) {
From ff64362edb37925ee74a1368c4872e5af952742a Mon Sep 17 00:00:00 2001
From: "aditya.chandel" <>
Date: Fri, 23 May 2025 00:03:14 -0600
Subject: [PATCH 02/10] Implement support for comic book files (CBZ, CBR and
CB7)
---
booklore-api/build.gradle | 2 +
.../booklore/config/MultipartConfig.java | 22 ++
.../config/security/SecurityConfig.java | 3 +-
.../controller/CbxReaderController.java | 29 ++
.../booklore/exception/ApiError.java | 3 +-
.../custom/BookLoreUserTransformer.java | 4 +
.../booklore/model/dto/Book.java | 1 +
.../booklore/model/dto/BookLoreUser.java | 14 +-
.../model/dto/BookViewerSettings.java | 1 +
.../booklore/model/dto/CbxProgress.java | 14 +
.../model/dto/CbxViewerPreferences.java | 14 +
.../dto/request/ReadProgressRequest.java | 4 +-
.../model/dto/settings/AppSettingKey.java | 11 +-
.../model/dto/settings/AppSettings.java | 2 +
.../model/dto/settings/UserSettingKey.java | 1 +
.../entity/CbxViewerPreferencesEntity.java | 36 ++
.../model/entity/UserBookProgressEntity.java | 6 +
.../booklore/model/enums/BookFileType.java | 2 +-
.../booklore/model/enums/CbxPageSpread.java | 6 +
.../booklore/model/enums/CbxPageViewMode.java | 6 +
.../CbxViewerPreferencesRepository.java | 14 +
.../booklore/service/AppSettingService.java | 2 +
.../booklore/service/BookMetadataService.java | 6 +-
.../booklore/service/BooksService.java | 39 +++
.../service/CbxMetadataExtractor.java | 19 +
.../booklore/service/CbxReaderService.java | 330 ++++++++++++++++++
.../service/EpubMetadataExtractor.java | 16 +-
.../booklore/service/FileUploadService.java | 55 ++-
.../service/LibraryProcessingService.java | 38 +-
.../service/PdfMetadataExtractor.java | 5 +-
...ava => UploadedFileMetadataExtractor.java} | 2 +-
.../service/fileprocessor/CbxProcessor.java | 209 +++++++++++
.../metadata/parser/AmazonBookParser.java | 73 ++--
.../service/user/UserProvisioningService.java | 10 +
.../booklore/util/FileService.java | 4 +
.../booklore/util/FileUtils.java | 12 +
.../src/main/resources/application.yaml | 4 +-
.../V22__Create_cbx_viewer_table.sql | 9 +
...Add_cbx_progress_to_user_book_progress.sql | 3 +
booklore-ui/src/app/app.routes.ts | 6 +
.../cbx-reader/cbx-reader.component.html | 35 ++
.../cbx-reader/cbx-reader.component.scss | 96 +++++
.../cbx-reader/cbx-reader.component.ts | 195 +++++++++++
.../metadata-viewer.component.html | 42 +--
.../metadata-viewer.component.ts | 41 ++-
booklore-ui/src/app/book/model/book.model.ts | 24 +-
.../src/app/book/service/book.service.ts | 15 +
.../app/book/service/cbx-reader.service.ts | 19 +
.../src/app/core/model/app-settings.model.ts | 6 +-
.../global-preferences.component.html | 61 +++-
.../global-preferences.component.ts | 31 +-
.../settings/user-management/user.service.ts | 8 +
.../user-preferences.component.html | 71 +++-
.../user-preferences.component.ts | 48 ++-
.../book-uploader.component.html | 8 +-
.../book-uploader/book-uploader.component.ts | 21 +-
56 files changed, 1617 insertions(+), 141 deletions(-)
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/config/MultipartConfig.java
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/controller/CbxReaderController.java
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CbxProgress.java
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CbxViewerPreferences.java
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CbxViewerPreferencesEntity.java
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/enums/CbxPageSpread.java
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/enums/CbxPageViewMode.java
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/repository/CbxViewerPreferencesRepository.java
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/CbxMetadataExtractor.java
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/CbxReaderService.java
rename booklore-api/src/main/java/com/adityachandel/booklore/service/{BookFileMetadataExtractor.java => UploadedFileMetadataExtractor.java} (77%)
create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java
create mode 100644 booklore-api/src/main/resources/db/migration/V22__Create_cbx_viewer_table.sql
create mode 100644 booklore-api/src/main/resources/db/migration/V23__Add_cbx_progress_to_user_book_progress.sql
create mode 100644 booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.html
create mode 100644 booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.scss
create mode 100644 booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.ts
create mode 100644 booklore-ui/src/app/book/service/cbx-reader.service.ts
diff --git a/booklore-api/build.gradle b/booklore-api/build.gradle
index d242b1d5c..06cb9e6af 100644
--- a/booklore-api/build.gradle
+++ b/booklore-api/build.gradle
@@ -67,6 +67,8 @@ dependencies {
// --- API Documentation ---
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.6'
+ implementation 'org.apache.commons:commons-compress:1.27.1'
+ implementation 'com.github.junrar:junrar:7.5.5'
}
hibernate {
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/MultipartConfig.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/MultipartConfig.java
new file mode 100644
index 000000000..660ca239f
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/MultipartConfig.java
@@ -0,0 +1,22 @@
+package com.adityachandel.booklore.config;
+
+import com.adityachandel.booklore.service.AppSettingService;
+import jakarta.servlet.MultipartConfigElement;
+import org.springframework.boot.web.servlet.MultipartConfigFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.util.unit.DataSize;
+
+@Configuration
+public class MultipartConfig {
+
+ @Bean
+ public MultipartConfigElement multipartConfigElement(AppSettingService appSettingService) {
+ MultipartConfigFactory factory = new MultipartConfigFactory();
+ long maxSizeMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
+
+ factory.setMaxFileSize(DataSize.ofMegabytes(maxSizeMb));
+ factory.setMaxRequestSize(DataSize.ofMegabytes(maxSizeMb));
+ return factory.createMultipartConfig();
+ }
+}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java
index 4d66bdb55..363f59f0b 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java
@@ -51,7 +51,8 @@ public class SecurityConfig {
"/api/v1/settings",
"/api/v1/setup",
"/api/v1/setup/**",
- "/api/v1/opds/*/cover.jpg"
+ "/api/v1/opds/*/cover.jpg",
+ "/api/v1/cbx/*/pages/*"
).permitAll()
.anyRequest().authenticated()
)
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/CbxReaderController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/CbxReaderController.java
new file mode 100644
index 000000000..5e93a37d0
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/CbxReaderController.java
@@ -0,0 +1,29 @@
+package com.adityachandel.booklore.controller;
+
+import com.adityachandel.booklore.service.CbxReaderService;
+import jakarta.servlet.http.HttpServletResponse;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.*;
+
+import java.io.IOException;
+import java.util.List;
+
+@RestController
+@RequestMapping("/api/v1/cbx")
+@RequiredArgsConstructor
+public class CbxReaderController {
+
+ private final CbxReaderService cbxReaderService;
+
+ @GetMapping("/{bookId}/pages")
+ public List listPages(@PathVariable Long bookId) {
+ return cbxReaderService.getAvailablePages(bookId);
+ }
+
+ @GetMapping("/{bookId}/pages/{pageNumber}")
+ public void getPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
+ response.setContentType(MediaType.IMAGE_JPEG_VALUE);
+ cbxReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
+ }
+}
\ No newline at end of file
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java b/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java
index 3a54440f5..bdb36678d 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java
@@ -17,7 +17,8 @@ public enum ApiError {
IMAGE_NOT_FOUND(HttpStatus.NOT_FOUND, "Image not found or not readable"),
INVALID_FILE_FORMAT(HttpStatus.BAD_REQUEST, "Invalid file format, only pdf and epub are supported"),
LIBRARY_NOT_FOUND(HttpStatus.NOT_FOUND, "Library not found with ID: %d"),
- FILE_TOO_LARGE(HttpStatus.BAD_REQUEST, "File size exceeds the limit: 100 MB"),
+ FILE_TOO_LARGE(HttpStatus.BAD_REQUEST, "File size exceeds the limit: %d MB"),
+ CACHE_TOO_LARGE(HttpStatus.BAD_REQUEST, "Book archive is too large to cache with current settings"),
DIRECTORY_CREATION_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to create the directory: %s"),
INVALID_LIBRARY_PATH(HttpStatus.BAD_REQUEST, "Invalid library path"),
FILE_ALREADY_EXISTS(HttpStatus.CONFLICT, "File already exists"),
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/custom/BookLoreUserTransformer.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/custom/BookLoreUserTransformer.java
index 56354b6cb..7eecfbae8 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/custom/BookLoreUserTransformer.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/custom/BookLoreUserTransformer.java
@@ -60,6 +60,10 @@ public class BookLoreUserTransformer {
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.EpubReaderSetting.class);
userSettings.setEpubReaderSetting(value);
}
+ case CBX_READER_SETTING -> {
+ var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.CbxReaderSetting.class);
+ userSettings.setCbxReaderSetting(value);
+ }
case SIDEBAR_LIBRARY_SORTING -> {
var value = objectMapper.readValue(jsonValue, SidebarSortOption.class);
userSettings.setSidebarLibrarySorting(value);
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java
index b5782978a..91c1bc926 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Book.java
@@ -23,5 +23,6 @@ public class Book {
private BookMetadata metadata;
private PdfProgress pdfProgress;
private EpubProgress epubProgress;
+ private CbxProgress cbxProgress;
private List shelves;
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java
index e06623613..d30e98c08 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java
@@ -1,6 +1,8 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.dto.settings.SidebarSortOption;
+import com.adityachandel.booklore.model.enums.CbxPageSpread;
+import com.adityachandel.booklore.model.enums.CbxPageViewMode;
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
import lombok.AllArgsConstructor;
import lombok.Builder;
@@ -36,6 +38,7 @@ public class BookLoreUser {
public PerBookSetting perBookSetting;
public PdfReaderSetting pdfReaderSetting;
public EpubReaderSetting epubReaderSetting;
+ public CbxReaderSetting cbxReaderSetting;
public SidebarSortOption sidebarLibrarySorting;
public SidebarSortOption sidebarShelfSorting;
@@ -50,7 +53,6 @@ public class BookLoreUser {
private String flow;
}
-
@Data
@Builder
@AllArgsConstructor
@@ -60,6 +62,15 @@ public class BookLoreUser {
private String pageZoom;
}
+ @Data
+ @Builder
+ @AllArgsConstructor
+ @NoArgsConstructor
+ public static class CbxReaderSetting {
+ private CbxPageSpread pageSpread;
+ private CbxPageViewMode pageViewMode;
+ }
+
@Data
@Builder
@AllArgsConstructor
@@ -67,6 +78,7 @@ public class BookLoreUser {
public static class PerBookSetting {
private GlobalOrIndividual pdf;
private GlobalOrIndividual epub;
+ private GlobalOrIndividual cbx;
public enum GlobalOrIndividual {
Global, Individual
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookViewerSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookViewerSettings.java
index 0dc1f0bad..96d39ec1f 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookViewerSettings.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookViewerSettings.java
@@ -8,4 +8,5 @@ import lombok.Data;
public class BookViewerSettings {
private PdfViewerPreferences pdfSettings;
private EpubViewerPreferences epubSettings;
+ private CbxViewerPreferences cbxSettings;
}
\ No newline at end of file
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CbxProgress.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CbxProgress.java
new file mode 100644
index 000000000..d82a3c872
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CbxProgress.java
@@ -0,0 +1,14 @@
+package com.adityachandel.booklore.model.dto;
+
+import jakarta.validation.constraints.NotNull;
+import lombok.Builder;
+import lombok.Data;
+
+@Builder
+@Data
+public class CbxProgress {
+ @NotNull
+ Integer page;
+ @NotNull
+ Float percentage;
+}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CbxViewerPreferences.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CbxViewerPreferences.java
new file mode 100644
index 000000000..9f30e634a
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CbxViewerPreferences.java
@@ -0,0 +1,14 @@
+package com.adityachandel.booklore.model.dto;
+
+import com.adityachandel.booklore.model.enums.CbxPageSpread;
+import com.adityachandel.booklore.model.enums.CbxPageViewMode;
+import lombok.Builder;
+import lombok.Data;
+
+@Data
+@Builder
+public class CbxViewerPreferences {
+ private Long bookId;
+ private CbxPageSpread pageSpread;
+ private CbxPageViewMode pageViewMode;
+}
\ No newline at end of file
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadProgressRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadProgressRequest.java
index b64e6ed91..7232bf241 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadProgressRequest.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadProgressRequest.java
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.model.dto.request;
+import com.adityachandel.booklore.model.dto.CbxProgress;
import com.adityachandel.booklore.model.dto.EpubProgress;
import com.adityachandel.booklore.model.dto.PdfProgress;
import jakarta.validation.constraints.AssertTrue;
@@ -12,9 +13,10 @@ public class ReadProgressRequest {
private Long bookId;
private EpubProgress epubProgress;
private PdfProgress pdfProgress;
+ private CbxProgress cbxProgress;
@AssertTrue(message = "Either epubProgress or pdfProgress must be provided")
public boolean isProgressValid() {
- return epubProgress != null || pdfProgress != null;
+ return epubProgress != null || pdfProgress != null || cbxProgress != null;
}
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java
index a63c11b87..32013a320 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java
@@ -5,16 +5,19 @@ import lombok.Getter;
@Getter
public enum AppSettingKey {
QUICK_BOOK_MATCH("quick_book_match", true),
+ OIDC_PROVIDER_DETAILS("oidc_provider_details", true),
+ OIDC_AUTO_PROVISION_DETAILS("oidc_auto_provision_details", true),
+ SIDEBAR_LIBRARY_SORTING("sidebar_library_sorting", true),
+ SIDEBAR_SHELF_SORTING("sidebar_shelf_sorting", true),
+
AUTO_BOOK_SEARCH("auto_book_search", false),
COVER_IMAGE_RESOLUTION("cover_image_resolution", false),
SIMILAR_BOOK_RECOMMENDATION("similar_book_recommendation", false),
UPLOAD_FILE_PATTERN("upload_file_pattern", false),
OPDS_SERVER_ENABLED("opds_server_enabled", false),
OIDC_ENABLED("oidc_enabled", false),
- OIDC_PROVIDER_DETAILS("oidc_provider_details", true),
- OIDC_AUTO_PROVISION_DETAILS("oidc_auto_provision_details", true),
- SIDEBAR_LIBRARY_SORTING("sidebar_library_sorting", true),
- SIDEBAR_SHELF_SORTING("sidebar_shelf_sorting", true);
+ CBX_CACHE_SIZE_IN_MB("cbx_cache_size_in_mb", false),
+ MAX_FILE_UPLOAD_SIZE_IN_MB("max_file_upload_size_in_mb", false);
private final String dbKey;
private final boolean isJson;
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java
index 29c0591db..b93300e6a 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java
@@ -17,6 +17,8 @@ public class AppSettings {
private boolean similarBookRecommendation;
private boolean opdsServerEnabled;
private String uploadPattern;
+ private Integer cbxCacheSizeInMb;
+ private Integer maxFileUploadSizeInMb;
private boolean remoteAuthEnabled;
private boolean oidcEnabled;
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java
index 82d33354e..14a9fef48 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java
@@ -7,6 +7,7 @@ public enum UserSettingKey {
PER_BOOK_SETTING("perBookSetting", true),
PDF_READER_SETTING("pdfReaderSetting", true),
EPUB_READER_SETTING("epubReaderSetting", true),
+ CBX_READER_SETTING("cbxReaderSetting", true),
SIDEBAR_LIBRARY_SORTING("sidebarLibrarySorting", true),
SIDEBAR_SHELF_SORTING("sidebarShelfSorting", true);
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CbxViewerPreferencesEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CbxViewerPreferencesEntity.java
new file mode 100644
index 000000000..7250c6073
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CbxViewerPreferencesEntity.java
@@ -0,0 +1,36 @@
+package com.adityachandel.booklore.model.entity;
+
+import com.adityachandel.booklore.model.enums.CbxPageSpread;
+import com.adityachandel.booklore.model.enums.CbxPageViewMode;
+import jakarta.persistence.*;
+import lombok.*;
+
+@Entity
+@Getter
+@Setter
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+@Table(name = "cbx_viewer_preference", uniqueConstraints = {
+ @UniqueConstraint(columnNames = {"user_id", "book_id"})
+})
+public class CbxViewerPreferencesEntity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @Column(name = "user_id", nullable = false)
+ private Long userId;
+
+ @Column(name = "book_id", nullable = false)
+ private Long bookId;
+
+ @Column(name = "spread")
+ @Enumerated(EnumType.STRING)
+ private CbxPageSpread pageSpread;
+
+ @Column(name = "view_mode")
+ @Enumerated(EnumType.STRING)
+ private CbxPageViewMode pageViewMode;
+}
\ No newline at end of file
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookProgressEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookProgressEntity.java
index 772b1d113..f5cafdab5 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookProgressEntity.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/UserBookProgressEntity.java
@@ -40,4 +40,10 @@ public class UserBookProgressEntity {
@Column(name = "epub_progress_percent")
private Float epubProgressPercent;
+
+ @Column(name = "cbx_progress")
+ private Integer cbxProgress;
+
+ @Column(name = "cbx_progress_percent")
+ private Float cbxProgressPercent;
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java
index 9edea4079..b16361b34 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java
@@ -1,5 +1,5 @@
package com.adityachandel.booklore.model.enums;
public enum BookFileType {
- PDF, EPUB
+ PDF, EPUB, CBX
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/CbxPageSpread.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/CbxPageSpread.java
new file mode 100644
index 000000000..223bc2f53
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/CbxPageSpread.java
@@ -0,0 +1,6 @@
+package com.adityachandel.booklore.model.enums;
+
+public enum CbxPageSpread {
+ EVEN,
+ ODD
+}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/CbxPageViewMode.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/CbxPageViewMode.java
new file mode 100644
index 000000000..40f23f8bb
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/CbxPageViewMode.java
@@ -0,0 +1,6 @@
+package com.adityachandel.booklore.model.enums;
+
+public enum CbxPageViewMode {
+ SINGLE_PAGE,
+ TWO_PAGE
+}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/CbxViewerPreferencesRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/CbxViewerPreferencesRepository.java
new file mode 100644
index 000000000..0ac8b0df6
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/CbxViewerPreferencesRepository.java
@@ -0,0 +1,14 @@
+package com.adityachandel.booklore.repository;
+
+import com.adityachandel.booklore.model.entity.CbxViewerPreferencesEntity;
+import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+import java.util.Optional;
+
+@Repository
+public interface CbxViewerPreferencesRepository extends JpaRepository {
+
+ Optional findByBookIdAndUserId(long bookId, Long id);
+}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/AppSettingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/AppSettingService.java
index 09bd7f9bd..6224355c9 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/AppSettingService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/AppSettingService.java
@@ -77,6 +77,8 @@ public class AppSettingService {
builder.similarBookRecommendation(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true")));
builder.opdsServerEnabled(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false")));
builder.oidcEnabled(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.OIDC_ENABLED, "false")));
+ builder.cbxCacheSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.CBX_CACHE_SIZE_IN_MB, "5120")));
+ builder.maxFileUploadSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, "100")));
return builder.build();
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataService.java
index abe812f83..8ece39bed 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataService.java
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.mapper.BookMetadataMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
+import com.adityachandel.booklore.model.dto.CbxProgress;
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
import com.adityachandel.booklore.model.dto.request.ToggleAllLockRequest;
@@ -19,6 +20,7 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.enums.MetadataProvider;
+import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.service.metadata.parser.BookParser;
@@ -54,6 +56,7 @@ public class BookMetadataService {
private final FileService fileService;
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
+ private final CbxProcessor cbxProcessor;
private final Map parserMap;
public List getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
@@ -438,9 +441,10 @@ public class BookMetadataService {
switch (book.getBookType()) {
case PDF -> pdfProcessor.generateCover(book);
case EPUB -> epubProcessor.generateCover(book);
+ case CBX -> cbxProcessor.generateCover(book);
default -> throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(book.getBookType());
}
- log.info("{} Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
+ log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
}
@Transactional
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BooksService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BooksService.java
index 6082a87d7..6b43b9537 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BooksService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BooksService.java
@@ -39,6 +39,7 @@ public class BooksService {
private final BookRepository bookRepository;
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
+ private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
private final ShelfRepository shelfRepository;
private final FileService fileService;
private final BookMapper bookMapper;
@@ -67,6 +68,13 @@ public class BooksService {
.zoom(pdfPref.getZoom())
.spread(pdfPref.getSpread())
.build()));
+ } else if (bookEntity.getBookType() == BookFileType.CBX) {
+ cbxViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
+ .ifPresent(cbxPref -> settingsBuilder.cbxSettings(CbxViewerPreferences.builder()
+ .bookId(bookId)
+ .pageViewMode(cbxPref.getPageViewMode())
+ .pageSpread(cbxPref.getPageSpread())
+ .build()));
} else {
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
}
@@ -111,6 +119,22 @@ public class BooksService {
epubPrefs.setFlow(epubSettings.getFlow());
epubViewerPreferencesRepository.save(epubPrefs);
+ } else if (bookEntity.getBookType() == BookFileType.CBX) {
+ CbxViewerPreferencesEntity cbxPrefs = cbxViewerPreferencesRepository
+ .findByBookIdAndUserId(bookId, user.getId())
+ .orElseGet(() -> {
+ CbxViewerPreferencesEntity newPrefs = CbxViewerPreferencesEntity.builder()
+ .bookId(bookId)
+ .userId(user.getId())
+ .build();
+ return cbxViewerPreferencesRepository.save(newPrefs);
+ });
+
+ CbxViewerPreferences cbxSettings = bookViewerSettings.getCbxSettings();
+ cbxPrefs.setPageSpread(cbxSettings.getPageSpread());
+ cbxPrefs.setPageViewMode(cbxSettings.getPageViewMode());
+ cbxViewerPreferencesRepository.save(cbxPrefs);
+
} else {
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
}
@@ -137,6 +161,12 @@ public class BooksService {
.percentage(userProgress.getEpubProgressPercent())
.build());
}
+ if (bookEntity.getBookType() == BookFileType.CBX) {
+ book.setCbxProgress(CbxProgress.builder()
+ .page(userProgress.getCbxProgress())
+ .percentage(userProgress.getCbxProgressPercent())
+ .build());
+ }
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
if (!withDescription) {
@@ -180,6 +210,12 @@ public class BooksService {
.percentage(userProgress.getPdfProgressPercent())
.build());
}
+ if (bookEntity.getBookType() == BookFileType.CBX) {
+ book.setCbxProgress(CbxProgress.builder()
+ .page(userProgress.getCbxProgress())
+ .percentage(userProgress.getCbxProgressPercent())
+ .build());
+ }
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
return book;
})
@@ -236,6 +272,9 @@ public class BooksService {
} else if (book.getBookType() == BookFileType.PDF && request.getPdfProgress() != null) {
userBookProgress.setPdfProgress(request.getPdfProgress().getPage());
userBookProgress.setPdfProgressPercent(request.getPdfProgress().getPercentage());
+ } else if (book.getBookType() == BookFileType.CBX && request.getCbxProgress() != null) {
+ userBookProgress.setCbxProgress(request.getCbxProgress().getPage());
+ userBookProgress.setCbxProgressPercent(request.getCbxProgress().getPercentage());
}
userBookProgressRepository.save(userBookProgress);
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/CbxMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/CbxMetadataExtractor.java
new file mode 100644
index 000000000..2fefd0c66
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/CbxMetadataExtractor.java
@@ -0,0 +1,19 @@
+package com.adityachandel.booklore.service;
+
+import com.adityachandel.booklore.model.UploadedFileMetadata;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.FilenameUtils;
+import org.springframework.stereotype.Service;
+
+@Slf4j
+@Service
+public class CbxMetadataExtractor implements UploadedFileMetadataExtractor {
+
+ @Override
+ public UploadedFileMetadata extractMetadata(String filePath) {
+ UploadedFileMetadata metadata = new UploadedFileMetadata();
+ String title = FilenameUtils.getBaseName(filePath);
+ metadata.setTitle(title);
+ return metadata;
+ }
+}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/CbxReaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/CbxReaderService.java
new file mode 100644
index 000000000..9f2da4263
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/CbxReaderService.java
@@ -0,0 +1,330 @@
+package com.adityachandel.booklore.service;
+
+import com.adityachandel.booklore.exception.ApiError;
+import com.adityachandel.booklore.model.entity.BookEntity;
+import com.adityachandel.booklore.repository.BookRepository;
+import com.adityachandel.booklore.util.FileService;
+import com.adityachandel.booklore.util.FileUtils;
+import com.github.junrar.Archive;
+import com.github.junrar.exception.RarException;
+import com.github.junrar.rarfile.FileHeader;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
+import org.apache.commons.compress.archivers.sevenz.SevenZFile;
+import org.apache.pdfbox.io.IOUtils;
+import org.springframework.stereotype.Service;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class CbxReaderService {
+
+ private static final String CACHE_INFO_FILENAME = ".cache-info";
+ private static final String CBZ_EXTENSION = ".cbz";
+ private static final String CBR_EXTENSION = ".cbr";
+ private static final String CB7_EXTENSION = ".cb7";
+
+ private final BookRepository bookRepository;
+ private final AppSettingService appSettingService;
+ private final FileService fileService;
+
+ public List getAvailablePages(Long bookId) {
+ BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
+ String bookFullPath = FileUtils.getBookFullPath(bookEntity);
+
+ Path cbzPath = Path.of(bookFullPath);
+ Path cacheDir = Path.of(fileService.getCbxCachePath(), String.valueOf(bookId));
+ Path cacheInfoPath = cacheDir.resolve(CACHE_INFO_FILENAME);
+
+ try {
+ long maxCacheSizeBytes = mbToBytes(appSettingService.getAppSettings().getCbxCacheSizeInMb());
+ long estimatedSize = estimateArchiveSize(cbzPath);
+ if (estimatedSize > maxCacheSizeBytes) {
+ log.warn("Cache skipped: Estimated archive size {} exceeds max cache size {}", estimatedSize, maxCacheSizeBytes);
+ throw ApiError.CACHE_TOO_LARGE.createException();
+ }
+ enforceCacheLimit();
+
+ if (needsCacheRefresh(cbzPath, cacheInfoPath)) {
+ log.info("Invalidating cache for book {}", bookId);
+ if (Files.exists(cacheDir)) FileUtils.deleteDirectoryRecursively(cacheDir);
+ Files.createDirectories(cacheDir);
+ extractCbxArchive(cbzPath, cacheDir);
+ writeCacheInfo(cbzPath, cacheInfoPath);
+ if (!Files.exists(cacheDir)) {
+ log.warn("Cache for book {} was deleted during enforcement. Re-extracting.", bookId);
+ Files.createDirectories(cacheDir);
+ extractCbxArchive(cbzPath, cacheDir);
+ writeCacheInfo(cbzPath, cacheInfoPath);
+ }
+ }
+ } catch (IOException e) {
+ log.error("Failed to cache CBZ for book {}", bookId, e);
+ return List.of();
+ }
+
+ try (var stream = Files.list(cacheDir)) {
+ return stream
+ .filter(p -> p.toString().endsWith(".jpg"))
+ .sorted(Comparator.comparing(Path::getFileName))
+ .map(p -> extractPageNumber(p.getFileName().toString()))
+ .filter(p -> p != -1)
+ .collect(Collectors.toList());
+ } catch (IOException e) {
+ log.error("Failed to list pages for book {}", bookId, e);
+ return List.of();
+ }
+ }
+
+ public void streamPageImage(Long bookId, int page, OutputStream outputStream) throws IOException {
+ Path pagePath = Path.of(fileService.getCbxCachePath(), String.valueOf(bookId), String.format("%04d.jpg", page));
+ if (!Files.exists(pagePath)) throw new FileNotFoundException("Page not found: " + page);
+ try (InputStream in = Files.newInputStream(pagePath)) {
+ IOUtils.copy(in, outputStream);
+ }
+ }
+
+ private void extractCbxArchive(Path cbxPath, Path targetDir) throws IOException {
+ String filename = cbxPath.getFileName().toString().toLowerCase();
+ if (filename.endsWith(CBZ_EXTENSION)) {
+ extractZipArchive(cbxPath, targetDir);
+ } else if (filename.endsWith(CB7_EXTENSION)) {
+ extract7zArchive(cbxPath, targetDir);
+ } else if (filename.endsWith(CBR_EXTENSION)) {
+ extractRarArchive(cbxPath, targetDir);
+ } else {
+ throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
+ }
+ }
+
+ private void extractZipArchive(Path cbzPath, Path targetDir) throws IOException {
+ try (InputStream fis = Files.newInputStream(cbzPath);
+ ZipInputStream zis = new ZipInputStream(fis)) {
+
+ ZipEntry entry;
+ int index = 1;
+
+ while ((entry = zis.getNextEntry()) != null) {
+ isImageFile(entry.getName());
+ if (!entry.isDirectory() && isImageFile(entry.getName())) {
+ Path target = targetDir.resolve(String.format("%04d.jpg", index++));
+ Files.copy(zis, target, StandardCopyOption.REPLACE_EXISTING);
+ }
+ zis.closeEntry();
+ }
+ }
+ }
+
+ private void extract7zArchive(Path cb7Path, Path targetDir) throws IOException {
+ try (SevenZFile sevenZFile = new SevenZFile(cb7Path.toFile())) {
+ SevenZArchiveEntry entry;
+ int index = 1;
+ while ((entry = sevenZFile.getNextEntry()) != null) {
+ if (!entry.isDirectory() && isImageFile(entry.getName())) {
+ Path target = targetDir.resolve(String.format("%04d.jpg", index++));
+ try (OutputStream out = Files.newOutputStream(target)) {
+ copySevenZEntry(sevenZFile, out, entry.getSize());
+ }
+ }
+ }
+ }
+ }
+
+ private void copySevenZEntry(SevenZFile sevenZFile, OutputStream out, long size) throws IOException {
+ byte[] buffer = new byte[8192];
+ long read = 0;
+ int count;
+ while (read < size && (count = sevenZFile.read(buffer, 0, (int) Math.min(buffer.length, size - read))) > 0) {
+ out.write(buffer, 0, count);
+ read += count;
+ }
+ }
+
+ private void extractRarArchive(Path cbrPath, Path targetDir) throws IOException {
+ try (Archive archive = new Archive(cbrPath.toFile())) {
+ List headers = archive.getFileHeaders();
+ int index = 1;
+ for (FileHeader header : headers) {
+ if (!header.isDirectory() && isImageFile(header.getFileName())) {
+ Path target = targetDir.resolve(String.format("%04d.jpg", index++));
+ try (OutputStream out = Files.newOutputStream(target)) {
+ archive.extractFile(header, out);
+ }
+ }
+ }
+ } catch (Exception e) {
+ throw new IOException("Failed to extract CBR archive", e);
+ }
+ }
+
+ private boolean isImageFile(String name) {
+ String lower = name.toLowerCase().replace("\\", "/");
+ return lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".png");
+ }
+
+ private int extractPageNumber(String filename) {
+ try {
+ return Integer.parseInt(filename.replaceAll("\\D+", ""));
+ } catch (Exception e) {
+ return -1;
+ }
+ }
+
+ private boolean needsCacheRefresh(Path cbzPath, Path cacheInfoPath) throws IOException {
+ if (!Files.exists(cacheInfoPath)) return true;
+
+ long currentLastModified = Files.getLastModifiedTime(cbzPath).toMillis();
+ String recordedTimestamp = Files.readString(cacheInfoPath).trim();
+
+ try {
+ long recordedLastModified = Long.parseLong(recordedTimestamp);
+ return recordedLastModified != currentLastModified;
+ } catch (NumberFormatException e) {
+ return true;
+ }
+ }
+
+ private void writeCacheInfo(Path cbzPath, Path cacheInfoPath) throws IOException {
+ long lastModified = Files.getLastModifiedTime(cbzPath).toMillis();
+ Files.writeString(cacheInfoPath, String.valueOf(lastModified), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
+ }
+
+ private void enforceCacheLimit() {
+ try {
+ Path cacheRoot = Path.of(fileService.getCbxCachePath());
+ if (!Files.exists(cacheRoot) || !Files.isDirectory(cacheRoot)) {
+ return;
+ }
+ long totalSize = 0L;
+ List cacheDirs;
+ try (Stream stream = Files.list(cacheRoot)) {
+ cacheDirs = stream.filter(Files::isDirectory).collect(Collectors.toList());
+ }
+
+ for (Path dir : cacheDirs) {
+ totalSize += getDirectorySize(dir);
+ }
+
+ long maxCacheSizeBytes = mbToBytes(appSettingService.getAppSettings().getCbxCacheSizeInMb());
+
+ while (totalSize > maxCacheSizeBytes && !cacheDirs.isEmpty()) {
+ Path leastRecentlyReadDir = cacheDirs.stream()
+ .min(Comparator.comparingLong(this::getLastReadTime))
+ .orElse(null);
+
+ long sizeFreed = getDirectorySize(leastRecentlyReadDir);
+ FileUtils.deleteDirectoryRecursively(leastRecentlyReadDir);
+ cacheDirs.remove(leastRecentlyReadDir);
+ totalSize -= sizeFreed;
+ log.info("Deleted cache directory {} to enforce cache size limit", leastRecentlyReadDir);
+ }
+ } catch (IOException e) {
+ log.error("Error enforcing cache size limit", e);
+ }
+ }
+
+ private long getLastReadTime(Path cacheDir) {
+ Path cacheInfoPath = cacheDir.resolve(CACHE_INFO_FILENAME);
+ if (!Files.exists(cacheInfoPath)) {
+ return Long.MIN_VALUE;
+ }
+ try {
+ String content = Files.readString(cacheInfoPath).trim();
+ return Long.parseLong(content);
+ } catch (Exception e) {
+ return Long.MIN_VALUE;
+ }
+ }
+
+ private long getDirectorySize(Path dir) {
+ try (Stream paths = Files.walk(dir)) {
+ return paths
+ .filter(Files::isRegularFile)
+ .mapToLong(p -> {
+ try {
+ return Files.size(p);
+ } catch (IOException e) {
+ return 0L;
+ }
+ })
+ .sum();
+ } catch (IOException e) {
+ return 0L;
+ }
+ }
+
+ private long estimateArchiveSize(Path cbxPath) {
+ try {
+ String name = cbxPath.getFileName().toString().toLowerCase();
+ if (name.endsWith(CBZ_EXTENSION)) {
+ return estimateCbzArchiveSize(cbxPath);
+ } else if (name.endsWith(CB7_EXTENSION)) {
+ return estimateCb7ArchiveSize(cbxPath);
+ } else if (name.endsWith(CBR_EXTENSION)) {
+ return estimateCbrArchiveSize(cbxPath);
+ }
+ } catch (Exception e) {
+ log.warn("Failed to estimate archive size for {}", cbxPath, e);
+ }
+ return Long.MAX_VALUE;
+ }
+
+ private long estimateCbzArchiveSize(Path cbxPath) throws IOException {
+ try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(cbxPath))) {
+ ZipEntry entry;
+ long total = 0;
+ while ((entry = zis.getNextEntry()) != null) {
+ if (!entry.isDirectory() && isImageFile(entry.getName())) {
+ total += entry.getCompressedSize();
+ }
+ }
+ return total;
+ }
+ }
+
+ private long estimateCb7ArchiveSize(Path cbxPath) throws IOException {
+ try (SevenZFile sevenZFile = new SevenZFile(cbxPath.toFile())) {
+ SevenZArchiveEntry entry;
+ long total = 0;
+ while ((entry = sevenZFile.getNextEntry()) != null) {
+ if (!entry.isDirectory() && isImageFile(entry.getName())) {
+ total += entry.getSize();
+ }
+ }
+ return total;
+ }
+ }
+
+ private long estimateCbrArchiveSize(Path cbxPath) throws IOException, RarException {
+ try (Archive archive = new Archive(cbxPath.toFile())) {
+ long total = 0;
+ for (FileHeader header : archive.getFileHeaders()) {
+ if (!header.isDirectory() && isImageFile(header.getFileName())) {
+ total += header.getFullUnpackSize();
+ }
+ }
+ return total;
+ }
+ }
+
+ private long mbToBytes(int mb) {
+ return mb * 1024L * 1024L;
+ }
+}
\ No newline at end of file
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/EpubMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/EpubMetadataExtractor.java
index de1660cc0..3bfd15e15 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/EpubMetadataExtractor.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/EpubMetadataExtractor.java
@@ -1,17 +1,13 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.UploadedFileMetadata;
-import com.adityachandel.booklore.util.FileUtils;
import io.documentnode.epub4j.domain.Author;
import io.documentnode.epub4j.domain.Book;
import io.documentnode.epub4j.epub.EpubReader;
import lombok.extern.slf4j.Slf4j;
-import org.apache.pdfbox.Loader;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDDocumentInformation;
+import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
-import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
@@ -20,21 +16,23 @@ import java.util.stream.Collectors;
@Slf4j
@Service
-public class EpubMetadataExtractor implements BookFileMetadataExtractor {
+public class EpubMetadataExtractor implements UploadedFileMetadataExtractor {
@Override
public UploadedFileMetadata extractMetadata(String filePath) {
UploadedFileMetadata metadata = new UploadedFileMetadata();
try (FileInputStream fis = new FileInputStream(filePath)) {
- Book epubBook = new EpubReader().readEpub(fis);
+ Book epub = new EpubReader().readEpub(fis);
- String title = epubBook.getTitle();
+ String title = epub.getTitle();
if (title != null && !title.isBlank()) {
metadata.setTitle(title);
+ } else {
+ metadata.setTitle(FilenameUtils.getBaseName(filePath));
}
- List epubAuthors = epubBook.getMetadata().getAuthors();
+ List epubAuthors = epub.getMetadata().getAuthors();
if (!epubAuthors.isEmpty()) {
Set authors = epubAuthors.stream()
.map(author -> author.getFirstname() + " " + author.getLastname())
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/FileUploadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/FileUploadService.java
index 1bae7ae53..9dba212c8 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/FileUploadService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/FileUploadService.java
@@ -3,13 +3,13 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.UploadedFileMetadata;
import com.adityachandel.booklore.model.dto.Book;
-import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.LibraryRepository;
+import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileUtils;
@@ -31,21 +31,24 @@ import java.util.Optional;
@Slf4j
public class FileUploadService {
- private static final long MAX_FILE_SIZE = 100 * 1024 * 1024;
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String EPUB_MIME_TYPE = "application/epub+zip";
+ private static final String CBZ_MIME_TYPE = "application/x-cbz";
+ private static final String CBR_MIME_TYPE = "application/x-cbr";
+ private static final String CB7_MIME_TYPE = "application/x-cb7";
private final LibraryRepository libraryRepository;
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
+ private final CbxProcessor cbxProcessor;
private final NotificationService notificationService;
private final AppSettingService appSettingService;
private final PdfMetadataExtractor pdfMetadataExtractor;
private final EpubMetadataExtractor epubMetadataExtractor;
public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException {
- String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
- validateFile(file);
+ Integer uploadSizeInMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
+ validateFile(file, uploadSizeInMb);
LibraryEntity libraryEntity = libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
@@ -62,18 +65,12 @@ public class FileUploadService {
try {
file.transferTo(tempPath);
- String fileType = Objects.requireNonNull(file.getContentType());
-
- if (fileType.equalsIgnoreCase(PDF_MIME_TYPE)) {
- metadata = pdfMetadataExtractor.extractMetadata(tempPath.toString());
- } else if (fileType.equalsIgnoreCase(EPUB_MIME_TYPE)) {
- metadata = epubMetadataExtractor.extractMetadata(tempPath.toString());
- } else {
- throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file type.");
- }
+ metadata = extractMetadata(file, tempPath);
String title = Optional.ofNullable(metadata.getTitle()).orElse("").trim();
String authors = metadata.getAuthors() != null ? String.join(", ", metadata.getAuthors()) : "";
+
+ String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
String relativePath = resolveUploadPath(uploadPattern, title, authors, file.getOriginalFilename());
Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
@@ -100,13 +97,35 @@ public class FileUploadService {
}
}
- private void validateFile(MultipartFile file) {
+ private UploadedFileMetadata extractMetadata(MultipartFile file, Path tempPath) throws IOException {
+ String fileType = Objects.requireNonNull(file.getContentType());
+ return switch (fileType.toLowerCase()) {
+ case PDF_MIME_TYPE -> pdfMetadataExtractor.extractMetadata(tempPath.toString());
+ case EPUB_MIME_TYPE -> epubMetadataExtractor.extractMetadata(tempPath.toString());
+ case CBZ_MIME_TYPE, CBR_MIME_TYPE, CB7_MIME_TYPE -> new UploadedFileMetadata();
+ default -> throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file type.");
+ };
+ }
+
+ private boolean isSupportedContentType(String fileType) {
+ return PDF_MIME_TYPE.equals(fileType)
+ || EPUB_MIME_TYPE.equals(fileType)
+ || CBZ_MIME_TYPE.equals(fileType)
+ || CBR_MIME_TYPE.equals(fileType)
+ || CB7_MIME_TYPE.equals(fileType);
+ }
+
+ private boolean isFileTooLarge(MultipartFile file, int uploadSizeInMb) {
+ return file.getSize() > uploadSizeInMb * 1024L * 1024L;
+ }
+
+ private void validateFile(MultipartFile file, int uploadSizeInMb) {
String fileType = file.getContentType();
- if (!PDF_MIME_TYPE.equals(fileType) && !EPUB_MIME_TYPE.equals(fileType)) {
+ if (!isSupportedContentType(fileType)) {
throw ApiError.INVALID_FILE_FORMAT.createException();
}
- if (file.getSize() > MAX_FILE_SIZE) {
- throw ApiError.FILE_TOO_LARGE.createException();
+ if (isFileTooLarge(file, uploadSizeInMb)) {
+ throw ApiError.FILE_TOO_LARGE.createException(uploadSizeInMb);
}
}
@@ -129,6 +148,7 @@ public class FileUploadService {
return switch (fileType) {
case PDF -> pdfProcessor.processFile(libraryFile, false);
case EPUB -> epubProcessor.processFile(libraryFile, false);
+ case CBX -> cbxProcessor.processFile(libraryFile, false);
};
}
@@ -160,6 +180,7 @@ public class FileUploadService {
return switch (fileType.toLowerCase()) {
case PDF_MIME_TYPE -> BookFileType.PDF;
case EPUB_MIME_TYPE -> BookFileType.EPUB;
+ case CBZ_MIME_TYPE, CBR_MIME_TYPE, CB7_MIME_TYPE -> BookFileType.CBX;
default -> null;
};
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java
index 3fea7d668..fa2749e26 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java
@@ -10,6 +10,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
+import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileUtils;
@@ -40,6 +41,7 @@ public class LibraryProcessingService {
private final NotificationService notificationService;
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
+ private final CbxProcessor cbxProcessor;
private final BookRepository bookRepository;
private final EntityManager entityManager;
private final TransactionTemplate transactionTemplate;
@@ -138,8 +140,15 @@ public class LibraryProcessingService {
@Transactional
protected BookFileType getBookFileType(String fileName) {
- if (fileName.endsWith(".pdf")) {
+ String lowerCaseName = fileName.toLowerCase();
+ if (lowerCaseName.endsWith(".pdf")) {
return BookFileType.PDF;
+ } else if (lowerCaseName.endsWith(".cbz")) {
+ return BookFileType.CBX;
+ } else if (lowerCaseName.endsWith(".cbr")) {
+ return BookFileType.CBX;
+ } else if (lowerCaseName.endsWith(".cb7")) {
+ return BookFileType.CBX;
} else {
return BookFileType.EPUB;
}
@@ -220,6 +229,8 @@ public class LibraryProcessingService {
return pdfProcessor.processFile(libraryFile, false);
} else if (libraryFile.getBookFileType() == BookFileType.EPUB) {
return epubProcessor.processFile(libraryFile, false);
+ } else if (libraryFile.getBookFileType() == BookFileType.CBX) {
+ return cbxProcessor.processFile(libraryFile, false);
}
return null;
}
@@ -239,12 +250,29 @@ public class LibraryProcessingService {
stream.filter(Files::isRegularFile)
.filter(file -> {
String fileName = file.getFileName().toString().toLowerCase();
- return fileName.endsWith(".pdf") || fileName.endsWith(".epub");
+ return fileName.endsWith(".pdf") ||
+ fileName.endsWith(".epub") ||
+ fileName.endsWith(".cbz") ||
+ fileName.endsWith(".cbr") ||
+ fileName.endsWith(".cb7");
})
.forEach(fullFilePath -> {
- BookFileType fileType = fullFilePath.getFileName().toString().toLowerCase().endsWith(".pdf")
- ? BookFileType.PDF
- : BookFileType.EPUB;
+ String fileName = fullFilePath.getFileName().toString().toLowerCase();
+ BookFileType fileType;
+ if (fileName.endsWith(".pdf")) {
+ fileType = BookFileType.PDF;
+ } else if (fileName.endsWith(".epub")) {
+ fileType = BookFileType.EPUB;
+ } else if (fileName.endsWith(".cbz")) {
+ fileType = BookFileType.CBX;
+ } else if (fileName.endsWith(".cbr")) {
+ fileType = BookFileType.CBX;
+ } else if (fileName.endsWith(".cb7")) {
+ fileType = BookFileType.CBX;
+ } else {
+ return;
+ }
+
String relativePath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), fullFilePath);
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/PdfMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/PdfMetadataExtractor.java
index cf120f13f..c05711945 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/PdfMetadataExtractor.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/PdfMetadataExtractor.java
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.UploadedFileMetadata;
import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
@@ -13,7 +14,7 @@ import java.util.Set;
@Slf4j
@Service
-public class PdfMetadataExtractor implements BookFileMetadataExtractor {
+public class PdfMetadataExtractor implements UploadedFileMetadataExtractor {
@Override
public UploadedFileMetadata extractMetadata(String filePath) {
@@ -24,6 +25,8 @@ public class PdfMetadataExtractor implements BookFileMetadataExtractor {
if (info != null) {
if (info.getTitle() != null && !info.getTitle().isBlank()) {
metadata.setTitle(info.getTitle());
+ } else {
+ metadata.setTitle(FilenameUtils.getBaseName(filePath));
}
if (info.getAuthor() != null && !info.getAuthor().isBlank()) {
metadata.setAuthors(Set.of(info.getAuthor().split(",")));
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookFileMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/UploadedFileMetadataExtractor.java
similarity index 77%
rename from booklore-api/src/main/java/com/adityachandel/booklore/service/BookFileMetadataExtractor.java
rename to booklore-api/src/main/java/com/adityachandel/booklore/service/UploadedFileMetadataExtractor.java
index 360aa67f6..7ed550379 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookFileMetadataExtractor.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/UploadedFileMetadataExtractor.java
@@ -2,7 +2,7 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.UploadedFileMetadata;
-public interface BookFileMetadataExtractor {
+public interface UploadedFileMetadataExtractor {
UploadedFileMetadata extractMetadata(String filePath);
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java
new file mode 100644
index 000000000..5a507579f
--- /dev/null
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java
@@ -0,0 +1,209 @@
+package com.adityachandel.booklore.service.fileprocessor;
+
+import com.adityachandel.booklore.mapper.BookMapper;
+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.BookFileType;
+import com.adityachandel.booklore.repository.BookMetadataRepository;
+import com.adityachandel.booklore.repository.BookRepository;
+import com.adityachandel.booklore.service.BookCreatorService;
+import com.adityachandel.booklore.util.FileUtils;
+import com.github.junrar.Archive;
+import com.github.junrar.rarfile.FileHeader;
+import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
+import org.apache.commons.compress.archivers.sevenz.SevenZFile;
+import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
+import org.apache.commons.compress.archivers.zip.ZipFile;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.InputStream;
+import java.time.Instant;
+import java.util.*;
+
+@Slf4j
+@Service
+@AllArgsConstructor
+public class CbxProcessor implements FileProcessor {
+
+ private final BookRepository bookRepository;
+ private final BookCreatorService bookCreatorService;
+ private final BookMapper bookMapper;
+ private final FileProcessingUtils fileProcessingUtils;
+ private final BookMetadataRepository bookMetadataRepository;
+
+ @Transactional(propagation = Propagation.REQUIRES_NEW)
+ @Override
+ public Book processFile(LibraryFile libraryFile, boolean forceProcess) {
+ File bookFile = new File(libraryFile.getFileName());
+ String fileName = bookFile.getName();
+
+ if (!forceProcess) {
+ Optional bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId());
+ return bookOptional.map(bookMapper::toBook).orElseGet(() -> processNewFile(libraryFile));
+ } else {
+ return processNewFile(libraryFile);
+ }
+ }
+
+ @Transactional(propagation = Propagation.REQUIRES_NEW)
+ protected Book processNewFile(LibraryFile libraryFile) {
+ BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX);
+ if (generateCover(bookEntity)) {
+ fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
+ }
+ setMetadata(bookEntity);
+ bookCreatorService.saveConnections(bookEntity);
+ bookEntity = bookRepository.save(bookEntity);
+ bookRepository.flush();
+ return bookMapper.toBook(bookEntity);
+ }
+
+ public boolean generateCover(BookEntity bookEntity) {
+ File file = new File(FileUtils.getBookFullPath(bookEntity));
+ try {
+ List images = extractImagesFromArchive(file);
+ if (images == null || images.isEmpty()) {
+ log.warn("No image entries found in archive: {}", file.getName());
+ return false;
+ }
+ BufferedImage coverImage = images.get(0);
+ boolean saved = fileProcessingUtils.saveCoverImage(coverImage, bookEntity.getId());
+ bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
+ bookMetadataRepository.save(bookEntity.getMetadata());
+ return saved;
+ } catch (Exception e) {
+ log.error("Error generating cover from archive {}, error: {}", bookEntity.getFileName(), e.getMessage());
+ return false;
+ }
+ }
+
+ private List extractImagesFromArchive(File file) {
+ String name = file.getName().toLowerCase();
+ if (name.endsWith(".cbz")) {
+ return extractImagesFromZip(file);
+ } else if (name.endsWith(".cb7")) {
+ return extractImagesFrom7z(file);
+ } else if (name.endsWith(".cbr")) {
+ return extractImagesFromRar(file);
+ } else {
+ log.warn("Unsupported archive format: {}", name);
+ return List.of();
+ }
+ }
+
+ private List extractImagesFromRar(File file) {
+ List images = new ArrayList<>();
+ try (Archive archive = new Archive(file)) {
+ List headers = archive.getFileHeaders();
+ headers.stream()
+ .filter(h -> {
+ if (h.isDirectory()) return false;
+ String fileName = h.getFileNameString().replace("\\", "/").toLowerCase();
+ return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png") || fileName.endsWith(".webp");
+ })
+ .sorted(Comparator.comparing(FileHeader::getFileNameString))
+ .forEach(header -> {
+ try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+ archive.extractFile(header, baos);
+ byte[] imageData = baos.toByteArray();
+ BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData));
+ if (img != null) {
+ images.add(img);
+ }
+ } catch (Exception e) {
+ log.warn("Failed to read image from RAR entry {}: {}", header.getFileNameString(), e.getMessage());
+ }
+ });
+ } catch (Exception e) {
+ log.error("Error extracting images from RAR archive {}: {}", file.getName(), e.getMessage());
+ return List.of();
+ }
+ return images;
+ }
+
+ /**
+ * Extracts image entries from a ZIP archive (.cbz), sorted by entry name.
+ */
+ private List extractImagesFromZip(File file) {
+ List images = new ArrayList<>();
+ try (ZipFile zipFile = new ZipFile(file)) {
+ List extends ZipArchiveEntry> imageEntries = Collections.list(zipFile.getEntries()).stream()
+ .filter(e -> !e.isDirectory())
+ .filter(e -> e.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)"))
+ .sorted(Comparator.comparing(ZipArchiveEntry::getName))
+ .toList();
+ for (ZipArchiveEntry entry : imageEntries) {
+ try (InputStream is = zipFile.getInputStream(entry)) {
+ BufferedImage img = ImageIO.read(is);
+ if (img != null) {
+ images.add(img);
+ }
+ } catch (Exception e) {
+ log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage());
+ }
+ }
+ return images;
+ } catch (Exception e) {
+ log.error("Error extracting images from ZIP archive {}: {}", file.getName(), e.getMessage());
+ return List.of();
+ }
+ }
+
+ private List extractImagesFrom7z(File file) {
+ List images = new ArrayList<>();
+ try (SevenZFile sevenZFile = new SevenZFile(file)) {
+ List entries = new ArrayList<>();
+ SevenZArchiveEntry entry;
+ while ((entry = sevenZFile.getNextEntry()) != null) {
+ if (!entry.isDirectory() && entry.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)")) {
+ entries.add(entry);
+ }
+ }
+ entries.sort(Comparator.comparing(SevenZArchiveEntry::getName));
+ for (SevenZArchiveEntry e : entries) {
+ try {
+ byte[] content = new byte[(int) e.getSize()];
+ int offset = 0;
+ while (offset < content.length) {
+ int bytesRead = sevenZFile.read(content, offset, content.length - offset);
+ if (bytesRead < 0) {
+ break;
+ }
+ offset += bytesRead;
+ }
+ BufferedImage img = ImageIO.read(new java.io.ByteArrayInputStream(content));
+ if (img != null) {
+ images.add(img);
+ }
+ } catch (Exception ex) {
+ log.warn("Failed to read image from 7z entry {}: {}", e.getName(), ex.getMessage());
+ }
+ }
+ } catch (Exception e) {
+ log.error("Error extracting images from 7z archive {}: {}", file.getName(), e.getMessage());
+ return List.of();
+ }
+ return images;
+ }
+
+ private void setMetadata(BookEntity bookEntity) {
+ String baseName = new File(bookEntity.getFileName()).getName();
+ String title = baseName.replaceAll("(?i)\\.cb[sz7]$", "").replaceAll("[_\\-]", " ").trim();
+ bookEntity.getMetadata().setTitle(truncate(title, 1000));
+ }
+
+ private String truncate(String input, int maxLength) {
+ if (input == null) return null;
+ return input.length() <= maxLength ? input : input.substring(0, maxLength);
+ }
+}
\ No newline at end of file
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java
index 0603818aa..8e4ebdbbb 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java
@@ -91,23 +91,17 @@ public class AmazonBookParser implements BookParser {
Element link = item.select("a:containsOwn(" + type + ")").first();
if (link != null) {
bookLink = link.attr("href");
- //log.info("{} link found: {}", type, bookLink);
- break; // Take the first found link, whether Paperback or Hardcover
- } else {
- //log.info("No link containing '{}' found.", type);
+ break;
}
}
if (bookLink != null) {
return extractAsinFromUrl(bookLink);
} else {
- String asin = item.attr("data-asin");
- //log.info("No book link found, returning ASIN: {}", asin);
- return asin;
+ return item.attr("data-asin");
}
}
private String extractAsinFromUrl(String url) {
- // Extract the ASIN (book ID) from the URL, which will be the part after "/dp/"
String[] parts = url.split("/dp/");
if (parts.length > 1) {
String[] asinParts = parts[1].split("/");
@@ -184,7 +178,7 @@ public class AmazonBookParser implements BookParser {
if (titleElement != null) {
return titleElement.text();
}
- log.error("Error fetching title: Element not found.");
+ log.warn("Failed to parse title: Element not found.");
return null;
}
@@ -193,7 +187,7 @@ public class AmazonBookParser implements BookParser {
if (subtitleElement != null) {
return subtitleElement.text();
}
- log.debug("Error fetching subtitle: Element not found.");
+ log.warn("Failed to parse subtitle: Element not found.");
return null;
}
@@ -207,9 +201,9 @@ public class AmazonBookParser implements BookParser {
.map(Element::text)
.collect(Collectors.toSet());
}
- log.error("Error fetching authors: Byline element not found.");
+ log.warn("Failed to parse authors: Byline element not found.");
} catch (Exception e) {
- log.error("Error fetching authors: {}", e.getMessage());
+ log.warn("Failed to parse authors: {}", e.getMessage());
}
return Set.of();
}
@@ -224,7 +218,7 @@ public class AmazonBookParser implements BookParser {
}
return null;
} catch (Exception e) {
- log.error("Error extracting description from the document", e);
+ log.warn("Failed to parse description: {}", e.getMessage());
}
return null;
}
@@ -235,9 +229,9 @@ public class AmazonBookParser implements BookParser {
if (isbn10Element != null) {
return isbn10Element.text();
}
- log.debug("Error fetching ISBN-10: Element not found.");
+ log.warn("Failed to parse isbn10: Element not found.");
} catch (Exception e) {
- log.debug("Error fetching ISBN-10: {}", e.getMessage());
+ log.warn("Failed to parse isbn10: {}", e.getMessage());
}
return null;
}
@@ -248,9 +242,9 @@ public class AmazonBookParser implements BookParser {
if (isbn13Element != null) {
return isbn13Element.text();
}
- log.debug("Error fetching ISBN-13: Element not found.");
+ log.warn("Failed to parse isbn13: Element not found.");
} catch (Exception e) {
- log.debug("Error fetching ISBN-13: {}", e.getMessage());
+ log.warn("Failed to parse isbn13: {}", e.getMessage());
}
return null;
}
@@ -271,10 +265,10 @@ public class AmazonBookParser implements BookParser {
}
}
} else {
- log.warn("Error fetching publisher: Element 'detailBullets_feature_div' not found.");
+ log.warn("Failed to parse publisher: Element 'detailBullets_feature_div' not found.");
}
} catch (Exception e) {
- log.warn("Error fetching publisher: {}", e.getMessage());
+ log.warn("Failed to parse publisher: {}", e.getMessage());
}
return null;
}
@@ -285,9 +279,9 @@ public class AmazonBookParser implements BookParser {
if (publicationDateElement != null) {
return parseAmazonDate(publicationDateElement.text());
}
- log.warn("Error fetching publication date: Element not found.");
+ log.warn("Failed to parse publishedDate: Element not found.");
} catch (Exception e) {
- log.warn("Error fetching publication date: {}", e.getMessage());
+ log.warn("Failed to parse publishedDate: {}", e.getMessage());
}
return null;
}
@@ -298,10 +292,10 @@ public class AmazonBookParser implements BookParser {
if (seriesNameElement != null) {
return seriesNameElement.text();
} else {
- log.debug("Error fetching series name: Element not found.");
+ log.warn("Failed to parse seriesName: Element not found.");
}
} catch (Exception e) {
- log.debug("Error fetching series name: {}", e.getMessage());
+ log.warn("Failed to parse seriesName: {}", e.getMessage());
}
return null;
}
@@ -316,10 +310,10 @@ public class AmazonBookParser implements BookParser {
return Float.parseFloat(parts[1]);
}
} else {
- log.debug("Error fetching series number: Element not found.");
+ log.warn("Failed to parse seriesNumber: Element not found.");
}
} catch (Exception e) {
- log.debug("Error fetching series number: {}", e.getMessage());
+ log.warn("Failed to parse seriesNumber: {}", e.getMessage());
}
return null;
}
@@ -334,10 +328,10 @@ public class AmazonBookParser implements BookParser {
return Integer.parseInt(parts[3]);
}
} else {
- log.debug("Error fetching series total: Element not found.");
+ log.warn("Failed to parse seriesTotal: Element not found.");
}
} catch (Exception e) {
- log.debug("Error fetching series total: {}", e.getMessage());
+ log.warn("Failed to parse seriesTotal: {}", e.getMessage());
}
return null;
}
@@ -348,9 +342,9 @@ public class AmazonBookParser implements BookParser {
if (languageElement != null) {
return languageElement.text();
}
- log.warn("Error fetching language: Element not found.");
+ log.warn("Failed to parse language: Element not found.");
} catch (Exception e) {
- log.warn("Error fetching language: {}", e.getMessage());
+ log.warn("Failed to parse language: {}", e.getMessage());
}
return null;
}
@@ -366,9 +360,9 @@ public class AmazonBookParser implements BookParser {
.map(c -> c.replace("(Books)", "").trim())
.collect(Collectors.toSet());
}
- log.warn("Error fetching best seller categories: Element not found.");
+ log.warn("Failed to parse categories: Element not found.");
} catch (Exception e) {
- log.warn("Error fetching best seller categories: {}", e.getMessage());
+ log.warn("Failed to parse categories: {}", e.getMessage());
}
return Set.of();
}
@@ -386,7 +380,7 @@ public class AmazonBookParser implements BookParser {
}
}
} catch (Exception e) {
- log.warn("Error fetching rating", e);
+ log.warn("Failed to parse amazonRating: {}", e.getMessage());
}
return null;
}
@@ -405,7 +399,7 @@ public class AmazonBookParser implements BookParser {
}
}
} catch (Exception e) {
- log.warn("Error fetching review count", e);
+ log.warn("Failed to parse amazonReviewCount: {}", e.getMessage());
}
return null;
}
@@ -416,9 +410,9 @@ public class AmazonBookParser implements BookParser {
if (imageElement != null) {
return imageElement.attr("src");
}
- log.warn("Error fetching image URL: Image element not found.");
+ log.warn("Failed to parse thumbnail: Image element not found.");
} catch (Exception e) {
- log.warn("Error fetching image URL: {}", e.getMessage());
+ log.warn("Failed to parse thumbnail: {}", e.getMessage());
}
return null;
}
@@ -432,7 +426,7 @@ public class AmazonBookParser implements BookParser {
String cleanedPageCount = pageCountText.replaceAll("[^\\d]", "");
return Integer.parseInt(cleanedPageCount);
} catch (NumberFormatException e) {
- log.warn("Error parsing page count: {}", pageCountText, e);
+ log.warn("Error parsing page count: {}, error: {}", pageCountText, e.getMessage());
}
}
}
@@ -485,7 +479,7 @@ public class AmazonBookParser implements BookParser {
document.select("span.a-text-bold").tagName("b").removeAttr("class");
document.select("span.a-text-italic").tagName("i").removeAttr("class");
for (Element span : document.select("span.a-list-item")) {
- span.unwrap(); // Removes the span and keeps its content
+ span.unwrap();
}
document.select("ol.a-ordered-list.a-vertical").tagName("ol").removeAttr("class");
document.select("ul.a-unordered-list.a-vertical").tagName("ul").removeAttr("class");
@@ -493,13 +487,10 @@ public class AmazonBookParser implements BookParser {
span.unwrap();
}
document.select("li").forEach(li -> {
- // Remove
tags preceding the (if any)
Element prev = li.previousElementSibling();
if (prev != null && "br".equals(prev.tagName())) {
prev.remove();
}
-
- // Remove
tags following the (if any)
Element next = li.nextElementSibling();
if (next != null && "br".equals(next.tagName())) {
next.remove();
@@ -510,7 +501,7 @@ public class AmazonBookParser implements BookParser {
.forEach(Element::remove);
return document.body().html();
} catch (Exception e) {
- log.warn("Error cleaning html description", e);
+ log.warn("Error cleaning html description, Error: {}", e.getMessage());
}
return html;
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java
index fecf8d588..b0e0db9b0 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java
@@ -9,6 +9,8 @@ import com.adityachandel.booklore.model.dto.settings.OidcAutoProvisionDetails;
import com.adityachandel.booklore.model.dto.settings.SidebarSortOption;
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
import com.adityachandel.booklore.model.entity.*;
+import com.adityachandel.booklore.model.enums.CbxPageSpread;
+import com.adityachandel.booklore.model.enums.CbxPageViewMode;
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.repository.ShelfRepository;
@@ -179,6 +181,7 @@ public class UserProvisioningService {
addUserSetting(user, UserSettingKey.PER_BOOK_SETTING, buildDefaultPerBookSetting());
addUserSetting(user, UserSettingKey.PDF_READER_SETTING, buildDefaultPdfReaderSetting());
addUserSetting(user, UserSettingKey.EPUB_READER_SETTING, buildDefaultEpubReaderSetting());
+ addUserSetting(user, UserSettingKey.CBX_READER_SETTING, buildDefaultEpubReaderSetting());
addUserSetting(user, UserSettingKey.SIDEBAR_LIBRARY_SORTING, buildDefaultSidebarLibrarySorting());
addUserSetting(user, UserSettingKey.SIDEBAR_SHELF_SORTING, buildDefaultSidebarShelfSorting());
@@ -222,6 +225,13 @@ public class UserProvisioningService {
.build();
}
+ private BookLoreUser.UserSettings.CbxReaderSetting buildDefaultCbxReaderSetting() {
+ return BookLoreUser.UserSettings.CbxReaderSetting.builder()
+ .pageViewMode(CbxPageViewMode.SINGLE_PAGE)
+ .pageSpread(CbxPageSpread.ODD)
+ .build();
+ }
+
private Object buildDefaultSidebarLibrarySorting() {
return SidebarSortOption.builder()
.field("id")
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java
index 9e3467706..284ae5b16 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java
@@ -118,6 +118,10 @@ public class FileService {
return appProperties.getPathConfig() + "/thumbs/" + bookId + "/";
}
+ public String getCbxCachePath() {
+ return appProperties.getPathConfig() + "/cbx_cache";
+ }
+
public String getMissingThumbnailPath() {
return appProperties.getPathConfig() + "/thumbs/missing/m.jpg";
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java
index b79261ab0..a997634e2 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java
@@ -3,9 +3,11 @@ package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.BookEntity;
import lombok.extern.slf4j.Slf4j;
+import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.Comparator;
import java.util.Optional;
@Slf4j
@@ -45,4 +47,14 @@ public class FileUtils {
return null;
}
}
+
+ public static void deleteDirectoryRecursively(Path path) throws IOException {
+ if (!Files.exists(path)) return;
+
+ try (var walk = Files.walk(path)) {
+ walk.sorted(Comparator.reverseOrder())
+ .map(Path::toFile)
+ .forEach(File::delete);
+ }
+ }
}
\ No newline at end of file
diff --git a/booklore-api/src/main/resources/application.yaml b/booklore-api/src/main/resources/application.yaml
index 1a4ae64c9..7bf058097 100644
--- a/booklore-api/src/main/resources/application.yaml
+++ b/booklore-api/src/main/resources/application.yaml
@@ -14,9 +14,7 @@ app:
spring:
servlet:
multipart:
- enabled: true
- max-file-size: 100MB
- max-request-size: 100MB
+ enabled: false
mvc:
async:
request-timeout: 600000
diff --git a/booklore-api/src/main/resources/db/migration/V22__Create_cbx_viewer_table.sql b/booklore-api/src/main/resources/db/migration/V22__Create_cbx_viewer_table.sql
new file mode 100644
index 000000000..148e6599e
--- /dev/null
+++ b/booklore-api/src/main/resources/db/migration/V22__Create_cbx_viewer_table.sql
@@ -0,0 +1,9 @@
+CREATE TABLE IF NOT EXISTS cbx_viewer_preference
+(
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ user_id BIGINT NOT NULL,
+ book_id BIGINT NOT NULL,
+ spread VARCHAR(16) NULL,
+ view_mode VARCHAR(16) NULL,
+ UNIQUE (user_id, book_id)
+);
\ No newline at end of file
diff --git a/booklore-api/src/main/resources/db/migration/V23__Add_cbx_progress_to_user_book_progress.sql b/booklore-api/src/main/resources/db/migration/V23__Add_cbx_progress_to_user_book_progress.sql
new file mode 100644
index 000000000..33e85cc7c
--- /dev/null
+++ b/booklore-api/src/main/resources/db/migration/V23__Add_cbx_progress_to_user_book_progress.sql
@@ -0,0 +1,3 @@
+ALTER TABLE user_book_progress
+ ADD COLUMN cbx_progress INT NULL,
+ ADD COLUMN cbx_progress_percent FLOAT NULL;
\ No newline at end of file
diff --git a/booklore-ui/src/app/app.routes.ts b/booklore-ui/src/app/app.routes.ts
index 9b7218da4..f97a7cd29 100644
--- a/booklore-ui/src/app/app.routes.ts
+++ b/booklore-ui/src/app/app.routes.ts
@@ -15,6 +15,7 @@ import {SetupRedirectGuard} from './core/setup/setup-redirect.guard';
import {EmptyComponent} from './core/empty/empty.component';
import {LoginGuard} from './core/setup/ login.guard';
import {OidcCallbackComponent} from './core/security/oidc-callback/oidc-callback.component';
+import {CbxReaderComponent} from './book/components/cbx-reader/cbx-reader.component';
export const routes: Routes = [
{
@@ -52,6 +53,11 @@ export const routes: Routes = [
component: EpubViewerComponent,
canActivate: [AuthGuard]
},
+ {
+ path: 'cbx-viewer/book/:bookId',
+ component: CbxReaderComponent,
+ canActivate: [AuthGuard]
+ },
{
path: 'login',
component: LoginComponent,
diff --git a/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.html b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.html
new file mode 100644
index 000000000..38a16ec60
--- /dev/null
+++ b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.html
@@ -0,0 +1,35 @@
+
+
+
+
+
+ Page {{ currentPage + 1 }}{{ isTwoPageView && imageUrls.length > 1 ? '-' + (currentPage + 2) : '' }} of {{ pages.length }}
+
+
+
+
+
+
+
+
+
+
+
+ 0; else noPages">
+
+
+
+
+ No pages available.
+
+
+
+
+
+
diff --git a/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.scss b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.scss
new file mode 100644
index 000000000..0aead1209
--- /dev/null
+++ b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.scss
@@ -0,0 +1,96 @@
+.comic-reader-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ height: 100vh;
+ width: 100vw;
+ overflow-x: hidden;
+ box-sizing: border-box;
+
+ .navigation {
+ position: relative;
+ width: 100%;
+ margin: 1rem;
+
+ .page-controls {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ display: flex;
+ gap: 1rem;
+ align-items: center;
+ white-space: nowrap;
+
+ span {
+ min-width: 8rem;
+ display: inline-block;
+ text-align: center;
+ font-variant-numeric: tabular-nums;
+ }
+
+ button {
+ min-width: 3rem;
+ padding: 0 0.5rem;
+ text-align: center;
+ white-space: nowrap;
+ cursor: pointer;
+
+ &:disabled {
+ cursor: default;
+ color: #999;
+ }
+ }
+ }
+
+ .spread-controls {
+ position: absolute;
+ right: 0;
+ top: 50%;
+ transform: translateY(-50%);
+ display: flex;
+ gap: 0.5rem;
+ align-items: center;
+
+ button {
+ padding-left: 0.5rem;
+ padding-right: 0.5rem;
+ }
+ }
+ }
+
+ .image-container {
+ flex-grow: 1;
+ width: 100%;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ gap: 1rem;
+ overflow: hidden;
+ padding: 0 1rem;
+ box-sizing: border-box;
+
+ &.two-page-view {
+ img {
+ max-width: calc(50% - 0.5rem);
+ }
+ }
+
+ &:not(.two-page-view) {
+ img {
+ max-width: 100%;
+ }
+ }
+
+ img {
+ max-height: 100%;
+ height: auto;
+ width: auto;
+ object-fit: contain;
+ box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
+ flex-shrink: 1;
+ margin: 0;
+ display: block;
+ }
+ }
+}
diff --git a/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.ts b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.ts
new file mode 100644
index 000000000..61665149d
--- /dev/null
+++ b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.ts
@@ -0,0 +1,195 @@
+import {Component, HostListener, inject, OnInit} from '@angular/core';
+import {NgFor, NgIf} from '@angular/common';
+import {ActivatedRoute} from '@angular/router';
+import {CbxReaderService} from '../../service/cbx-reader.service';
+import {BookService} from '../../service/book.service';
+import {UserService} from '../../../settings/user-management/user.service';
+import {MessageService} from 'primeng/api';
+import {forkJoin} from 'rxjs';
+import {BookSetting, CbxPageSpread, CbxPageViewMode} from '../../model/book.model';
+import {ProgressSpinner} from 'primeng/progressspinner';
+
+@Component({
+ selector: 'app-cbx-reader',
+ standalone: true,
+ imports: [NgIf, NgFor, ProgressSpinner],
+ templateUrl: './cbx-reader.component.html',
+ styleUrl: './cbx-reader.component.scss'
+})
+export class CbxReaderComponent implements OnInit {
+ bookId!: number;
+ pages: number[] = [];
+ currentPage = 0;
+ isLoading = true;
+
+ pageSpread: CbxPageSpread = CbxPageSpread.ODD;
+ pageViewMode: CbxPageViewMode = CbxPageViewMode.SINGLE_PAGE;
+
+ private touchStartX = 0;
+ private touchEndX = 0;
+
+ private route = inject(ActivatedRoute);
+ private cbxReaderService = inject(CbxReaderService);
+ private bookService = inject(BookService);
+ private userService = inject(UserService);
+ private messageService = inject(MessageService);
+
+ ngOnInit() {
+ this.route.paramMap.subscribe((params) => {
+ this.isLoading = true;
+ this.bookId = +params.get('bookId')!;
+
+ forkJoin([
+ this.bookService.getBookByIdFromAPI(this.bookId, false),
+ this.bookService.getBookSetting(this.bookId),
+ this.userService.getMyself(),
+ this.cbxReaderService.getAvailablePages(this.bookId)
+ ]).subscribe({
+ next: ([cbxMeta, bookSettings, myself, pages]) => {
+ const userSettings = myself.userSettings;
+ const global = userSettings.perBookSetting.cbx === 'Global';
+
+ this.pageViewMode = global
+ ? userSettings.cbxReaderSetting.pageViewMode || CbxPageViewMode.SINGLE_PAGE
+ : bookSettings.cbxSettings?.pageViewMode || userSettings.cbxReaderSetting.pageViewMode || CbxPageViewMode.SINGLE_PAGE;
+
+ this.pageSpread = global
+ ? userSettings.cbxReaderSetting.pageSpread || CbxPageSpread.ODD
+ : bookSettings.cbxSettings?.pageSpread || userSettings.cbxReaderSetting.pageSpread || CbxPageSpread.ODD;
+
+ this.pages = pages;
+ this.currentPage = (cbxMeta.cbxProgress?.page || 1) - 1;
+ this.alignCurrentPageToParity();
+ this.isLoading = false;
+ },
+ error: (err) => {
+ const errorMessage = err?.error?.message || 'Failed to load the book';
+ this.messageService.add({severity: 'error', summary: 'Error', detail: errorMessage});
+ this.isLoading = false;
+ }
+ });
+ });
+ }
+
+ get isTwoPageView(): boolean {
+ return this.pageViewMode === CbxPageViewMode.TWO_PAGE;
+ }
+
+ toggleView() {
+ if (!this.isTwoPageView && this.isPhonePortrait()) return;
+ this.pageViewMode = this.isTwoPageView ? CbxPageViewMode.SINGLE_PAGE : CbxPageViewMode.TWO_PAGE;
+ this.alignCurrentPageToParity();
+ this.updateViewerSetting();
+ }
+
+ toggleSpreadDirection() {
+ this.pageSpread = this.pageSpread === CbxPageSpread.ODD ? CbxPageSpread.EVEN : CbxPageSpread.ODD;
+ this.alignCurrentPageToParity();
+ this.updateViewerSetting();
+ }
+
+ nextPage() {
+ if (this.isTwoPageView) {
+ this.currentPage += (this.currentPage < this.pages.length - 2) ? 2 : 1;
+ } else if (this.currentPage < this.pages.length - 1) {
+ this.currentPage++;
+ }
+ this.updateProgress();
+ }
+
+ previousPage() {
+ if (this.isTwoPageView) {
+ this.currentPage = Math.max(0, this.currentPage - 2);
+ } else {
+ this.currentPage = Math.max(0, this.currentPage - 1);
+ }
+ this.updateProgress();
+ }
+
+ private alignCurrentPageToParity() {
+ if (!this.pages.length || !this.isTwoPageView) return;
+
+ const desiredOdd = this.pageSpread === CbxPageSpread.ODD;
+ for (let i = this.currentPage; i >= 0; i--) {
+ if ((this.pages[i] % 2 === 1) === desiredOdd) {
+ this.currentPage = i;
+ this.updateProgress();
+ return;
+ }
+ }
+ for (let i = 0; i < this.pages.length; i++) {
+ if ((this.pages[i] % 2 === 1) === desiredOdd) {
+ this.currentPage = i;
+ this.updateProgress();
+ return;
+ }
+ }
+ }
+
+ @HostListener('window:keydown', ['$event'])
+ handleKeyDown(event: KeyboardEvent) {
+ if (event.key === 'ArrowRight') this.nextPage();
+ else if (event.key === 'ArrowLeft') this.previousPage();
+ }
+
+ @HostListener('touchstart', ['$event'])
+ onTouchStart(event: TouchEvent) {
+ this.touchStartX = event.changedTouches[0].screenX;
+ }
+
+ @HostListener('touchend', ['$event'])
+ onTouchEnd(event: TouchEvent) {
+ this.touchEndX = event.changedTouches[0].screenX;
+ this.handleSwipeGesture();
+ }
+
+ @HostListener('window:resize')
+ onResize() {
+ this.enforcePortraitSinglePageView();
+ }
+
+ private handleSwipeGesture() {
+ const delta = this.touchEndX - this.touchStartX;
+ if (Math.abs(delta) >= 50) delta < 0 ? this.nextPage() : this.previousPage();
+ }
+
+ private enforcePortraitSinglePageView() {
+ if (this.isPhonePortrait() && this.isTwoPageView) {
+ this.pageViewMode = CbxPageViewMode.SINGLE_PAGE;
+ this.updateViewerSetting();
+ }
+ }
+
+ private isPhonePortrait(): boolean {
+ return window.innerWidth < 768 && window.innerHeight > window.innerWidth;
+ }
+
+ get imageUrls(): string[] {
+ if (!this.pages.length) return [];
+
+ const urls = [this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[this.currentPage])];
+ if (this.isTwoPageView && this.currentPage + 1 < this.pages.length) {
+ urls.push(this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[this.currentPage + 1]));
+ }
+
+ return urls;
+ }
+
+ private updateViewerSetting(): void {
+ const bookSetting: BookSetting = {
+ cbxSettings: {
+ pageSpread: this.pageSpread,
+ pageViewMode: this.pageViewMode,
+ }
+ }
+ this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
+ }
+
+ updateProgress(): void {
+ const percentage = this.pages.length > 0
+ ? Math.round(((this.currentPage + 1) / this.pages.length) * 1000) / 10
+ : 0;
+
+ this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
+ }
+}
diff --git a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html
index 14d429693..e611ad852 100644
--- a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html
+++ b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html
@@ -129,28 +129,7 @@
- 0">
-
-
-
0">
-
diff --git a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts
index 2adf064ad..91e38a6bb 100644
--- a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts
+++ b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts
@@ -1,4 +1,4 @@
-import {Component, DestroyRef, inject, Input, OnInit, ViewChild} from '@angular/core';
+import {Component, DestroyRef, inject, Input, OnInit, OnChanges, SimpleChanges, ViewChild} from '@angular/core';
import {Button, ButtonDirective} from 'primeng/button';
import {AsyncPipe, DecimalPipe, NgClass, NgForOf, NgIf} from '@angular/common';
import {first, Observable} from 'rxjs';
@@ -31,10 +31,11 @@ import {ProgressBar} from 'primeng/progressbar';
styleUrl: './metadata-viewer.component.scss',
imports: [Button, NgForOf, NgIf, AsyncPipe, Rating, FormsModule, Tag, Divider, SplitButton, NgClass, Tooltip, DecimalPipe, InfiniteScrollDirective, BookCardComponent, ButtonDirective, Editor, ProgressBar]
})
-export class MetadataViewerComponent implements OnInit {
+export class MetadataViewerComponent implements OnInit, OnChanges {
@Input() book: Book | undefined;
@Input() recommendedBooks: BookRecommendation[] = [];
+ private originalRecommendedBooks: BookRecommendation[] = [];
@ViewChild(Editor) quillEditor!: Editor;
@@ -81,7 +82,7 @@ export class MetadataViewerComponent implements OnInit {
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((metadata) => {
if (metadata) {
- this.getBooksInSeries(metadata.bookId);
+ this.loadBooksInSeriesAndFilterRecommended(metadata.bookId);
if (this.quillEditor && this.quillEditor.quill) {
this.quillEditor.quill.root.innerHTML = metadata.description;
}
@@ -89,14 +90,34 @@ export class MetadataViewerComponent implements OnInit {
});
}
- toggleExpand(): void {
- this.isExpanded = !this.isExpanded;
+ private loadBooksInSeriesAndFilterRecommended(bookId: number): void {
+ this.bookService.getBooksInSeries(bookId).subscribe((bookInSeries) => {
+ bookInSeries.sort((a, b) => (a.metadata?.seriesNumber ?? 0) - (b.metadata?.seriesNumber ?? 0));
+ this.bookInSeries = bookInSeries;
+ this.originalRecommendedBooks = [...this.recommendedBooks];
+ this.filterRecommendations();
+ });
}
- getBooksInSeries(bookId: number): void {
- this.bookService.getBooksInSeries(bookId).subscribe((bookInSeries) => {
- this.bookInSeries = bookInSeries;
- });
+ ngOnChanges(changes: SimpleChanges): void {
+ if (changes['recommendedBooks']) {
+ this.originalRecommendedBooks = [...this.recommendedBooks];
+ this.filterRecommendations();
+ }
+ }
+
+ private filterRecommendations(): void {
+ if (!this.originalRecommendedBooks) {
+ return;
+ }
+ const bookInSeriesIds = new Set(this.bookInSeries.map(book => book.id));
+ this.recommendedBooks = this.originalRecommendedBooks.filter(
+ rec => !bookInSeriesIds.has(rec.book.id)
+ );
+ }
+
+ toggleExpand(): void {
+ this.isExpanded = !this.isExpanded;
}
read(bookId: number): void {
@@ -168,6 +189,8 @@ export class MetadataViewerComponent implements OnInit {
getProgressPercent(): number | undefined {
if (this.book?.bookType === 'PDF') {
return this.book.pdfProgress?.percentage;
+ } else if(this.book?.bookType === 'CBX') {
+ return this.book?.cbxProgress?.percentage;
} else {
return this.book?.epubProgress?.percentage;
}
diff --git a/booklore-ui/src/app/book/model/book.model.ts b/booklore-ui/src/app/book/model/book.model.ts
index 064c2724c..3e3d2daa3 100644
--- a/booklore-ui/src/app/book/model/book.model.ts
+++ b/booklore-ui/src/app/book/model/book.model.ts
@@ -1,6 +1,6 @@
import {Shelf} from './shelf.model';
-export type BookType = "PDF" | "EPUB";
+export type BookType = "PDF" | "EPUB" | "CBX";
export interface Book {
id: number;
@@ -12,6 +12,7 @@ export interface Book {
addedOn?: string;
epubProgress?: EpubProgress;
pdfProgress?: PdfProgress;
+ cbxProgress?: CbxProgress;
filePath?: string;
fileSizeKb?: number;
}
@@ -26,6 +27,11 @@ export interface PdfProgress {
percentage: number;
}
+export interface CbxProgress {
+ page: number;
+ percentage: number;
+}
+
export interface BookMetadata {
bookId: number;
title: string;
@@ -102,9 +108,15 @@ export interface EpubViewerSetting {
flow: string;
}
+export interface CbxViewerSetting {
+ pageSpread: CbxPageSpread;
+ pageViewMode: CbxPageViewMode;
+}
+
export interface BookSetting {
pdfSettings?: PdfViewerSetting;
epubSettings?: EpubViewerSetting;
+ cbxSettings?: CbxViewerSetting;
[key: string]: any;
}
@@ -113,3 +125,13 @@ export interface BookRecommendation {
book: Book;
similarityScore: number;
}
+
+export const enum CbxPageViewMode {
+ SINGLE_PAGE = 'SINGLE_PAGE',
+ TWO_PAGE = 'TWO_PAGE',
+}
+
+export const enum CbxPageSpread {
+ EVEN = 'EVEN',
+ ODD = 'ODD',
+}
diff --git a/booklore-ui/src/app/book/service/book.service.ts b/booklore-ui/src/app/book/service/book.service.ts
index 2cb781147..fe30fbff3 100644
--- a/booklore-ui/src/app/book/service/book.service.ts
+++ b/booklore-ui/src/app/book/service/book.service.ts
@@ -128,6 +128,10 @@ export class BookService {
const url = `/epub-viewer/book/${book.id}`;
window.open(url, '_blank');
this.updateLastReadTime(book.id);
+ } else if (book.bookType === "CBX") {
+ const url = `/cbx-viewer/book/${book.id}`;
+ window.open(url, '_blank');
+ this.updateLastReadTime(book.id);
} else {
console.error('Unsupported book type:', book.bookType);
}
@@ -207,6 +211,17 @@ export class BookService {
return this.http.post(`${this.url}/progress`, body);
}
+ saveCbxProgress(bookId: number, page: number, percentage: number): Observable {
+ const body = {
+ bookId: bookId,
+ cbxProgress: {
+ page: page,
+ percentage: percentage
+ }
+ };
+ return this.http.post(`${this.url}/progress`, body);
+ }
+
regenerateCovers(): Observable {
return this.http.post(`${this.url}/regenerate-covers`, {});
}
diff --git a/booklore-ui/src/app/book/service/cbx-reader.service.ts b/booklore-ui/src/app/book/service/cbx-reader.service.ts
new file mode 100644
index 000000000..f5bb64203
--- /dev/null
+++ b/booklore-ui/src/app/book/service/cbx-reader.service.ts
@@ -0,0 +1,19 @@
+import { HttpClient } from '@angular/common/http';
+import { Injectable } from '@angular/core';
+import {API_CONFIG} from '../../config/api-config';
+
+@Injectable({ providedIn: 'root' })
+export class CbxReaderService {
+
+ private readonly url = `${API_CONFIG.BASE_URL}/api/v1/cbx`;
+
+ constructor(private http: HttpClient) {}
+
+ getAvailablePages(bookId: number) {
+ return this.http.get(`${this.url}/${bookId}/pages`);
+ }
+
+ getPageImageUrl(bookId: number, page: number): string {
+ return `${this.url}/${bookId}/pages/${page}`;
+ }
+}
diff --git a/booklore-ui/src/app/core/model/app-settings.model.ts b/booklore-ui/src/app/core/model/app-settings.model.ts
index 1e2646adf..838bfaedf 100644
--- a/booklore-ui/src/app/core/model/app-settings.model.ts
+++ b/booklore-ui/src/app/core/model/app-settings.model.ts
@@ -29,6 +29,8 @@ export interface AppSettings {
oidcEnabled: boolean;
oidcProviderDetails: OidcProviderDetails;
oidcAutoProvisionDetails: OidcAutoProvisionDetails;
+ cbxCacheSizeInMb: number;
+ maxFileUploadSizeInMb: number;
}
export enum AppSettingKey {
@@ -40,5 +42,7 @@ export enum AppSettingKey {
OPDS_SERVER_ENABLED = 'OPDS_SERVER_ENABLED',
OIDC_ENABLED = 'OIDC_ENABLED',
OIDC_PROVIDER_DETAILS = 'OIDC_PROVIDER_DETAILS',
- OIDC_AUTO_PROVISION_DETAILS = 'OIDC_AUTO_PROVISION_DETAILS'
+ OIDC_AUTO_PROVISION_DETAILS = 'OIDC_AUTO_PROVISION_DETAILS',
+ CBX_CACHE_SIZE_IN_MB = 'CBX_CACHE_SIZE_IN_MB',
+ MAX_FILE_UPLOAD_SIZE_IN_MB = 'MAX_FILE_UPLOAD_SIZE_IN_MB'
}
diff --git a/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html b/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html
index 9c2b6fffe..0db5dde55 100644
--- a/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html
+++ b/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html
@@ -13,14 +13,13 @@
Resolution:
Regenerate Covers?
@@ -50,7 +49,7 @@
Auto Book Search
@@ -68,7 +67,7 @@
Similar Book Recommendation
@@ -89,6 +88,55 @@
+
+
+
Max File Upload Size:
+
+
+
+
+
+
+
CBX Cache Size:
+
+
+
+
+
+
+
+
+
@@ -114,7 +162,8 @@
style="cursor: pointer;">
-
+
diff --git a/booklore-ui/src/app/settings/global-preferences/global-preferences.component.ts b/booklore-ui/src/app/settings/global-preferences/global-preferences.component.ts
index 1fd2b8edc..303a76eea 100644
--- a/booklore-ui/src/app/settings/global-preferences/global-preferences.component.ts
+++ b/booklore-ui/src/app/settings/global-preferences/global-preferences.component.ts
@@ -18,6 +18,7 @@ import {MetadataAdvancedFetchOptionsComponent} from '../../book/metadata/metadat
import {filter, take} from 'rxjs/operators';
import {FileUploadPatternComponent} from './file-upload-pattern/file-upload-pattern.component';
import {OpdsSettingsComponent} from './opds-settings/opds-settings.component';
+import {InputText} from 'primeng/inputtext';
@Component({
selector: 'app-global-preferences',
@@ -32,7 +33,8 @@ import {OpdsSettingsComponent} from './opds-settings/opds-settings.component';
FormsModule,
MetadataAdvancedFetchOptionsComponent,
FileUploadPatternComponent,
- OpdsSettingsComponent
+ OpdsSettingsComponent,
+ InputText
],
templateUrl: './global-preferences.component.html',
styleUrl: './global-preferences.component.scss'
@@ -59,6 +61,8 @@ export class GlobalPreferencesComponent implements OnInit {
private messageService = inject(MessageService);
appSettings$: Observable
= this.appSettingsService.appSettings$;
+ cbxCacheValue?: number;
+ maxFileUploadSizeInMb?: number;
ngOnInit(): void {
this.appSettings$.pipe(
@@ -68,9 +72,15 @@ export class GlobalPreferencesComponent implements OnInit {
if (settings?.coverResolution) {
this.selectedResolution = settings.coverResolution;
}
- if (settings.metadataRefreshOptions) {
+ if (settings?.metadataRefreshOptions) {
this.currentMetadataOptions = settings.metadataRefreshOptions;
}
+ if (settings?.cbxCacheSizeInMb) {
+ this.cbxCacheValue = settings.cbxCacheSizeInMb;
+ }
+ if (settings?.maxFileUploadSizeInMb) {
+ this.maxFileUploadSizeInMb = settings.maxFileUploadSizeInMb;
+ }
this.toggles.autoBookSearch = settings.autoBookSearch ?? false;
this.toggles.similarBookRecommendation = settings.similarBookRecommendation ?? false;
});
@@ -98,6 +108,23 @@ export class GlobalPreferencesComponent implements OnInit {
this.saveSetting(AppSettingKey.QUICK_BOOK_MATCH, metadataRefreshOptions);
}
+ saveCacheSize(): void {
+ if (!this.cbxCacheValue || this.cbxCacheValue <= 0) {
+ this.showMessage('error', 'Invalid Input', 'Please enter a valid cache size in MB.');
+ return;
+ }
+
+ this.saveSetting(AppSettingKey.CBX_CACHE_SIZE_IN_MB, this.cbxCacheValue);
+ }
+
+ saveFileSize() {
+ if (!this.maxFileUploadSizeInMb || this.maxFileUploadSizeInMb <= 0) {
+ this.showMessage('error', 'Invalid Input', 'Please enter a valid max file upload size in MB.');
+ return;
+ }
+ this.saveSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, this.maxFileUploadSizeInMb);
+ }
+
regenerateCovers(): void {
this.bookService.regenerateCovers().subscribe({
next: () =>
diff --git a/booklore-ui/src/app/settings/user-management/user.service.ts b/booklore-ui/src/app/settings/user-management/user.service.ts
index 689ce06be..0e2665490 100644
--- a/booklore-ui/src/app/settings/user-management/user.service.ts
+++ b/booklore-ui/src/app/settings/user-management/user.service.ts
@@ -5,6 +5,7 @@ import {API_CONFIG} from '../../config/api-config';
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
import {Library} from '../../book/model/library.model';
import {catchError} from 'rxjs/operators';
+import {CbxPageSpread, CbxPageViewMode} from '../../book/model/book.model';
export interface SidebarLibrarySorting {
field: string;
@@ -19,6 +20,7 @@ export interface SidebarShelfSorting {
export interface PerBookSetting {
pdf: string;
epub: string;
+ cbx: string;
}
export type PageSpread = 'off' | 'even' | 'odd';
@@ -36,10 +38,16 @@ export interface EpubReaderSetting {
flow: string;
}
+export interface CbxReaderSetting {
+ pageSpread: CbxPageSpread;
+ pageViewMode: CbxPageViewMode;
+}
+
export interface UserSettings {
perBookSetting: PerBookSetting;
pdfReaderSetting: PdfReaderSetting;
epubReaderSetting: EpubReaderSetting;
+ cbxReaderSetting: CbxReaderSetting;
sidebarLibrarySorting: SidebarLibrarySorting;
sidebarShelfSorting: SidebarShelfSorting
}
diff --git a/booklore-ui/src/app/settings/user-preferences/user-preferences.component.html b/booklore-ui/src/app/settings/user-preferences/user-preferences.component.html
index f9704a735..5c3947d47 100644
--- a/booklore-ui/src/app/settings/user-preferences/user-preferences.component.html
+++ b/booklore-ui/src/app/settings/user-preferences/user-preferences.component.html
@@ -38,6 +38,20 @@
+
+ CBX:
+
@@ -97,12 +111,13 @@
Theme:
@@ -110,12 +125,13 @@
Font:
@@ -123,21 +139,64 @@
Flow:
Font Size:
-
+
{{ fontSize }}%
-
+
+
+
+
+
+
+
+
+
+ CBX Reader: Global Preferences
+
+
+
+
+
Page Spread:
+
+
+
+
+
+
+
+
+
Page Zoom:
+
@@ -164,6 +223,7 @@
@@ -101,7 +101,9 @@
Drag and drop files here to upload.
-
Only .epub and .pdf files are supported (max size: 100 MB per file).
+
+ Only .pdf, .epub, .cbz, .cbr, and .cb7 files are supported (max size: 100 MB per file).
+
diff --git a/booklore-ui/src/app/utilities/component/book-uploader/book-uploader.component.ts b/booklore-ui/src/app/utilities/component/book-uploader/book-uploader.component.ts
index 904333063..4bae722b3 100644
--- a/booklore-ui/src/app/utilities/component/book-uploader/book-uploader.component.ts
+++ b/booklore-ui/src/app/utilities/component/book-uploader/book-uploader.component.ts
@@ -1,4 +1,4 @@
-import {Component, inject} from '@angular/core';
+import {Component, inject, OnInit} from '@angular/core';
import {FileSelectEvent, FileUpload, FileUploadHandlerEvent} from 'primeng/fileupload';
import {Button} from 'primeng/button';
import {AsyncPipe, NgForOf, NgIf, NgSwitch, NgSwitchCase} from '@angular/common';
@@ -14,6 +14,9 @@ import {API_CONFIG} from '../../../config/api-config';
import {Book} from '../../../book/model/book.model';
import {HttpClient} from '@angular/common/http';
import {Tooltip} from 'primeng/tooltip';
+import {AppSettingsService} from '../../../core/service/app-settings.service';
+import {filter, take} from 'rxjs/operators';
+import {AppSettings} from '../../../core/model/app-settings.model';
interface UploadingFile {
file: File;
@@ -40,7 +43,7 @@ interface UploadingFile {
templateUrl: './book-uploader.component.html',
styleUrl: './book-uploader.component.scss'
})
-export class BookUploaderComponent {
+export class BookUploaderComponent implements OnInit {
files: UploadingFile[] = [];
isUploading: boolean = false;
selectedLibrary: Library | null = null;
@@ -48,9 +51,23 @@ export class BookUploaderComponent {
private readonly libraryService = inject(LibraryService);
private readonly messageService = inject(MessageService);
+ private readonly appSettingsService = inject(AppSettingsService);
private readonly http = inject(HttpClient);
readonly libraryState$: Observable
= this.libraryService.libraryState$;
+ appSettings$: Observable = this.appSettingsService.appSettings$;
+ maxFileSizeBytes?: number;
+
+ ngOnInit(): void {
+ this.appSettings$
+ .pipe(
+ filter(settings => settings != null),
+ take(1)
+ )
+ .subscribe(settings => {
+ this.maxFileSizeBytes = (settings?.maxFileUploadSizeInMb ?? 100) * 1024 * 1024;
+ });
+ }
hasPendingFiles(): boolean {
return this.files.some(f => f.status === 'Pending');
From 93f15720fea5119158b9107a4d2d2a4fea1421dc Mon Sep 17 00:00:00 2001
From: "aditya.chandel" <>
Date: Fri, 23 May 2025 23:43:02 -0600
Subject: [PATCH 03/10] Fix event handling
---
.../booklore/service/LibraryProcessingService.java | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java
index fa2749e26..15fcf4244 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/LibraryProcessingService.java
@@ -159,8 +159,14 @@ public class LibraryProcessingService {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName()));
detectMovedBooksAndUpdatePaths(libraryEntity);
+ entityManager.flush();
+ entityManager.clear();
deleteRemovedBooks(detectDeletedBookIds(libraryEntity));
+ entityManager.flush();
+ entityManager.clear();
processLibraryFiles(detectNewBookPaths(libraryEntity));
+ entityManager.flush();
+ entityManager.clear();
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
}
@@ -207,7 +213,9 @@ public class LibraryProcessingService {
protected void deleteRemovedBooks(List bookIds) {
bookRepository.deleteByIdIn(bookIds);
notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
- log.info("Books removed: {}", bookIds);
+ if (bookIds.size() > 1) {
+ log.info("Books removed: {}", bookIds);
+ }
}
@Transactional
From 3921d420149ad1d000ed956b69ecaec20cfb0083 Mon Sep 17 00:00:00 2001
From: Alex Fair <20632147+afairgiant@users.noreply.github.com>
Date: Wed, 21 May 2025 19:29:45 -0400
Subject: [PATCH 04/10] feature: Implement OPF Support (#339)
---
.../service/fileprocessor/EpubProcessor.java | 148 +++++++++++++++---
1 file changed, 123 insertions(+), 25 deletions(-)
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java
index 89411a518..0466f1c9c 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java
@@ -1,31 +1,11 @@
package com.adityachandel.booklore.service.fileprocessor;
-import com.adityachandel.booklore.mapper.BookMapper;
-import com.adityachandel.booklore.model.dto.settings.LibraryFile;
-import com.adityachandel.booklore.model.dto.Book;
-import com.adityachandel.booklore.model.entity.BookEntity;
-import com.adityachandel.booklore.model.entity.BookMetadataEntity;
-import com.adityachandel.booklore.model.enums.BookFileType;
-import com.adityachandel.booklore.repository.BookMetadataRepository;
-import com.adityachandel.booklore.repository.BookRepository;
-import com.adityachandel.booklore.service.BookCreatorService;
-import com.adityachandel.booklore.util.FileUtils;
-import io.documentnode.epub4j.domain.Identifier;
-import io.documentnode.epub4j.domain.Metadata;
-import io.documentnode.epub4j.domain.Resource;
-import io.documentnode.epub4j.epub.EpubReader;
-import lombok.AllArgsConstructor;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.time.Instant;
import java.time.LocalDate;
import java.time.OffsetDateTime;
@@ -35,6 +15,39 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
+import javax.imageio.ImageIO;
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import com.adityachandel.booklore.mapper.BookMapper;
+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.BookMetadataEntity;
+import com.adityachandel.booklore.model.enums.BookFileType;
+import com.adityachandel.booklore.repository.BookMetadataRepository;
+import com.adityachandel.booklore.repository.BookRepository;
+import com.adityachandel.booklore.service.BookCreatorService;
+import com.adityachandel.booklore.util.FileUtils;
+
+import io.documentnode.epub4j.domain.Identifier;
+import io.documentnode.epub4j.domain.Metadata;
+import io.documentnode.epub4j.domain.Resource;
+import io.documentnode.epub4j.epub.EpubReader;
+import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import net.lingala.zip4j.ZipFile;
+import net.lingala.zip4j.model.FileHeader;
+
@Slf4j
@Service
@AllArgsConstructor
@@ -117,10 +130,16 @@ public class EpubProcessor implements FileProcessor {
}
private void setBookMetadata(BookEntity bookEntity) {
- try {
- io.documentnode.epub4j.domain.Book book = new EpubReader().readEpub(new FileInputStream(FileUtils.getBookFullPath(bookEntity)));
+ log.debug("***Setting metadata for book {}", bookEntity.getFileName());
+ try (FileInputStream fis =
+ new FileInputStream(FileUtils.getBookFullPath(bookEntity))) {
+
+ io.documentnode.epub4j.domain.Book book =
+ new EpubReader().readEpub(fis);
+
BookMetadataEntity bookMetadata = bookEntity.getMetadata();
- Metadata epubMetadata = book.getMetadata();
+ Metadata epubMetadata = book.getMetadata();
+
if (epubMetadata != null) {
bookMetadata.setTitle(truncate(epubMetadata.getFirstTitle(), 1000));
@@ -162,7 +181,8 @@ public class EpubProcessor implements FileProcessor {
}
});
}
-
+
+ // Calibre (EPUB2) series tags
String seriesName = epubMetadata.getMetaAttribute("calibre:series");
if (seriesName != null && !seriesName.isEmpty()) {
bookMetadata.setSeriesName(truncate(seriesName, 1000));
@@ -178,6 +198,9 @@ public class EpubProcessor implements FileProcessor {
}
}
+ // fall-back to OPF for anything still missing
+ extractFromOpf(FileUtils.getBookFullPath(bookEntity), bookMetadata);
+
bookCreatorService.addAuthorsToBook(getAuthors(book), bookEntity);
bookCreatorService.addCategoriesToBook(epubMetadata.getSubjects(), bookEntity);
}
@@ -213,4 +236,79 @@ public class EpubProcessor implements FileProcessor {
if (input == null) return null;
return input.length() <= maxLength ? input : input.substring(0, maxLength);
}
+
+ private void extractFromOpf(String epubPath, BookMetadataEntity meta) {
+ try (ZipFile zip = new ZipFile(epubPath)) {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(true);
+ dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ DocumentBuilder builder = dbf.newDocumentBuilder();
+
+ FileHeader containerHdr = zip.getFileHeader("META-INF/container.xml");
+ if (containerHdr == null) return;
+ try (InputStream cis = zip.getInputStream(containerHdr)) {
+ Document containerDoc;
+ try {
+ containerDoc = builder.parse(cis);
+ } catch (Exception e) {
+ return;
+ }
+ if (containerDoc == null) return;
+ NodeList roots = containerDoc.getElementsByTagName("rootfile");
+ if (roots.getLength() == 0) return;
+ String opfPath = ((Element) roots.item(0)).getAttribute("full-path");
+ if (StringUtils.isBlank(opfPath)) return;
+ FileHeader opfHdr = zip.getFileHeader(opfPath);
+ if (opfHdr == null) return;
+ try (InputStream in = zip.getInputStream(opfHdr)) {
+ Document doc;
+ try {
+ doc = builder.parse(in);
+ } catch (Exception e) {
+ return;
+ }
+ if (doc == null) return;
+ if (StringUtils.isBlank(meta.getIsbn13()) || StringUtils.isBlank(meta.getIsbn10())) {
+ NodeList idNodes = doc.getElementsByTagNameNS("*", "identifier");
+ for (int i = 0; i < idNodes.getLength(); i++) {
+ String idRaw = idNodes.item(i).getTextContent().trim();
+ String isbn = idRaw.toLowerCase().startsWith("isbn:") ? idRaw.substring(5) : idRaw;
+ if (isbn.length() == 13 && StringUtils.isBlank(meta.getIsbn13())) {
+ meta.setIsbn13(truncate(isbn, 64));
+ }
+ if (isbn.length() == 10 && StringUtils.isBlank(meta.getIsbn10())) {
+ meta.setIsbn10(truncate(isbn, 64));
+ }
+ }
+ }
+ NodeList metaNodes = doc.getElementsByTagNameNS("*", "meta");
+ for (int i = 0; i < metaNodes.getLength(); i++) {
+ Element m = (Element) metaNodes.item(i);
+ String nameAttr = m.getAttribute("name");
+ String propAttr = m.getAttribute("property");
+ String content = m.hasAttribute("content") ? m.getAttribute("content").trim() : m.getTextContent().trim();
+
+ if (StringUtils.isBlank(meta.getSeriesName()) && (nameAttr.equalsIgnoreCase("calibre:series") || propAttr.equalsIgnoreCase("belongs-to-collection"))) {
+ meta.setSeriesName(truncate(content, 1000));
+ }
+ if (meta.getSeriesNumber() == null && (nameAttr.equalsIgnoreCase("calibre:series_index") || propAttr.equalsIgnoreCase("group-position"))) {
+ try {
+ int number = (int) Double.parseDouble(content);
+ meta.setSeriesNumber((float) number);
+ } catch (NumberFormatException ignored) {
+ }
+ }
+ if (meta.getPageCount() == null && (nameAttr.equalsIgnoreCase("calibre:pages") || nameAttr.equalsIgnoreCase("pageCount") || propAttr.equalsIgnoreCase("schema:pageCount") || propAttr.equalsIgnoreCase("media:pageCount"))) {
+ try {
+ int pages = Integer.parseInt(content);
+ meta.setPageCount(pages);
+ } catch (NumberFormatException ignored) {
+ }
+ }
+ }
+ }
+ }
+ } catch (Exception ignored) {
+ }
+ }
}
\ No newline at end of file
From a7b665e0ba7d0fd625ffb36abf7cf75d0dc46b7e Mon Sep 17 00:00:00 2001
From: Alex Fair <20632147+afairgiant@users.noreply.github.com>
Date: Tue, 27 May 2025 02:04:14 -0400
Subject: [PATCH 05/10] Asin metadata support (#346)
---------
Co-authored-by: Aditya Chandel <8075870+adityachandelgit@users.noreply.github.com>
---
.../booklore/model/dto/BookMetadata.java | 2 ++
.../dto/request/FetchMetadataRequest.java | 1 +
.../model/entity/BookMetadataEntity.java | 9 ++++++
.../booklore/service/BookMetadataService.java | 5 ++++
.../booklore/service/BookMetadataUpdater.java | 7 ++++-
.../service/fileprocessor/EpubProcessor.java | 29 +++++++++++++++++--
.../metadata/parser/AmazonBookParser.java | 1 +
.../db/migration/V22__Add_asin_column.sql | 2 ++
.../metadata-editor.component.html | 8 +++++
.../metadata-editor.component.ts | 16 ++++++++--
.../metadata-picker.component.ts | 8 +++++
.../metadata-viewer.component.html | 1 +
12 files changed, 84 insertions(+), 5 deletions(-)
create mode 100644 booklore-api/src/main/resources/db/migration/V22__Add_asin_column.sql
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java
index e80270a54..cfd00c244 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java
@@ -26,6 +26,7 @@ public class BookMetadata {
private Integer seriesTotal;
private String isbn13;
private String isbn10;
+ private String asin;
private Integer pageCount;
private String language;
private Double rating;
@@ -54,6 +55,7 @@ public class BookMetadata {
private Boolean seriesTotalLocked;
private Boolean isbn13Locked;
private Boolean isbn10Locked;
+ private Boolean asinLocked;
private Boolean pageCountLocked;
private Boolean languageLocked;
private Boolean ratingLocked;
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FetchMetadataRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FetchMetadataRequest.java
index 1c1fc326d..de15ccc81 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FetchMetadataRequest.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FetchMetadataRequest.java
@@ -14,4 +14,5 @@ public class FetchMetadataRequest {
private String isbn;
private String title;
private String author;
+ private String asin;
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookMetadataEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookMetadataEntity.java
index 5fdb21b21..d5290d1cf 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookMetadataEntity.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookMetadataEntity.java
@@ -51,6 +51,9 @@ public class BookMetadataEntity {
@Column(name = "isbn_10", length = 10)
private String isbn10;
+ @Column(name = "asin", length = 10)
+ private String asin;
+
@Column(name = "page_count")
private Integer pageCount;
@@ -104,6 +107,9 @@ public class BookMetadataEntity {
@Column(name = "isbn_10_locked")
private Boolean isbn10Locked = Boolean.FALSE;
+ @Column(name = "asin_locked")
+ private Boolean asinLocked = Boolean.FALSE;
+
@Column(name = "page_count_locked")
private Boolean pageCountLocked = Boolean.FALSE;
@@ -181,6 +187,7 @@ public class BookMetadataEntity {
this.descriptionLocked = lock;
this.isbn13Locked = lock;
this.isbn10Locked = lock;
+ this.asinLocked = lock;
this.pageCountLocked = lock;
this.thumbnailLocked = lock;
this.languageLocked = lock;
@@ -206,6 +213,7 @@ public class BookMetadataEntity {
|| Boolean.TRUE.equals(this.descriptionLocked)
|| Boolean.TRUE.equals(this.isbn13Locked)
|| Boolean.TRUE.equals(this.isbn10Locked)
+ || Boolean.TRUE.equals(this.asinLocked)
|| Boolean.TRUE.equals(this.pageCountLocked)
|| Boolean.TRUE.equals(this.thumbnailLocked)
|| Boolean.TRUE.equals(this.languageLocked)
@@ -231,6 +239,7 @@ public class BookMetadataEntity {
&& Boolean.TRUE.equals(this.descriptionLocked)
&& Boolean.TRUE.equals(this.isbn13Locked)
&& Boolean.TRUE.equals(this.isbn10Locked)
+ && Boolean.TRUE.equals(this.asinLocked)
&& Boolean.TRUE.equals(this.pageCountLocked)
&& Boolean.TRUE.equals(this.thumbnailLocked)
&& Boolean.TRUE.equals(this.languageLocked)
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataService.java
index 8ece39bed..ed6c8b9cf 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataService.java
@@ -200,6 +200,7 @@ public class BookMetadataService {
metadataCombined.setPublishedDate(metadata.getPublishedDate() != null ? metadata.getPublishedDate() : metadataCombined.getPublishedDate());
metadataCombined.setIsbn10(metadata.getIsbn10() != null ? metadata.getIsbn10() : metadataCombined.getIsbn10());
metadataCombined.setIsbn13(metadata.getIsbn13() != null ? metadata.getIsbn13() : metadataCombined.getIsbn13());
+ metadataCombined.setAsin(metadata.getAsin() != null ? metadata.getAsin() : metadataCombined.getAsin());
metadataCombined.setPageCount(metadata.getPageCount() != null ? metadata.getPageCount() : metadataCombined.getPageCount());
metadataCombined.setLanguage(metadata.getLanguage() != null ? metadata.getLanguage() : metadataCombined.getLanguage());
metadataCombined.setRating(metadata.getRating() != null ? metadata.getRating() : metadataCombined.getRating());
@@ -334,6 +335,7 @@ public class BookMetadataService {
private FetchMetadataRequest buildFetchMetadataRequestFromBook(Book book) {
return FetchMetadataRequest.builder()
.isbn(book.getMetadata().getIsbn10())
+ .asin(book.getMetadata().getAsin())
.author(String.join(", ", book.getMetadata().getAuthors()))
.title(book.getMetadata().getTitle())
.bookId(book.getId())
@@ -375,6 +377,9 @@ public class BookMetadataService {
case "isbn13":
existingMetadata.setIsbn13Locked(isLocked);
break;
+ case "asin":
+ existingMetadata.setAsinLocked(isLocked);
+ break;
case "description":
existingMetadata.setDescriptionLocked(isLocked);
break;
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataUpdater.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataUpdater.java
index 4f15c15ea..d56533601 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataUpdater.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookMetadataUpdater.java
@@ -71,7 +71,9 @@ public class BookMetadataUpdater {
if ((metadata.getIsbn13Locked() == null || !metadata.getIsbn13Locked()) && newMetadata.getIsbn13() != null) {
metadata.setIsbn13(newMetadata.getIsbn13().isBlank() ? null : newMetadata.getIsbn13());
}
-
+ if ((metadata.getAsinLocked() == null || !metadata.getAsinLocked()) && newMetadata.getAsin() != null) {
+ metadata.setAsin(newMetadata.getAsin().isBlank() ? null : newMetadata.getAsin());
+ }
if ((metadata.getDescriptionLocked() == null || !metadata.getDescriptionLocked()) && newMetadata.getDescription() != null) {
metadata.setDescription(newMetadata.getDescription().isBlank() ? null : newMetadata.getDescription());
}
@@ -216,6 +218,9 @@ public class BookMetadataUpdater {
if (newMetadata.getIsbn10Locked() != null) {
metadata.setIsbn10Locked(newMetadata.getIsbn10Locked());
}
+ if (newMetadata.getAsinLocked() != null) {
+ metadata.setAsinLocked(newMetadata.getAsinLocked());
+ }
if (newMetadata.getPageCountLocked() != null) {
metadata.setPageCountLocked(newMetadata.getPageCountLocked());
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java
index 0466f1c9c..74f1f88ae 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java
@@ -11,6 +11,7 @@ import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeParseException;
import java.util.List;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@@ -153,12 +154,36 @@ public class EpubProcessor implements FileProcessor {
List identifiers = epubMetadata.getIdentifiers().stream()
.map(Identifier::getValue)
+ .filter(Objects::nonNull)
+ .map(String::trim)
+ .map(id -> id.contains(":") ? id.substring(id.indexOf(":") + 1) : id) // strip prefix
+ .map(id -> id.replace("-", "")) // remove dashes
.toList();
+
+
if (!identifiers.isEmpty()) {
- String isbn13 = identifiers.stream().filter(id -> id.length() == 13).findFirst().orElse(null);
- String isbn10 = identifiers.stream().filter(id -> id.length() == 10).findFirst().orElse(null);
+ // Checking for ISBN 13 (strict 13-digit numeric)
+ String isbn13 = identifiers.stream()
+ .filter(id -> id.length() == 13 && id.matches("\\d{13}"))
+ .findFirst()
+ .orElse(null);
+
+ // Checking for ISBN 10 (strict 10-digit format or ends in X)
+ String isbn10 = identifiers.stream()
+ .filter(id -> id.length() == 10 && id.matches("\\d{9}[\\dXx]"))
+ .findFirst()
+ .orElse(null);
+
+ // Checking for ASIN (alphanumeric 10 chars, must not be ISBN-10)
+ String asin = identifiers.stream()
+ .filter(id -> id.length() == 10 && id.matches("^[A-Z0-9]{10}$"))
+ .filter(id -> !id.equalsIgnoreCase(isbn10))
+ .findFirst()
+ .orElse(null);
+
bookMetadata.setIsbn13(truncate(isbn13, 64));
bookMetadata.setIsbn10(truncate(isbn10, 64));
+ bookMetadata.setAsin(truncate(asin, 20));
}
bookMetadata.setLanguage(truncate(
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java
index 8e4ebdbbb..2759e293b 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/parser/AmazonBookParser.java
@@ -126,6 +126,7 @@ public class AmazonBookParser implements BookParser {
.seriesTotal(getSeriesTotal(doc))
.isbn13(getIsbn13(doc))
.isbn10(getIsbn10(doc))
+ .asin(amazonBookId)
.publisher(getPublisher(doc))
.publishedDate(getPublicationDate(doc))
.language(getLanguage(doc))
diff --git a/booklore-api/src/main/resources/db/migration/V22__Add_asin_column.sql b/booklore-api/src/main/resources/db/migration/V22__Add_asin_column.sql
new file mode 100644
index 000000000..216c2084c
--- /dev/null
+++ b/booklore-api/src/main/resources/db/migration/V22__Add_asin_column.sql
@@ -0,0 +1,2 @@
+ALTER TABLE book_metadata ADD COLUMN asin VARCHAR(20);
+ALTER TABLE book_metadata ADD COLUMN asin_locked BOOLEAN DEFAULT FALSE;
\ No newline at end of file
diff --git a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-editor/metadata-editor.component.html b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-editor/metadata-editor.component.html
index a3463e871..4a51b08db 100644
--- a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-editor/metadata-editor.component.html
+++ b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-editor/metadata-editor.component.html
@@ -183,6 +183,14 @@
+
diff --git a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-editor/metadata-editor.component.ts b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-editor/metadata-editor.component.ts
index 681894187..d964f5114 100644
--- a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-editor/metadata-editor.component.ts
+++ b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-editor/metadata-editor.component.ts
@@ -69,6 +69,7 @@ export class MetadataEditorComponent implements OnInit {
publishedDate: new FormControl(''),
isbn10: new FormControl(''),
isbn13: new FormControl(''),
+ asin: new FormControl(''),
description: new FormControl(''),
pageCount: new FormControl(''),
language: new FormControl(''),
@@ -90,6 +91,7 @@ export class MetadataEditorComponent implements OnInit {
publishedDateLocked: new FormControl(false),
isbn10Locked: new FormControl(false),
isbn13Locked: new FormControl(false),
+ asinLocked: new FormControl(false),
descriptionLocked: new FormControl(false),
pageCountLocked: new FormControl(false),
languageLocked: new FormControl(false),
@@ -125,6 +127,7 @@ export class MetadataEditorComponent implements OnInit {
publishedDate: metadata.publishedDate || null,
isbn10: metadata.isbn10 || null,
isbn13: metadata.isbn13 || null,
+ asin: metadata.asin || null,
description: metadata.description || null,
pageCount: metadata.pageCount || null,
language: metadata.language || null,
@@ -146,6 +149,7 @@ export class MetadataEditorComponent implements OnInit {
publishedDateLocked: metadata.publishedDateLocked || false,
isbn10Locked: metadata.isbn10Locked || false,
isbn13Locked: metadata.isbn13Locked || false,
+ asinLocked: metadata.asinLocked || false,
descriptionLocked: metadata.descriptionLocked || false,
pageCountLocked: metadata.pageCountLocked || false,
languageLocked: metadata.languageLocked || false,
@@ -171,6 +175,7 @@ export class MetadataEditorComponent implements OnInit {
{ key: 'languageLocked', control: 'language' },
{ key: 'isbn10Locked', control: 'isbn10' },
{ key: 'isbn13Locked', control: 'isbn13' },
+ { key: 'asinLocked', control: 'asin'},
{ key: 'amazonReviewCountLocked', control: 'amazonReviewCount' },
{ key: 'amazonRatingLocked', control: 'amazonRating' },
{ key: 'goodreadsReviewCountLocked', control: 'goodreadsReviewCount' },
@@ -210,8 +215,13 @@ export class MetadataEditorComponent implements OnInit {
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Book metadata updated'});
this.metadataCenterService.emitMetadata(response);
},
- error: () => {
- this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update book metadata'});
+ error: (err) => {
+ console.error('Update metadata failed:', err);
+ this.messageService.add({
+ severity: 'error',
+ summary: 'Error',
+ detail: err?.error?.message || 'Failed to update book metadata'
+ });
}
});
}
@@ -276,6 +286,7 @@ export class MetadataEditorComponent implements OnInit {
publishedDate: this.metadataForm.get('publishedDate')?.value,
isbn10: this.metadataForm.get('isbn10')?.value,
isbn13: this.metadataForm.get('isbn13')?.value,
+ asin: this.metadataForm.get('asin')?.value,
description: this.metadataForm.get('description')?.value,
pageCount: this.metadataForm.get('pageCount')?.value,
rating: this.metadataForm.get('rating')?.value,
@@ -297,6 +308,7 @@ export class MetadataEditorComponent implements OnInit {
publishedDateLocked: this.metadataForm.get('publishedDateLocked')?.value,
isbn10Locked: this.metadataForm.get('isbn10Locked')?.value,
isbn13Locked: this.metadataForm.get('isbn13Locked')?.value,
+ asinLocked: this.metadataForm.get('asinLocked')?.value,
descriptionLocked: this.metadataForm.get('descriptionLocked')?.value,
pageCountLocked: this.metadataForm.get('pageCountLocked')?.value,
languageLocked: this.metadataForm.get('languageLocked')?.value,
diff --git a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-picker/metadata-picker.component.ts b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-picker/metadata-picker.component.ts
index 131b47330..560c3eb74 100644
--- a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-picker/metadata-picker.component.ts
+++ b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-picker/metadata-picker.component.ts
@@ -54,6 +54,7 @@ export class MetadataPickerComponent implements OnInit {
{label: 'Book #', controlName: 'seriesNumber', lockedKey: 'seriesNumberLocked', fetchedKey: 'seriesNumber'},
{label: 'Total Books', controlName: 'seriesTotal', lockedKey: 'seriesTotalLocked', fetchedKey: 'seriesTotal'},
{label: 'ISBN-13', controlName: 'isbn13', lockedKey: 'isbn13Locked', fetchedKey: 'isbn13'},
+ {label: 'ASIN', controlName: 'asin', lockedKey: 'asinLocked', fetchedKey: 'asin'},
{label: 'Amazon Reviews', controlName: 'amazonReviewCount', lockedKey: 'amazonReviewCountLocked', fetchedKey: 'amazonReviewCount'},
{label: 'Amazon Rating', controlName: 'amazonRating', lockedKey: 'amazonRatingLocked', fetchedKey: 'amazonRating'},
{label: 'Goodreads Reviews', controlName: 'goodreadsReviewCount', lockedKey: 'goodreadsReviewCountLocked', fetchedKey: 'goodreadsReviewCount'},
@@ -87,6 +88,7 @@ export class MetadataPickerComponent implements OnInit {
publishedDate: new FormControl(''),
isbn10: new FormControl(''),
isbn13: new FormControl(''),
+ asin: new FormControl(''),
description: new FormControl(''),
pageCount: new FormControl(''),
language: new FormControl(''),
@@ -107,6 +109,7 @@ export class MetadataPickerComponent implements OnInit {
publishedDateLocked: new FormControl(false),
isbn10Locked: new FormControl(false),
isbn13Locked: new FormControl(false),
+ asinLocked: new FormControl(false),
descriptionLocked: new FormControl(false),
pageCountLocked: new FormControl(false),
languageLocked: new FormControl(false),
@@ -136,6 +139,7 @@ export class MetadataPickerComponent implements OnInit {
publishedDate: metadata.publishedDate || null,
isbn10: metadata.isbn10 || null,
isbn13: metadata.isbn13 || null,
+ asin: metadata.asin || null,
description: metadata.description || null,
pageCount: metadata.pageCount || null,
language: metadata.language || null,
@@ -156,6 +160,7 @@ export class MetadataPickerComponent implements OnInit {
publishedDateLocked: metadata.publishedDateLocked || false,
isbn10Locked: metadata.isbn10Locked || false,
isbn13Locked: metadata.isbn13Locked || false,
+ asinLocked: metadata.asinLocked || false,
descriptionLocked: metadata.descriptionLocked || false,
pageCountLocked: metadata.pageCountLocked || false,
languageLocked: metadata.languageLocked || false,
@@ -178,6 +183,7 @@ export class MetadataPickerComponent implements OnInit {
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.amazonReviewCountLocked) this.metadataForm.get('amazonReviewCount')?.disable();
if (metadata.amazonRatingLocked) this.metadataForm.get('amazonRating')?.disable();
if (metadata.goodreadsReviewCountLocked) this.metadataForm.get('goodreadsReviewCount')?.disable();
@@ -220,6 +226,7 @@ export class MetadataPickerComponent implements OnInit {
publishedDate: this.metadataForm.get('publishedDate')?.value || this.copiedFields['publishedDate'] ? this.getValueOrCopied('publishedDate') : '',
isbn10: this.metadataForm.get('isbn10')?.value || this.copiedFields['isbn10'] ? this.getValueOrCopied('isbn10') : '',
isbn13: this.metadataForm.get('isbn13')?.value || this.copiedFields['isbn13'] ? this.getValueOrCopied('isbn13') : '',
+ asin: this.metadataForm.get('asin')?.value || this.copiedFields['asin'] ? this.getValueOrCopied('asin') : '',
description: this.metadataForm.get('description')?.value || this.copiedFields['description'] ? this.getValueOrCopied('description') : '',
pageCount: this.metadataForm.get('pageCount')?.value || this.copiedFields['pageCount'] ? this.getPageCountOrCopied() : null,
language: this.metadataForm.get('language')?.value || this.copiedFields['language'] ? this.getValueOrCopied('language') : '',
@@ -240,6 +247,7 @@ export class MetadataPickerComponent implements OnInit {
publishedDateLocked: this.metadataForm.get('publishedDateLocked')?.value,
isbn10Locked: this.metadataForm.get('isbn10Locked')?.value,
isbn13Locked: this.metadataForm.get('isbn13Locked')?.value,
+ asinLocked: this.metadataForm.get('asin')?.value,
descriptionLocked: this.metadataForm.get('descriptionLocked')?.value,
pageCountLocked: this.metadataForm.get('pageCountLocked')?.value,
languageLocked: this.metadataForm.get('languageLocked')?.value,
diff --git a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html
index e611ad852..45e614f9a 100644
--- a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html
+++ b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html
@@ -86,6 +86,7 @@
Language: {{ metadata.language || '-' }}
ISBN 10: {{ metadata.isbn10 || '-' }}
ISBN 13: {{ metadata.isbn13 || '-' }}
+
ASIN: {{ metadata.asin || '-' }}
Page Count: {{ metadata.pageCount || '-' }}
File Size: {{ getFileSizeInMB() }}
Progress: {{ getProgressPercent() !== null ? getProgressPercent() + '%' : '-' }}
From e559efc2f7048919ec59276b30b90bd480946205 Mon Sep 17 00:00:00 2001
From: "aditya.chandel" <>
Date: Sat, 24 May 2025 00:43:50 -0600
Subject: [PATCH 06/10] Reduce memory footprint during comic cover parsing
---
.../booklore/service/AppMigrationService.java | 66 +++++++
.../booklore/service/AppMigrationStartup.java | 5 +
.../service/fileprocessor/CbxProcessor.java | 168 +++++++++---------
.../service/user/UserProvisioningService.java | 5 +-
.../cbx-reader/cbx-reader.component.html | 20 ++-
.../cbx-reader/cbx-reader.component.scss | 27 ++-
.../cbx-reader/cbx-reader.component.ts | 27 ++-
7 files changed, 219 insertions(+), 99 deletions(-)
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/AppMigrationService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/AppMigrationService.java
index 7306f3797..6073ee84e 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/AppMigrationService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/AppMigrationService.java
@@ -1,10 +1,17 @@
package com.adityachandel.booklore.service;
+import com.adityachandel.booklore.model.dto.BookLoreUser;
+import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
+import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
+import com.adityachandel.booklore.model.entity.UserSettingEntity;
import com.adityachandel.booklore.repository.AppMigrationRepository;
import com.adityachandel.booklore.repository.BookRepository;
+import com.adityachandel.booklore.repository.UserRepository;
+import com.adityachandel.booklore.service.user.UserProvisioningService;
import com.adityachandel.booklore.util.FileUtils;
+import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -12,6 +19,7 @@ import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
@AllArgsConstructor
@@ -20,6 +28,7 @@ public class AppMigrationService {
private AppMigrationRepository migrationRepository;
private BookRepository bookRepository;
+ private UserProvisioningService userProvisioningService;
@Transactional
public void populateMissingFileSizesOnce() {
@@ -44,4 +53,61 @@ public class AppMigrationService {
migrationRepository.save(migration);
log.info("Migration 'populateFileSizes' executed successfully.");
}
+
+ @Transactional
+ public void addCbxReaderSettingToExistingUsers(UserRepository userRepository, ObjectMapper objectMapper) {
+ final String migrationKey = "addCbxReaderSetting";
+
+ if (migrationRepository.existsById(migrationKey)) {
+ return;
+ }
+
+ List
users = userRepository.findAll();
+ int updatedCount = 0;
+ AtomicInteger perBookUpdatedCount = new AtomicInteger();
+
+ for (BookLoreUserEntity user : users) {
+ boolean hasCbxSetting = user.getSettings().stream().anyMatch(s -> s.getSettingKey().equals(UserSettingKey.CBX_READER_SETTING.getDbKey()));
+
+ if (!hasCbxSetting) {
+ try {
+ UserSettingEntity setting = UserSettingEntity.builder()
+ .user(user)
+ .settingKey(UserSettingKey.CBX_READER_SETTING.getDbKey())
+ .settingValue(objectMapper.writeValueAsString(userProvisioningService.buildDefaultCbxReaderSetting()))
+ .build();
+ user.getSettings().add(setting);
+ updatedCount++;
+ } catch (Exception e) {
+ log.error("Failed to create CBX setting for user {}", user.getUsername(), e);
+ }
+ }
+
+ user.getSettings().stream()
+ .filter(s -> s.getSettingKey().equals(UserSettingKey.PER_BOOK_SETTING.getDbKey()))
+ .findFirst()
+ .ifPresent(setting -> {
+ try {
+ var current = objectMapper.readValue(setting.getSettingValue(), BookLoreUser.UserSettings.PerBookSetting.class);
+ if (current.getCbx() == null) {
+ current.setCbx(BookLoreUser.UserSettings.PerBookSetting.GlobalOrIndividual.Individual);
+ setting.setSettingValue(objectMapper.writeValueAsString(current));
+ perBookUpdatedCount.getAndIncrement();
+ }
+ } catch (Exception e) {
+ log.error("Failed to update PER_BOOK_SETTING for user {}", user.getUsername(), e);
+ }
+ });
+ }
+
+ userRepository.saveAll(users);
+
+ AppMigrationEntity migration = new AppMigrationEntity();
+ migration.setKey(migrationKey);
+ migration.setExecutedAt(LocalDateTime.now());
+ migration.setDescription("Add CBX reader setting and update PER_BOOK_SETTING to include CBX for existing users");
+ migrationRepository.save(migration);
+
+ log.info("Migration '{}' completed. Added CBX setting to {} users and updated PER_BOOK_SETTING for {} users.", migrationKey, updatedCount, perBookUpdatedCount);
+ }
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/AppMigrationStartup.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/AppMigrationStartup.java
index 3d10e7112..2185e04ca 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/AppMigrationStartup.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/AppMigrationStartup.java
@@ -1,5 +1,7 @@
package com.adityachandel.booklore.service;
+import com.adityachandel.booklore.repository.UserRepository;
+import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
@@ -10,9 +12,12 @@ import org.springframework.stereotype.Component;
public class AppMigrationStartup {
private final AppMigrationService appMigrationService;
+ private final UserRepository userRepository;
+ private final ObjectMapper objectMapper;
@EventListener(ApplicationReadyEvent.class)
public void runMigrationsOnce() {
appMigrationService.populateMissingFileSizesOnce();
+ appMigrationService.addCbxReaderSettingToExistingUsers(userRepository, objectMapper);
}
}
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java
index 5a507579f..ac9a382f0 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java
@@ -23,12 +23,10 @@ import org.springframework.transaction.annotation.Transactional;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.InputStream;
+import java.io.*;
import java.time.Instant;
import java.util.*;
+import java.util.function.Consumer;
@Slf4j
@Service
@@ -46,7 +44,6 @@ public class CbxProcessor implements FileProcessor {
public Book processFile(LibraryFile libraryFile, boolean forceProcess) {
File bookFile = new File(libraryFile.getFileName());
String fileName = bookFile.getName();
-
if (!forceProcess) {
Optional bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId());
return bookOptional.map(bookMapper::toBook).orElseGet(() -> processNewFile(libraryFile));
@@ -71,129 +68,128 @@ public class CbxProcessor implements FileProcessor {
public boolean generateCover(BookEntity bookEntity) {
File file = new File(FileUtils.getBookFullPath(bookEntity));
try {
- List images = extractImagesFromArchive(file);
- if (images == null || images.isEmpty()) {
- log.warn("No image entries found in archive: {}", file.getName());
- return false;
+ Optional imageOptional = extractImagesFromArchive(file);
+ if (imageOptional.isPresent()) {
+ BufferedImage firstImage = imageOptional.get();
+ boolean saved = fileProcessingUtils.saveCoverImage(firstImage, bookEntity.getId());
+ if (saved) {
+ bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
+ bookMetadataRepository.save(bookEntity.getMetadata());
+ return true;
+ }
}
- BufferedImage coverImage = images.get(0);
- boolean saved = fileProcessingUtils.saveCoverImage(coverImage, bookEntity.getId());
- bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
- bookMetadataRepository.save(bookEntity.getMetadata());
- return saved;
+ return false;
} catch (Exception e) {
log.error("Error generating cover from archive {}, error: {}", bookEntity.getFileName(), e.getMessage());
return false;
}
}
- private List extractImagesFromArchive(File file) {
+ private Optional extractImagesFromArchive(File file) {
String name = file.getName().toLowerCase();
if (name.endsWith(".cbz")) {
- return extractImagesFromZip(file);
+ return extractFirstImageFromZip(file);
} else if (name.endsWith(".cb7")) {
- return extractImagesFrom7z(file);
+ return extractFirstImageFrom7z(file);
} else if (name.endsWith(".cbr")) {
- return extractImagesFromRar(file);
+ return extractFirstImageFromRar(file);
} else {
log.warn("Unsupported archive format: {}", name);
- return List.of();
+ return Optional.empty();
}
}
- private List extractImagesFromRar(File file) {
- List images = new ArrayList<>();
+ private Optional extractFirstImageFromRar(File file) {
try (Archive archive = new Archive(file)) {
List headers = archive.getFileHeaders();
- headers.stream()
+ List imageHeaders = headers.stream()
+ .filter(h -> !h.isDirectory())
.filter(h -> {
- if (h.isDirectory()) return false;
String fileName = h.getFileNameString().replace("\\", "/").toLowerCase();
return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png") || fileName.endsWith(".webp");
})
.sorted(Comparator.comparing(FileHeader::getFileNameString))
- .forEach(header -> {
- try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
- archive.extractFile(header, baos);
- byte[] imageData = baos.toByteArray();
- BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData));
- if (img != null) {
- images.add(img);
- }
+ .toList();
+
+ for (FileHeader header : imageHeaders) {
+ try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+ archive.extractFile(header, baos);
+ byte[] imageData = baos.toByteArray();
+ BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData));
+ if (img != null) {
+ return Optional.of(img);
+ }
+ } catch (Exception e) {
+ log.warn("Failed to read image from RAR entry {}: {}", header.getFileNameString(), e.getMessage());
+ }
+ }
+ } catch (Exception e) {
+ log.error("Error extracting image from RAR archive {}: {}", file.getName(), e.getMessage());
+ }
+ return Optional.empty();
+ }
+
+ private Optional extractFirstImageFromZip(File file) {
+ try (ZipFile zipFile = new ZipFile(file)) {
+ return Collections.list(zipFile.getEntries()).stream()
+ .filter(e -> !e.isDirectory())
+ .filter(e -> e.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)"))
+ .min(Comparator.comparing(ZipArchiveEntry::getName))
+ .map(entry -> {
+ try (InputStream is = zipFile.getInputStream(entry)) {
+ return ImageIO.read(is);
} catch (Exception e) {
- log.warn("Failed to read image from RAR entry {}: {}", header.getFileNameString(), e.getMessage());
+ log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage());
+ return null;
}
});
} catch (Exception e) {
- log.error("Error extracting images from RAR archive {}: {}", file.getName(), e.getMessage());
- return List.of();
- }
- return images;
- }
-
- /**
- * Extracts image entries from a ZIP archive (.cbz), sorted by entry name.
- */
- private List extractImagesFromZip(File file) {
- List images = new ArrayList<>();
- try (ZipFile zipFile = new ZipFile(file)) {
- List extends ZipArchiveEntry> imageEntries = Collections.list(zipFile.getEntries()).stream()
- .filter(e -> !e.isDirectory())
- .filter(e -> e.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)"))
- .sorted(Comparator.comparing(ZipArchiveEntry::getName))
- .toList();
- for (ZipArchiveEntry entry : imageEntries) {
- try (InputStream is = zipFile.getInputStream(entry)) {
- BufferedImage img = ImageIO.read(is);
- if (img != null) {
- images.add(img);
- }
- } catch (Exception e) {
- log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage());
- }
- }
- return images;
- } catch (Exception e) {
- log.error("Error extracting images from ZIP archive {}: {}", file.getName(), e.getMessage());
- return List.of();
+ log.error("Error extracting image from ZIP archive {}: {}", file.getName(), e.getMessage());
+ return Optional.empty();
}
}
- private List extractImagesFrom7z(File file) {
- List images = new ArrayList<>();
+ private Optional extractFirstImageFrom7z(File file) {
try (SevenZFile sevenZFile = new SevenZFile(file)) {
- List entries = new ArrayList<>();
+ List imageEntries = new ArrayList<>();
SevenZArchiveEntry entry;
while ((entry = sevenZFile.getNextEntry()) != null) {
if (!entry.isDirectory() && entry.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)")) {
- entries.add(entry);
+ imageEntries.add(entry);
}
}
- entries.sort(Comparator.comparing(SevenZArchiveEntry::getName));
- for (SevenZArchiveEntry e : entries) {
- try {
- byte[] content = new byte[(int) e.getSize()];
- int offset = 0;
- while (offset < content.length) {
- int bytesRead = sevenZFile.read(content, offset, content.length - offset);
- if (bytesRead < 0) {
- break;
+ imageEntries.sort(Comparator.comparing(SevenZArchiveEntry::getName));
+ sevenZFile.close();
+
+ try (SevenZFile sevenZFileReset = new SevenZFile(file)) {
+ for (SevenZArchiveEntry imgEntry : imageEntries) {
+ SevenZArchiveEntry currentEntry;
+ while ((currentEntry = sevenZFileReset.getNextEntry()) != null) {
+ if (currentEntry.equals(imgEntry)) {
+ byte[] content = new byte[(int) currentEntry.getSize()];
+ int offset = 0;
+ while (offset < content.length) {
+ int bytesRead = sevenZFileReset.read(content, offset, content.length - offset);
+ if (bytesRead < 0) {
+ break;
+ }
+ offset += bytesRead;
+ }
+ BufferedImage img = ImageIO.read(new ByteArrayInputStream(content));
+ if (img != null) {
+ return Optional.of(img);
+ } else {
+ break;
+ }
}
- offset += bytesRead;
}
- BufferedImage img = ImageIO.read(new java.io.ByteArrayInputStream(content));
- if (img != null) {
- images.add(img);
- }
- } catch (Exception ex) {
- log.warn("Failed to read image from 7z entry {}: {}", e.getName(), ex.getMessage());
}
}
+ return Optional.empty();
} catch (Exception e) {
- log.error("Error extracting images from 7z archive {}: {}", file.getName(), e.getMessage());
- return List.of();
+ log.error("Error extracting image from 7z archive {}: {}", file.getName(), e.getMessage());
+ return Optional.empty();
}
- return images;
}
private void setMetadata(BookEntity bookEntity) {
diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java
index b0e0db9b0..bc05a34c6 100644
--- a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java
+++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserProvisioningService.java
@@ -181,7 +181,7 @@ public class UserProvisioningService {
addUserSetting(user, UserSettingKey.PER_BOOK_SETTING, buildDefaultPerBookSetting());
addUserSetting(user, UserSettingKey.PDF_READER_SETTING, buildDefaultPdfReaderSetting());
addUserSetting(user, UserSettingKey.EPUB_READER_SETTING, buildDefaultEpubReaderSetting());
- addUserSetting(user, UserSettingKey.CBX_READER_SETTING, buildDefaultEpubReaderSetting());
+ addUserSetting(user, UserSettingKey.CBX_READER_SETTING, buildDefaultCbxReaderSetting());
addUserSetting(user, UserSettingKey.SIDEBAR_LIBRARY_SORTING, buildDefaultSidebarLibrarySorting());
addUserSetting(user, UserSettingKey.SIDEBAR_SHELF_SORTING, buildDefaultSidebarShelfSorting());
@@ -206,6 +206,7 @@ public class UserProvisioningService {
return BookLoreUser.UserSettings.PerBookSetting.builder()
.epub(BookLoreUser.UserSettings.PerBookSetting.GlobalOrIndividual.Individual)
.pdf(BookLoreUser.UserSettings.PerBookSetting.GlobalOrIndividual.Individual)
+ .cbx(BookLoreUser.UserSettings.PerBookSetting.GlobalOrIndividual.Individual)
.build();
}
@@ -225,7 +226,7 @@ public class UserProvisioningService {
.build();
}
- private BookLoreUser.UserSettings.CbxReaderSetting buildDefaultCbxReaderSetting() {
+ public BookLoreUser.UserSettings.CbxReaderSetting buildDefaultCbxReaderSetting() {
return BookLoreUser.UserSettings.CbxReaderSetting.builder()
.pageViewMode(CbxPageViewMode.SINGLE_PAGE)
.pageSpread(CbxPageSpread.ODD)
diff --git a/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.html b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.html
index 38a16ec60..cdef316cf 100644
--- a/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.html
+++ b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.html
@@ -1,13 +1,25 @@
-
-
+
+
+
+
+
+
+
+
Page {{ currentPage + 1 }}{{ isTwoPageView && imageUrls.length > 1 ? '-' + (currentPage + 2) : '' }} of {{ pages.length }}
-
+
+
-
+
+
diff --git a/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.scss b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.scss
index 0aead1209..963185303 100644
--- a/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.scss
+++ b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.scss
@@ -18,7 +18,6 @@
top: 50%;
transform: translate(-50%, -50%);
display: flex;
- gap: 1rem;
align-items: center;
white-space: nowrap;
@@ -26,12 +25,10 @@
min-width: 8rem;
display: inline-block;
text-align: center;
- font-variant-numeric: tabular-nums;
}
button {
- min-width: 3rem;
- padding: 0 0.5rem;
+ padding: 0 0.25rem;
text-align: center;
white-space: nowrap;
cursor: pointer;
@@ -93,4 +90,26 @@
display: block;
}
}
+
+ .goto-page-controls {
+ position: absolute;
+ left: 0;
+ top: 50%;
+ transform: translateY(-50%);
+ display: flex;
+ gap: 0.5rem;
+ align-items: center;
+ padding-left: 6px;
+ }
+
+ .goto-page-controls input[type="number"] {
+ width: 40px;
+ border-radius: 0.25rem;
+ font-size: 0.875rem;
+ }
+
+ .goto-page-controls button:disabled {
+ cursor: default;
+ color: #999;
+ }
}
diff --git a/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.ts b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.ts
index 61665149d..033bd2218 100644
--- a/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.ts
+++ b/booklore-ui/src/app/book/components/cbx-reader/cbx-reader.component.ts
@@ -8,15 +8,17 @@ import {MessageService} from 'primeng/api';
import {forkJoin} from 'rxjs';
import {BookSetting, CbxPageSpread, CbxPageViewMode} from '../../model/book.model';
import {ProgressSpinner} from 'primeng/progressspinner';
+import {FormsModule} from "@angular/forms";
@Component({
selector: 'app-cbx-reader',
standalone: true,
- imports: [NgIf, NgFor, ProgressSpinner],
+ imports: [NgIf, NgFor, ProgressSpinner, FormsModule],
templateUrl: './cbx-reader.component.html',
styleUrl: './cbx-reader.component.scss'
})
export class CbxReaderComponent implements OnInit {
+ goToPageInput: number | null = null;
bookId!: number;
pages: number[] = [];
currentPage = 0;
@@ -89,12 +91,21 @@ export class CbxReaderComponent implements OnInit {
}
nextPage() {
+ const previousPage = this.currentPage;
+
if (this.isTwoPageView) {
- this.currentPage += (this.currentPage < this.pages.length - 2) ? 2 : 1;
+ if (this.currentPage + 2 < this.pages.length) {
+ this.currentPage += 2;
+ } else if (this.currentPage + 1 < this.pages.length) {
+ this.currentPage += 1;
+ }
} else if (this.currentPage < this.pages.length - 1) {
this.currentPage++;
}
- this.updateProgress();
+
+ if (this.currentPage !== previousPage) {
+ this.updateProgress();
+ }
}
previousPage() {
@@ -192,4 +203,14 @@ export class CbxReaderComponent implements OnInit {
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
}
+ goToPage(page: number): void {
+ if (page < 1 || page > this.pages.length) return;
+
+ const targetIndex = page - 1;
+ if (targetIndex === this.currentPage) return;
+
+ this.currentPage = targetIndex;
+ this.alignCurrentPageToParity();
+ this.updateProgress();
+ }
}
From 1acb2917dd2a805fc5674052cbf00a4bb7d3f55f Mon Sep 17 00:00:00 2001
From: "aditya.chandel" <>
Date: Tue, 27 May 2025 02:30:14 -0600
Subject: [PATCH 07/10] Add sorting option: Title followed by Series
---
.../book/components/book-browser/book-browser.component.ts | 6 ++++--
booklore-ui/src/app/book/service/sort.service.ts | 6 ++++++
2 files changed, 10 insertions(+), 2 deletions(-)
diff --git a/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts
index 8c3b0b4e6..904a621d3 100644
--- a/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts
+++ b/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts
@@ -115,6 +115,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
sortOptions: any[] = [
{label: 'Title', icon: '', field: 'title', command: () => this.sortBooks('title')},
+ {label: 'Title + Series', icon: '', field: 'titleSeries', command: () => this.sortBooks('titleSeries')},
{label: 'Author', icon: '', field: 'author', command: () => this.sortBooks('author')},
{label: 'Last Read', field: 'lastReadTime', command: () => this.sortBooks('lastReadTime')},
{label: 'Added On', field: 'addedOn', command: () => this.sortBooks('addedOn')},
@@ -497,7 +498,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
sortBooks(field: string): void {
const existingSort = this.sortOptions.find(opt => opt.field === field);
-
if (!existingSort) return;
if (this.selectedSort?.field === field) {
@@ -521,7 +521,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.router.navigate([], {
queryParams: {
sort: this.selectedSort.field,
- direction: this.selectedSort.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING
+ direction: this.selectedSort.direction === SortDirection.ASCENDING
+ ? SORT_DIRECTION.ASCENDING
+ : SORT_DIRECTION.DESCENDING
},
queryParamsHandling: 'merge',
replaceUrl: true
diff --git a/booklore-ui/src/app/book/service/sort.service.ts b/booklore-ui/src/app/book/service/sort.service.ts
index 5525471d8..647ff96ca 100644
--- a/booklore-ui/src/app/book/service/sort.service.ts
+++ b/booklore-ui/src/app/book/service/sort.service.ts
@@ -9,6 +9,12 @@ export class SortService {
private readonly fieldExtractors: Record
any> = {
title: (book) => book.metadata?.title?.toLowerCase() || null,
+ titleSeries: (book) => {
+ const title = book.metadata?.title?.toLowerCase() || '';
+ const inSeries = !!book.metadata?.seriesName;
+ const seriesOrder = book.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
+ return [title, inSeries ? 1 : 0, seriesOrder];
+ },
author: (book) => book.metadata?.authors?.map(a => a.toLowerCase()).join(", ") || null,
publishedDate: (book) => book.metadata?.publishedDate === null ? null : new Date(book.metadata?.publishedDate!).getTime(),
publisher: (book) => book.metadata?.publisher || null,
From e0187d0edef6ebe8850985b83edba37745defcf2 Mon Sep 17 00:00:00 2001
From: "aditya.chandel" <>
Date: Tue, 27 May 2025 08:37:14 -0600
Subject: [PATCH 08/10] Fix flyway version
---
.../{V22__Add_asin_column.sql => V24__Add_asin_column.sql} | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename booklore-api/src/main/resources/db/migration/{V22__Add_asin_column.sql => V24__Add_asin_column.sql} (100%)
diff --git a/booklore-api/src/main/resources/db/migration/V22__Add_asin_column.sql b/booklore-api/src/main/resources/db/migration/V24__Add_asin_column.sql
similarity index 100%
rename from booklore-api/src/main/resources/db/migration/V22__Add_asin_column.sql
rename to booklore-api/src/main/resources/db/migration/V24__Add_asin_column.sql
From 74c2f1153177d6f9382005644de270f00c5a14db Mon Sep 17 00:00:00 2001
From: "aditya.chandel" <>
Date: Tue, 27 May 2025 09:00:00 -0600
Subject: [PATCH 09/10] Add support for series name in search bar
---
.../book-browser/book-browser.component.html | 9 +++++---
.../book-browser/book-browser.component.scss | 18 +++++++++++++++
.../book-browser/book-browser.component.ts | 23 ++++++++++---------
3 files changed, 36 insertions(+), 14 deletions(-)
diff --git a/booklore-ui/src/app/book/components/book-browser/book-browser.component.html b/booklore-ui/src/app/book/components/book-browser/book-browser.component.html
index ce0d2303e..a3aac50c2 100644
--- a/booklore-ui/src/app/book/components/book-browser/book-browser.component.html
+++ b/booklore-ui/src/app/book/components/book-browser/book-browser.component.html
@@ -61,19 +61,22 @@
diff --git a/booklore-ui/src/app/book/components/book-browser/book-browser.component.scss b/booklore-ui/src/app/book/components/book-browser/book-browser.component.scss
index 3e4308ef2..cd58f9a71 100644
--- a/booklore-ui/src/app/book/components/book-browser/book-browser.component.scss
+++ b/booklore-ui/src/app/book/components/book-browser/book-browser.component.scss
@@ -85,3 +85,21 @@
font-weight: 100;
}
}
+
+.search-icon {
+ position: absolute;
+ top: 50%;
+ left: 10px;
+ transform: translateY(-50%);
+ color: var(--text-color-secondary);
+ font-size: 1.0rem;
+ pointer-events: none;
+}
+
+.search-input {
+ width: 100%;
+ padding-left: 30px;
+ height: 2.5rem;
+ line-height: 2.5rem;
+ font-size: 1rem;
+}
diff --git a/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts
index 904a621d3..0cb372754 100644
--- a/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts
+++ b/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts
@@ -84,7 +84,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
bookState$: Observable | undefined;
entity$: Observable | undefined;
entityType$: Observable | undefined;
- bookOrAuthor$ = new BehaviorSubject('');
+ searchTerm$ = new BehaviorSubject('');
entity: Library | Shelf | null = null;
entityType: EntityType | undefined;
@@ -178,7 +178,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
}
this.activatedRoute.paramMap.subscribe(() => {
- this.bookOrAuthor$.next('');
+ this.searchTerm$.next('');
this.bookTitle = '';
this.deselectAllBooks();
this.clearFilter();
@@ -312,15 +312,16 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
}
private headerFilter(bookState: BookState): Observable {
- return this.bookOrAuthor$.pipe(
- map(title => {
- if (title && title.trim() !== '') {
+ return this.searchTerm$.pipe(
+ map(term => {
+ if (term && term.trim() !== '') {
const filteredBooks = bookState.books?.filter(book => {
- const matchesTitle = book.metadata?.title?.toLowerCase().includes(title.toLowerCase());
+ const matchesTitle = book.metadata?.title?.toLowerCase().includes(term.toLowerCase());
+ const matchesSeries = book.metadata?.seriesName?.toLowerCase().includes(term.toLowerCase());
const matchesAuthor = book.metadata?.authors.some(author =>
- author.toLowerCase().includes(title.toLowerCase())
+ author.toLowerCase().includes(term.toLowerCase())
);
- return matchesTitle || matchesAuthor;
+ return matchesTitle || matchesSeries || matchesAuthor;
}) || null;
return {...bookState, books: filteredBooks};
}
@@ -426,13 +427,13 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
}
}
- onBookTitleChange(newTitle: string): void {
- this.bookOrAuthor$.next(newTitle);
+ onSearchTermChange(term: string): void {
+ this.searchTerm$.next(term);
}
clearSearch(): void {
this.bookTitle = '';
- this.onBookTitleChange('');
+ this.onSearchTermChange('');
this.resetFilters();
}
From 99650f083975b1a0df3637e1d6bf63cb4f24e294 Mon Sep 17 00:00:00 2001
From: "aditya.chandel" <>
Date: Tue, 27 May 2025 09:35:47 -0600
Subject: [PATCH 10/10] Display series name and number in table view
---
.../book-browser/book-table/book-table.component.html | 6 +++++-
booklore-ui/src/app/book/service/sort.service.ts | 9 ++++++---
2 files changed, 11 insertions(+), 4 deletions(-)
diff --git a/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.html b/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.html
index c4d0c9fea..b30fd35f8 100644
--- a/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.html
+++ b/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.html
@@ -21,6 +21,8 @@
Title |
Authors |
Publisher |
+ Series |
+ # |
Genres |
Published |
Last Read |
@@ -55,9 +57,11 @@
|
- {{ metadata.title }} |
+ {{ metadata.title }} |
{{ getAuthorNames(metadata.authors) }} |
{{ metadata.publisher }} |
+ {{ metadata.seriesName }} |
+ {{ metadata.seriesNumber }} |
{{ getGenres(metadata.categories) }} |
{{ metadata.publishedDate ? (metadata.publishedDate | date: 'dd-MMM-yyyy') : '' }}
diff --git a/booklore-ui/src/app/book/service/sort.service.ts b/booklore-ui/src/app/book/service/sort.service.ts
index 647ff96ca..4bb52316e 100644
--- a/booklore-ui/src/app/book/service/sort.service.ts
+++ b/booklore-ui/src/app/book/service/sort.service.ts
@@ -11,9 +11,12 @@ export class SortService {
title: (book) => book.metadata?.title?.toLowerCase() || null,
titleSeries: (book) => {
const title = book.metadata?.title?.toLowerCase() || '';
- const inSeries = !!book.metadata?.seriesName;
- const seriesOrder = book.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
- return [title, inSeries ? 1 : 0, seriesOrder];
+ const series = book.metadata?.seriesName?.toLowerCase();
+ const seriesNumber = book.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
+ if (series) {
+ return [series, seriesNumber];
+ }
+ return [title, Number.MAX_SAFE_INTEGER];
},
author: (book) => book.metadata?.authors?.map(a => a.toLowerCase()).join(", ") || null,
publishedDate: (book) => book.metadata?.publishedDate === null ? null : new Date(book.metadata?.publishedDate!).getTime(),
|