diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml index d98524bd3..6f5116e77 100644 --- a/.github/release-drafter.yml +++ b/.github/release-drafter.yml @@ -8,6 +8,9 @@ categories: - title: '✨ Enhancements' labels: - 'enhancement' + - title: '🎨 UI Tweaks' + labels: + - 'ui-tweaks' - title: '🐛 Bug Fixes' labels: - 'bug' diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java index 5bf27bf67..5ad231d2b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java @@ -6,14 +6,12 @@ import com.adityachandel.booklore.model.dto.kobo.KoboAuthentication; import com.adityachandel.booklore.model.dto.kobo.KoboReadingStateWrapper; import com.adityachandel.booklore.model.dto.kobo.KoboResources; import com.adityachandel.booklore.model.dto.kobo.KoboTestResponse; -import com.adityachandel.booklore.service.BookService; -import com.adityachandel.booklore.service.KoboEntitlementService; -import com.adityachandel.booklore.service.KoboReadingStateService; -import com.adityachandel.booklore.service.ShelfService; +import com.adityachandel.booklore.service.*; import com.adityachandel.booklore.service.kobo.*; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; @@ -23,6 +21,9 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.*; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; import java.util.List; import java.util.Set; @@ -42,6 +43,7 @@ public class KoboController { private final KoboLibrarySyncService koboLibrarySyncService; private final KoboThumbnailService koboThumbnailService; private final ShelfService shelfService; + private final BookDownloadService bookDownloadService; @ModelAttribute public void captureToken(@PathVariable("token") String token) { @@ -129,11 +131,11 @@ public class KoboController { } @GetMapping("/v1/books/{bookId}/download") - public ResponseEntity downloadBook(@PathVariable String bookId) { + public void downloadBook(@PathVariable String bookId, HttpServletResponse response) throws IOException { if (StringUtils.isNumeric(bookId)) { - return bookService.downloadBook(Long.parseLong(bookId)); + bookDownloadService.downloadKoboBook(Long.parseLong(bookId), response); } else { - return koboServerProxy.proxyCurrentRequest(null, false); + koboServerProxy.proxyCurrentRequest(null, false); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java b/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java index 0a8debfb8..7fa218094 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java @@ -95,7 +95,7 @@ public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity handleGenericException(Exception ex) { - ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred."); + ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage()); log.error(ex.getMessage(), ex); return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR); } 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 b944fef30..383dccc37 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 @@ -4,8 +4,9 @@ import lombok.Getter; @Getter public enum AppSettingKey { - QUICK_BOOK_MATCH("quick_book_match", true, false), OIDC_PROVIDER_DETAILS("oidc_provider_details", true, true), + + QUICK_BOOK_MATCH("quick_book_match", true, false), OIDC_AUTO_PROVISION_DETAILS("oidc_auto_provision_details", true, false), SIDEBAR_LIBRARY_SORTING("sidebar_library_sorting", true, false), SIDEBAR_SHELF_SORTING("sidebar_shelf_sorting", true, false), @@ -13,6 +14,7 @@ public enum AppSettingKey { METADATA_MATCH_WEIGHTS("metadata_match_weights", true, false), METADATA_PERSISTENCE_SETTINGS("metadata_persistence_settings", true, false), METADATA_PUBLIC_REVIEWS_SETTINGS("metadata_public_reviews_settings", true, false), + KOBO_SETTINGS("kobo_settings", true, false), AUTO_BOOK_SEARCH("auto_book_search", false, false), COVER_IMAGE_RESOLUTION("cover_image_resolution", false, false), 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 e9b77ed1a..0ebe7f1f6 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 @@ -30,4 +30,5 @@ public class AppSettings { private MetadataMatchWeights metadataMatchWeights; private MetadataPersistenceSettings metadataPersistenceSettings; private MetadataPublicReviewsSettings metadataPublicReviewsSettings; + private KoboSettings koboSettings; } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/KoboSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/KoboSettings.java new file mode 100644 index 000000000..7192789ff --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/KoboSettings.java @@ -0,0 +1,11 @@ +package com.adityachandel.booklore.model.dto.settings; + +import lombok.Builder; +import lombok.Data; + +@Builder +@Data +public class KoboSettings { + private boolean convertToKepub; + private int conversionLimitInMb; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/KoboBookFormat.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/KoboBookFormat.java new file mode 100644 index 000000000..7456dd2a9 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/KoboBookFormat.java @@ -0,0 +1,6 @@ +package com.adityachandel.booklore.model.enums; + +public enum KoboBookFormat { + EPUB3, + KEPUB, +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookDownloadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookDownloadService.java new file mode 100644 index 000000000..54cea4fd1 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookDownloadService.java @@ -0,0 +1,117 @@ +package com.adityachandel.booklore.service; + +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.model.dto.settings.KoboSettings; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import com.adityachandel.booklore.service.kobo.KepubConversionService; +import com.adityachandel.booklore.util.FileUtils; +import jakarta.servlet.http.HttpServletResponse; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.FileSystemUtils; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +@Slf4j +@AllArgsConstructor +@Service +public class BookDownloadService { + + private final BookRepository bookRepository; + private final KepubConversionService kepubConversionService; + private final AppSettingService appSettingService; + + public ResponseEntity downloadBook(Long bookId) { + try { + BookEntity bookEntity = bookRepository.findById(bookId) + .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize(); + Resource resource = new UrlResource(file.toUri()); + + return ResponseEntity.ok() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"") + .body(resource); + } catch (Exception e) { + log.error("Failed to download book {}: {}", bookId, e.getMessage(), e); + throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); + } + } + + public void downloadKoboBook(Long bookId, HttpServletResponse response) { + BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + if (bookEntity.getBookType() != BookFileType.EPUB) { + throw ApiError.GENERIC_BAD_REQUEST.createException("The requested book is not an EPUB file."); + } + + KoboSettings koboSettings = appSettingService.getAppSettings().getKoboSettings(); + if (koboSettings == null) { + throw ApiError.GENERIC_BAD_REQUEST.createException("Kobo settings not found."); + } + + + boolean asKepub = koboSettings.isConvertToKepub() && bookEntity.getFileSizeKb() <= (long) koboSettings.getConversionLimitInMb() * 1024; + + Path tempDir = null; + try { + File inputFile = new File(FileUtils.getBookFullPath(bookEntity)); + File fileToSend = inputFile; + + if (asKepub) { + tempDir = Files.createTempDirectory("kepub-output"); + fileToSend = kepubConversionService.convertEpubToKepub(inputFile, tempDir.toFile()); + } + + setResponseHeaders(response, fileToSend); + streamFileToResponse(fileToSend, response); + + log.info("Successfully streamed {} ({} bytes) to client", fileToSend.getName(), fileToSend.length()); + + } catch (Exception e) { + log.error("Failed to download kobo book {}: {}", bookId, e.getMessage(), e); + throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); + } finally { + cleanupTempDirectory(tempDir); + } + } + + private void setResponseHeaders(HttpServletResponse response, File file) { + response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); + response.setContentLengthLong(file.length()); + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\""); + } + + private void streamFileToResponse(File file, HttpServletResponse response) throws IOException { + try (InputStream in = Files.newInputStream(file.toPath())) { + in.transferTo(response.getOutputStream()); + response.getOutputStream().flush(); + } + } + + private void cleanupTempDirectory(Path tempDir) { + if (tempDir != null) { + try { + FileSystemUtils.deleteRecursively(tempDir); + log.debug("Deleted temporary directory {}", tempDir); + } catch (Exception e) { + log.warn("Failed to delete temporary directory {}: {}", tempDir, e.getMessage()); + } + } + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java index 1eb9a02f7..d5e446dbb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java @@ -59,6 +59,7 @@ public class BookService { private final AuthenticationService authenticationService; private final BookQueryService bookQueryService; private final UserProgressService userProgressService; + private final BookDownloadService bookDownloadService; private void setBookProgress(Book book, UserBookProgressEntity progress) { @@ -312,12 +313,12 @@ public class BookService { userBookProgress.setCbxProgress(request.getCbxProgress().getPage()); userBookProgress.setCbxProgressPercent(request.getCbxProgress().getPercentage()); } - + // Update dateFinished if provided if (request.getDateFinished() != null) { userBookProgress.setDateFinished(request.getDateFinished()); } - + userBookProgressRepository.save(userBookProgress); } @@ -453,18 +454,7 @@ public class BookService { } public ResponseEntity downloadBook(Long bookId) { - try { - BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - - Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize(); - Resource resource = new UrlResource(file.toUri()); - return ResponseEntity.ok() - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"") - .body(resource); - } catch (Exception e) { - throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); - } + return bookDownloadService.downloadBook(bookId); } public ResponseEntity getBookContent(long bookId) throws IOException { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/KoboEntitlementService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/KoboEntitlementService.java index 6d06ab6b2..f625aa364 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/KoboEntitlementService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/KoboEntitlementService.java @@ -1,12 +1,15 @@ package com.adityachandel.booklore.service; import com.adityachandel.booklore.model.dto.kobo.*; +import com.adityachandel.booklore.model.dto.settings.KoboSettings; import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.entity.CategoryEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.enums.KoboBookFormat; import com.adityachandel.booklore.model.enums.KoboReadStatus; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.util.kobo.KoboUrlBuilder; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; @@ -25,6 +28,7 @@ public class KoboEntitlementService { private final KoboUrlBuilder koboUrlBuilder; private final BookQueryService bookQueryService; + private final AppSettingService appSettingService; public List generateNewEntitlements(Set bookIds, String token, boolean removed) { List books = bookQueryService.findAllWithMetadataByIds(bookIds); @@ -146,6 +150,12 @@ public class KoboEntitlementService { String downloadUrl = koboUrlBuilder.downloadUrl(token, book.getId()); + KoboBookFormat bookFormat = KoboBookFormat.EPUB3; + KoboSettings koboSettings = appSettingService.getAppSettings().getKoboSettings(); + if (koboSettings != null && koboSettings.isConvertToKepub()) { + bookFormat = KoboBookFormat.KEPUB; + } + return KoboBookMetadata.builder() .crossRevisionId(String.valueOf(book.getId())) .revisionId(String.valueOf(book.getId())) @@ -170,7 +180,7 @@ public class KoboEntitlementService { .downloadUrls(List.of( KoboBookMetadata.DownloadUrl.builder() .url(downloadUrl) - .format("EPUB3") + .format(bookFormat.toString()) .size(book.getFileSizeKb() * 1024) .build() )) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java index e8b226deb..f5a23a267 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java @@ -89,6 +89,7 @@ public class AppSettingService { builder.metadataMatchWeights(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_MATCH_WEIGHTS, MetadataMatchWeights.class, settingPersistenceHelper.getDefaultMetadataMatchWeights(), true)); builder.metadataPersistenceSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_PERSISTENCE_SETTINGS, MetadataPersistenceSettings.class, settingPersistenceHelper.getDefaultMetadataPersistenceSettings(), true)); builder.metadataPublicReviewsSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_PUBLIC_REVIEWS_SETTINGS, MetadataPublicReviewsSettings.class, settingPersistenceHelper.getDefaultMetadataPublicReviewsSettings(), true)); + builder.koboSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.KOBO_SETTINGS, KoboSettings.class, settingPersistenceHelper.getDefaultKoboSettings(), true)); builder.coverResolution(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.COVER_IMAGE_RESOLUTION, "250x350")); builder.autoBookSearch(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.AUTO_BOOK_SEARCH, "true"))); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java index b6af148a3..622c15371 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java @@ -200,4 +200,11 @@ public class SettingPersistenceHelper { )) .build(); } + + public KoboSettings getDefaultKoboSettings() { + return KoboSettings.builder() + .convertToKepub(false) + .conversionLimitInMb(100) + .build(); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KepubConversionService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KepubConversionService.java new file mode 100644 index 000000000..a848b70e6 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KepubConversionService.java @@ -0,0 +1,113 @@ +package com.adityachandel.booklore.service.kobo; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.stream.Collectors; + +@Slf4j +@Service +public class KepubConversionService { + + private static final String KEPUBIFY_BINARY_MACOS_ARM64 = "/bin/kepubify-darwin-arm64"; + private static final String KEPUBIFY_BINARY_LINUX_X64 = "/bin/kepubify-linux-64bit"; + + public File convertEpubToKepub(File epubFile, File tempDir) throws IOException, InterruptedException { + validateInputs(epubFile); + + Path kepubifyBinary = setupKepubifyBinary(tempDir); + File outputFile = executeKepubifyConversion(epubFile, tempDir, kepubifyBinary); + + log.info("Successfully converted {} to {} (size: {} bytes)", epubFile.getName(), outputFile.getName(), outputFile.length()); + return outputFile; + } + + private void validateInputs(File epubFile) { + if (epubFile == null || !epubFile.isFile() || !epubFile.getName().endsWith(".epub")) { + throw new IllegalArgumentException("Invalid EPUB file: " + epubFile); + } + } + + private Path setupKepubifyBinary(File tempDir) throws IOException { + Path tempKepubify = tempDir.toPath().resolve("kepubify"); + String resourcePath = getKepubifyResourcePath(); + + try (InputStream in = getClass().getResourceAsStream(resourcePath)) { + if (in == null) { + throw new IOException("Resource not found: " + resourcePath); + } + Files.copy(in, tempKepubify, StandardCopyOption.REPLACE_EXISTING); + } + tempKepubify.toFile().setExecutable(true); + return tempKepubify; + } + + private String getKepubifyResourcePath() { + String osName = System.getProperty("os.name").toLowerCase(); + String osArch = System.getProperty("os.arch").toLowerCase(); + + log.debug("Detected OS: {} ({})", osName, osArch); + + if (osName.contains("mac") || osName.contains("darwin")) { + return KEPUBIFY_BINARY_MACOS_ARM64; + } else if (osName.contains("linux")) { + return KEPUBIFY_BINARY_LINUX_X64; + } else { + throw new IllegalStateException("Unsupported operating system: " + osName); + } + } + + private File executeKepubifyConversion(File epubFile, File tempDir, Path kepubifyBinary) throws IOException, InterruptedException { + + ProcessBuilder pb = new ProcessBuilder(kepubifyBinary.toAbsolutePath().toString(), "-o", tempDir.getAbsolutePath(), epubFile.getAbsolutePath()); + pb.directory(tempDir); + + log.info("Starting kepubify conversion for {} -> output dir: {}", epubFile.getAbsolutePath(), tempDir.getAbsolutePath()); + + Process process = pb.start(); + + String output = readProcessOutput(process.getInputStream()); + String error = readProcessOutput(process.getErrorStream()); + + int exitCode = process.waitFor(); + logProcessResults(exitCode, output, error); + + if (exitCode != 0) { + throw new IOException(String.format("Kepubify conversion failed with exit code: %d. Error: %s", exitCode, error)); + } + + return findOutputFile(tempDir); + } + + private String readProcessOutput(InputStream inputStream) { + return new BufferedReader(new InputStreamReader(inputStream)) + .lines() + .collect(Collectors.joining("\n")); + } + + private void logProcessResults(int exitCode, String output, String error) { + log.debug("Kepubify process exited with code {}", exitCode); + if (!output.isEmpty()) { + log.debug("Kepubify stdout: {}", output); + } + if (!error.isEmpty()) { + log.error("Kepubify stderr: {}", error); + } + } + + private File findOutputFile(File tempDir) throws IOException { + File[] kepubFiles = tempDir.listFiles((dir, name) -> name.endsWith(".kepub.epub")); + if (kepubFiles == null || kepubFiles.length == 0) { + throw new IOException("Kepubify conversion completed but no .kepub.epub file was created in: " + tempDir.getAbsolutePath()); + } + return kepubFiles[0]; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/kobo/KoboUrlBuilder.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/kobo/KoboUrlBuilder.java index c926e9c32..1c3431c22 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/kobo/KoboUrlBuilder.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/kobo/KoboUrlBuilder.java @@ -3,6 +3,7 @@ package com.adityachandel.booklore.util.kobo; import com.adityachandel.booklore.util.RequestUtils; import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder; @@ -11,6 +12,9 @@ import org.springframework.web.util.UriComponentsBuilder; @Slf4j public class KoboUrlBuilder { + @Value("${server.port}") + private int serverPort; + public UriComponentsBuilder baseBuilder() { HttpServletRequest request = RequestUtils.getCurrentRequest(); @@ -18,10 +22,9 @@ public class KoboUrlBuilder { .fromCurrentContextPath() .replacePath("") .replaceQuery(null) - .port(-1); // drop default port + .port(-1); String host = builder.build().getHost(); - String scheme = builder.build().getScheme(); if (host == null) host = ""; @@ -34,6 +37,7 @@ public class KoboUrlBuilder { } log.info("Applied X-Forwarded-Port: {}", port); } catch (NumberFormatException e) { + builder.port(serverPort); log.warn("Invalid X-Forwarded-Port header: {}", xfPort); } diff --git a/booklore-api/src/main/resources/bin/kepubify-darwin-arm64 b/booklore-api/src/main/resources/bin/kepubify-darwin-arm64 new file mode 100644 index 000000000..c98a374ef Binary files /dev/null and b/booklore-api/src/main/resources/bin/kepubify-darwin-arm64 differ diff --git a/booklore-api/src/main/resources/bin/kepubify-linux-64bit b/booklore-api/src/main/resources/bin/kepubify-linux-64bit new file mode 100644 index 000000000..eb425265e Binary files /dev/null and b/booklore-api/src/main/resources/bin/kepubify-linux-64bit differ diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java b/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java index cee1ea1a5..435eefe6c 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java @@ -3,6 +3,7 @@ package com.adityachandel.booklore; import com.adityachandel.booklore.config.security.AuthenticationService; import com.adityachandel.booklore.mapper.BookMapper; import com.adityachandel.booklore.repository.*; +import com.adityachandel.booklore.service.BookDownloadService; import com.adityachandel.booklore.service.BookQueryService; import com.adityachandel.booklore.service.BookService; import com.adityachandel.booklore.service.UserProgressService; @@ -46,6 +47,7 @@ class BookServiceDeleteTests { AuthenticationService authenticationService = Mockito.mock(AuthenticationService.class); BookQueryService bookQueryService = Mockito.mock(BookQueryService.class); UserProgressService userProgressService = Mockito.mock(UserProgressService.class); + BookDownloadService bookDownloadService = Mockito.mock(BookDownloadService.class); bookService = new BookService( bookRepository, @@ -60,7 +62,8 @@ class BookServiceDeleteTests { userBookProgressRepository, authenticationService, bookQueryService, - userProgressService + userProgressService, + bookDownloadService ); } 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 fe3ddc210..fea36348c 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 @@ -44,7 +44,8 @@ + tooltipPosition="top" + style="color: orange;"> } @@ -83,7 +84,6 @@ } - + + @if (this.showFilter) {
+ + } - - + 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 53f9bb82d..274a4e97e 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 @@ -96,11 +96,12 @@ } .search-input { - width: 100%; + min-width: 22rem; padding-left: 30px; height: 2.5rem; line-height: 2.5rem; font-size: 1rem; + box-sizing: border-box; } .mobile-filter-mask { 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 fa0c7e1b7..7a712172f 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 @@ -1,4 +1,4 @@ -import {AfterViewInit, ChangeDetectorRef, Component, inject, OnInit, ViewChild} from '@angular/core'; +import {Component, inject, OnInit, ViewChild} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {ConfirmationService, MenuItem, MessageService, PrimeTemplate} from 'primeng/api'; import {LibraryService} from '../../service/library.service'; @@ -46,6 +46,7 @@ import {BookMenuService} from '../../service/book-menu.service'; import {MagicShelf, MagicShelfService} from '../../../magic-shelf.service'; import {BookRuleEvaluatorService} from '../../../book-rule-evaluator.service'; import {GroupRule} from '../../../magic-shelf-component/magic-shelf-component'; +import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref-service'; export enum EntityType { LIBRARY = 'Library', @@ -87,18 +88,19 @@ const SORT_DIRECTION = { providers: [SeriesCollapseFilter], animations: [ trigger('slideInOut', [ - state('void', style({ transform: 'translateY(100%)' })), - state('*', style({ transform: 'translateY(0)' })), - transition(':enter', [ animate('0.1s ease-in') ]), - transition(':leave', [ animate('0.1s ease-out') ]) + state('void', style({transform: 'translateY(100%)'})), + state('*', style({transform: 'translateY(0)'})), + transition(':enter', [animate('0.1s ease-in')]), + transition(':leave', [animate('0.1s ease-out')]) ]) ] }) -export class BookBrowserComponent implements OnInit, AfterViewInit { +export class BookBrowserComponent implements OnInit { protected userService = inject(UserService); protected coverScalePreferenceService = inject(CoverScalePreferenceService); protected filterSortPreferenceService = inject(FilterSortPreferenceService); protected columnPreferenceService = inject(TableColumnPreferenceService); + protected sidebarFilterTogglePrefService = inject(SidebarFilterTogglePrefService); private activatedRoute = inject(ActivatedRoute); private messageService = inject(MessageService); private libraryService = inject(LibraryService); @@ -108,7 +110,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { private bookMenuService = inject(BookMenuService); private sortService = inject(SortService); private router = inject(Router); - private changeDetectorRef = inject(ChangeDetectorRef); private libraryShelfMenuService = inject(LibraryShelfMenuService); protected seriesCollapseFilter = inject(SeriesCollapseFilter); protected confirmationService = inject(ConfirmationService); @@ -148,14 +149,30 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { private headerFilter = new HeaderFilter(this.searchTerm$); protected bookSorter = new BookSorter(selectedSort => this.applySortOption(selectedSort)); - @ViewChild(BookTableComponent) bookTableComponent!: BookTableComponent; - @ViewChild(BookFilterComponent) bookFilterComponent!: BookFilterComponent; + @ViewChild(BookTableComponent) + bookTableComponent!: BookTableComponent; + @ViewChild(BookFilterComponent, { static: false }) + bookFilterComponent!: BookFilterComponent; - get currentCardSize() { return this.coverScalePreferenceService.currentCardSize; } - get gridColumnMinWidth(): string { return this.coverScalePreferenceService.gridColumnMinWidth; } - get viewIcon(): string { return this.currentViewMode === VIEW_MODES.GRID ? 'pi pi-objects-column' : 'pi pi-table'; } - get hasSidebarFilters(): boolean { return !!this.selectedFilter.value && Object.keys(this.selectedFilter.value).length > 0; } - get isFilterActive(): boolean { return this.selectedFilter.value !== null; } + get currentCardSize() { + return this.coverScalePreferenceService.currentCardSize; + } + + get gridColumnMinWidth(): string { + return this.coverScalePreferenceService.gridColumnMinWidth; + } + + get viewIcon(): string { + return this.currentViewMode === VIEW_MODES.GRID ? 'pi pi-objects-column' : 'pi pi-table'; + } + + get hasSidebarFilters(): boolean { + return !!this.selectedFilter.value && Object.keys(this.selectedFilter.value).length > 0; + } + + get isFilterActive(): boolean { + return this.selectedFilter.value !== null; + } ngOnInit(): void { this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000)).subscribe(); @@ -197,23 +214,22 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { () => this.multiBookEditMetadata() ); this.tieredMenuItems = this.bookMenuService.getTieredMenuItems(this.selectedBooks); - } - ngAfterViewInit(): void { - combineLatest({ - paramMap: this.activatedRoute.queryParamMap, - user: this.userService.userState$.pipe( - filter(userState => !!userState?.user && userState.loaded), - take(1) - ) - }).subscribe(({paramMap, user}) => { + // --- NEW: Subscribe to query params + user changes for reactive updates --- + combineLatest([ + this.activatedRoute.paramMap, + this.activatedRoute.queryParamMap, + this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded)) + ]).subscribe(([paramMap, queryParamMap, user]) => { - const viewParam = paramMap.get(QUERY_PARAMS.VIEW); - const sortParam = paramMap.get(QUERY_PARAMS.SORT); - const directionParam = paramMap.get(QUERY_PARAMS.DIRECTION); - const filterParams = paramMap.get(QUERY_PARAMS.FILTER); - const sidebarParam = paramMap.get(QUERY_PARAMS.SIDEBAR); - this.showFilter = sidebarParam === null ? true : sidebarParam === 'true'; + const viewParam = queryParamMap.get(QUERY_PARAMS.VIEW); + const sortParam = queryParamMap.get(QUERY_PARAMS.SORT); + const directionParam = queryParamMap.get(QUERY_PARAMS.DIRECTION); + const filterParams = queryParamMap.get(QUERY_PARAMS.FILTER); + + this.sidebarFilterTogglePrefService.showFilter$.subscribe(value => { + this.showFilter = value; + }); const parsedFilters: Record = {}; @@ -229,8 +245,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { }); this.selectedFilter.next(parsedFilters); - this.bookFilterComponent.setFilters?.(parsedFilters); - this.bookFilterComponent.onFiltersChanged?.(); + if(this.bookFilterComponent) { + this.bookFilterComponent.setFilters?.(parsedFilters); + this.bookFilterComponent.onFiltersChanged?.(); + } const firstFilter = filterParams.split(',')[0]; const [key, ...values] = firstFilter.split(':'); @@ -256,7 +274,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { this.columnPreferenceService.initPreferences(user.user?.userSettings?.tableColumnPreference); this.visibleColumns = this.columnPreferenceService.visibleColumns; - const override = this.entityViewPreferences?.overrides?.find(o => o.entityType?.toUpperCase() === currentEntityTypeStr && o.entityId === this.entity?.id @@ -289,7 +306,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { direction: SortDirection.DESCENDING }; - const fromParam = paramMap.get(QUERY_PARAMS.FROM); + const fromParam = queryParamMap.get(QUERY_PARAMS.FROM); this.currentViewMode = fromParam === 'toggle' ? (viewParam === VIEW_MODES.TABLE || viewParam === VIEW_MODES.GRID ? viewParam @@ -306,8 +323,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { const queryParams: any = { [QUERY_PARAMS.VIEW]: this.currentViewMode, [QUERY_PARAMS.SORT]: this.bookSorter.selectedSort.field, - [QUERY_PARAMS.DIRECTION]: this.bookSorter.selectedSort.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING, - [QUERY_PARAMS.SIDEBAR]: this.showFilter.toString() + [QUERY_PARAMS.DIRECTION]: this.bookSorter.selectedSort.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING }; if (Object.keys(parsedFilters).length > 0) { @@ -316,29 +332,13 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { const currentParams = this.activatedRoute.snapshot.queryParams; const changed = Object.keys(queryParams).some(k => currentParams[k] !== queryParams[k]); - if (changed) { + const mergedParams = {...currentParams, ...queryParams}; this.router.navigate([], { - queryParams, + queryParams: mergedParams, replaceUrl: true }); } - - this.changeDetectorRef.detectChanges(); - }); - - this.bookFilterComponent.filterSelected.subscribe((filters: Record | null) => { - if (this.settingFiltersFromUrl) return; - - this.selectedFilter.next(filters); - this.rawFilterParamFromUrl = null; - - const hasSidebarFilters = !!filters && Object.keys(filters).length > 0; - this.currentFilterLabel = hasSidebarFilters ? 'All Books (Filtered)' : 'All Books'; - }); - - this.bookFilterComponent.filterModeChanged.subscribe((mode: 'and' | 'or') => { - this.selectedFilterMode.next(mode); }); this.searchTerm$.subscribe(term => { @@ -346,6 +346,25 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { }); } + onFilterSelected(filters: Record | null): void { + if (this.settingFiltersFromUrl) return; + + this.selectedFilter.next(filters); + this.rawFilterParamFromUrl = null; + + const hasSidebarFilters = !!filters && Object.keys(filters).length > 0; + this.currentFilterLabel = hasSidebarFilters ? 'All Books (Filtered)' : 'All Books'; + } + + onFilterModeChanged(mode: 'and' | 'or'): void { + this.selectedFilterMode.next(mode); + } + + toggleSidebar(): void { + this.showFilter = !this.showFilter; + this.sidebarFilterTogglePrefService.selectedShowFilter = this.showFilter; + } + updateScale(): void { this.coverScalePreferenceService.setScale(this.coverScalePreferenceService.scaleFactor); } @@ -476,18 +495,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { this.clearSearch(); } - toggleFilterSidebar() { - this.showFilter = !this.showFilter; - const currentParams = this.activatedRoute.snapshot.queryParams; - this.router.navigate([], { - queryParams: { - ...currentParams, - [QUERY_PARAMS.SIDEBAR]: this.showFilter.toString() - }, - replaceUrl: true - }); - } - toggleTableGrid(): void { this.currentViewMode = this.currentViewMode === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID; this.router.navigate([], { diff --git a/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.html b/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.html index 541daa6d4..f4f111df0 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.html +++ b/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.html @@ -14,7 +14,7 @@
- @for (filterType of filterTypes; track filterType; let i = $index) { + @for (filterType of filterTypes; track trackByFilterType(i, filterType); let i = $index) { @@ -32,7 +32,7 @@
- @for (filter of filters; track filter) { + @for (filter of filters; track trackByFilter(j, filter); let j = $index) {
@if (searchQuery) { @@ -22,29 +22,6 @@ } - - @if (books.length > 0 || searchQuery) {
(); + #searchSubject = new BehaviorSubject(''); #subscription!: Subscription; private bookService = inject(BookService); private router = inject(Router); protected urlHelper = inject(UrlHelperService); - - isSearchDropdownOpen = false; - - toggleSearchInputDropdown() { - this.isSearchDropdownOpen = !this.isSearchDropdownOpen; - } - - closeSearchDropdown() { - this.isSearchDropdownOpen = false; - } + private headerFilter = new HeaderFilter(this.#searchSubject.asObservable()); ngOnInit(): void { this.initializeSearch(); } initializeSearch(): void { - this.#subscription = this.#searchSubject.pipe( - debounceTime(350), - distinctUntilChanged(), - switchMap((query) => { - const result = this.bookService.searchBooks(query); - return of(result); - }), + this.#subscription = this.bookService.bookState$.pipe( + switchMap(bookState => this.headerFilter.filter(bookState)), catchError((error) => { console.error('Error while searching books:', error); - return of([]); + return of({books: [], loaded: true, error: null}); }) ).subscribe({ - next: (result: Book[]) => this.books = result, + next: (filteredState) => { + this.books = this.searchQuery.trim() ? (filteredState.books || []) : []; + }, error: (error) => console.error('Subscription error:', error) }); } 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 ba05329e2..199cc35a9 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,56 +1,80 @@ -
+
+ +
+ + +
+ {{ currentPage + 1 }} + {{ isTwoPageView && imageUrls.length > 1 ? '-' + (currentPage + 2) : '' }} + of {{ pages.length }} +
+ +
-
- - - - Page {{ currentPage + 1 }} - {{ isTwoPageView && imageUrls.length > 1 ? '-' + (currentPage + 2) : '' }} of {{ pages.length }} - - - -
- -
+
@if (isTwoPageView) { - } - +
-
+
@if (!isLoading) { @if (pages.length > 0) { - @for (url of imageUrls; track url) { - Page Image - } +
+ @for (url of imageUrls; track url) { + Page Image + } +
} @else { -

No pages available.

+
+

No pages available.

+
} } @else { -
- -

Processing pages... This may take a few seconds on first load. Future loads will be significantly faster.

+
+ +

Processing pages... This may take a few seconds on first load. Future loads will be significantly faster.

}
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 325300c5f..acbcef4db 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 @@ -1,115 +1,267 @@ .comic-reader-container { display: flex; flex-direction: column; - align-items: center; height: 100dvh; width: 100vw; - overflow-x: hidden; + overflow: hidden; box-sizing: border-box; + background: #1a1a1a; + color: #ffffff; + + &:focus { + outline: none; + } .navigation { - position: relative; + flex-shrink: 0; width: 100%; - margin: 1rem; + background: linear-gradient(135deg, #2d2d2d 0%, #1f1f1f 100%); + border-bottom: 1px solid #404040; + padding: 0.25rem 0.5rem; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3); + display: flex; + align-items: center; + justify-content: space-between; + z-index: 1000; + min-width: 0; + + .goto-page-controls { + flex: 0 0 auto; + order: 1; + min-width: fit-content; + + .input-group { + display: flex; + align-items: center; + gap: 0.125rem; + background: rgba(51, 51, 51, 0.9); + border-radius: 4px; + padding: 1px; + border: 1px solid #555; + + .page-input { + width: 55px; + padding: 4px 6px; + border: none; + border-radius: 3px; + background: #404040; + color: #ffffff; + font-size: 12px; + text-align: center; + transition: all 0.2s ease; + + &:focus { + outline: none; + background: #4a4a4a; + box-shadow: 0 0 0 1px rgba(74, 144, 226, 0.5); + } + + &::placeholder { + color: #999; + } + } + + .go-button { + padding: 4px 8px; + background: #4a90e2; + color: white; + border: none; + border-radius: 3px; + font-size: 12px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s ease; + + &:hover:not(:disabled) { + background: #357abd; + } + + &:disabled { + background: #666; + cursor: not-allowed; + opacity: 0.6; + } + } + } + } .page-controls { - position: absolute; - left: 50%; - top: 50%; - transform: translate(-50%, -50%); + flex: 1; display: flex; align-items: center; - white-space: nowrap; + justify-content: center; + gap: 0.25rem; + order: 2; + min-width: 0; - span { - min-width: 8rem; - display: inline-block; - text-align: center; - } - - button { - padding: 0 0.25rem; - text-align: center; - white-space: nowrap; + .nav-button { + width: 24px; + height: 28px; + border: 1px solid #555; + background: rgba(51, 51, 51, 0.9); + color: #ffffff; + border-radius: 4px; cursor: pointer; + transition: all 0.2s ease; + display: flex; + align-items: center; + justify-content: center; + + span { + font-size: 11px; + font-weight: bold; + } + + &:hover:not(:disabled) { + background: #4a4a4a; + border-color: #666; + } &:disabled { - cursor: default; - color: #999; + background: #2a2a2a; + color: #666; + cursor: not-allowed; + border-color: #333; + } + } + + .page-info { + margin: 0 0.5rem; + padding: 2px 8px; + background: rgba(255, 255, 255, 0.1); + border-radius: 4px; + font-weight: 500; + font-size: 12px; + min-width: 80px; + text-align: center; + + .current-page { + color: #4a90e2; + font-weight: 600; + } + + .page-separator { + color: #4a90e2; + font-weight: 600; + } + + .total-pages { + color: #ccc; } } } .spread-controls { - position: absolute; - right: 0; - top: 50%; - transform: translateY(-50%); + flex: 0 0 auto; display: flex; - gap: 0.5rem; - align-items: center; + gap: 0.25rem; + order: 3; + min-width: fit-content; - button { - padding-left: 0.5rem; - padding-right: 0.5rem; + .view-button { + width: 28px; + height: 28px; + border: 1px solid #555; + background: rgba(51, 51, 51, 0.9); + color: #ffffff; + border-radius: 4px; + cursor: pointer; + transition: all 0.2s ease; + display: flex; + align-items: center; + justify-content: center; + + span { + font-size: 13px; + } + + &:hover { + background: #4a4a4a; + border-color: #666; + } } } } .image-container { - flex-grow: 1; - width: 100%; + flex: 1; display: flex; justify-content: center; align-items: center; - gap: 1rem; overflow: hidden; - padding: 0 1rem; - box-sizing: border-box; + padding: 0.5rem; + background: #0f0f0f; + min-height: 0; + + &.bg-black { + background: #000000; + } + + &.bg-gray { + background: #0f0f0f; + } + + &.bg-white { + background: #ffffff; + } + + .pages-wrapper { + display: flex; + justify-content: center; + align-items: center; + gap: 1rem; + height: 100%; + width: 100%; + } &.two-page-view { - img { + .page-image { max-width: calc(50% - 0.5rem); + max-height: 100%; } } &:not(.two-page-view) { - img { + .page-image { max-width: 100%; + max-height: 100%; } } - img { - max-height: 100%; + .page-image { 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; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6); + border-radius: 4px; + transition: transform 0.2s ease; + + &:hover { + transform: scale(1.02); + } + } + + .no-pages { + text-align: center; + color: #999; + font-size: 18px; + } + + .loading-container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + gap: 1.5rem; + text-align: center; + + .loading-text { + color: #ccc; + font-size: 16px; + max-width: 400px; + line-height: 1.5; + margin: 0; + } } } - - .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 af0618cd1..77dea36a7 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 @@ -1,5 +1,4 @@ import {Component, HostListener, inject, OnInit} from '@angular/core'; - import {ActivatedRoute} from '@angular/router'; import {CbxReaderService} from '../../service/cbx-reader.service'; import {BookService} from '../../service/book.service'; @@ -31,6 +30,8 @@ export class CbxReaderComponent implements OnInit { pageSpread: CbxPageSpread | PdfPageSpread = CbxPageSpread.ODD; pageViewMode: CbxPageViewMode | PdfPageViewMode = CbxPageViewMode.SINGLE_PAGE; + backgroundColor: 'black' | 'gray' | 'white' = 'gray'; + private touchStartX = 0; private touchEndX = 0; @@ -111,6 +112,29 @@ export class CbxReaderComponent implements OnInit { return this.pageViewMode === CbxPageViewMode.TWO_PAGE || this.pageViewMode === PdfPageViewMode.TWO_PAGE; } + get backgroundColorIcon(): string { + switch (this.backgroundColor) { + case 'black': return '⚫'; + case 'gray': return '🔘'; + case 'white': return '⚪'; + default: return '🔘'; + } + } + + toggleBackground(): void { + switch (this.backgroundColor) { + case 'black': + this.backgroundColor = 'gray'; + break; + case 'gray': + this.backgroundColor = 'white'; + break; + case 'white': + this.backgroundColor = 'black'; + break; + } + } + toggleView() { if (!this.isTwoPageView && this.isPhonePortrait()) return; this.pageViewMode = this.isTwoPageView ? (this.bookType === "CBX" ? CbxPageViewMode.SINGLE_PAGE : PdfPageViewMode.SINGLE_PAGE) : (this.bookType === "CBX" ? CbxPageViewMode.TWO_PAGE : PdfPageViewMode.TWO_PAGE); @@ -222,7 +246,10 @@ export class CbxReaderComponent implements OnInit { get imageUrls(): string[] { if (!this.pages.length) return []; - const urls = [this.getPageImageUrl(this.currentPage)]; + const urls: string[] = []; + + urls.push(this.getPageImageUrl(this.currentPage)); + if (this.isTwoPageView && this.currentPage + 1 < this.pages.length) { urls.push(this.getPageImageUrl(this.currentPage + 1)); } @@ -233,17 +260,17 @@ export class CbxReaderComponent implements OnInit { private updateViewerSetting(): void { const bookSetting: BookSetting = this.bookType === "CBX" ? { - cbxSettings: { - pageSpread: this.pageSpread as CbxPageSpread, - pageViewMode: this.pageViewMode as CbxPageViewMode, - } + cbxSettings: { + pageSpread: this.pageSpread as CbxPageSpread, + pageViewMode: this.pageViewMode as CbxPageViewMode, } + } : { - newPdfSettings: { - pageSpread: this.pageSpread as PdfPageSpread, - pageViewMode: this.pageViewMode as PdfPageViewMode, - } - }; + newPdfSettings: { + pageSpread: this.pageSpread as PdfPageSpread, + pageViewMode: this.pageViewMode as PdfPageViewMode, + } + }; this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe(); } @@ -252,13 +279,14 @@ export class CbxReaderComponent implements OnInit { ? Math.round(((this.currentPage + 1) / this.pages.length) * 1000) / 10 : 0; - if(this.bookType === 'CBX') { + if (this.bookType === 'CBX') { this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe(); } - if(this.bookType === 'PDF') { + if (this.bookType === 'PDF') { this.bookService.savePdfProgress(this.bookId, this.currentPage + 1, percentage).subscribe(); } } + goToPage(page: number): void { if (page < 1 || page > this.pages.length) return; diff --git a/booklore-ui/src/app/book/service/book.service.ts b/booklore-ui/src/app/book/service/book.service.ts index 8a1dcef3f..9c7e3ede7 100644 --- a/booklore-ui/src/app/book/service/book.service.ts +++ b/booklore-ui/src/app/book/service/book.service.ts @@ -191,21 +191,6 @@ export class BookService { this.updateLastReadTime(book.id); } - searchBooks(query: string): Book[] { - if (query.length < 2) { - return []; - } - const normalize = (str: string): string => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase(); - const normalizedQuery = normalize(query); - const state = this.bookStateSubject.value; - return (state.books || []).filter(book => { - const title = book.metadata?.title; - const authors = book.metadata?.authors || []; - return (title && normalize(title).includes(normalizedQuery)) || - authors.some(author => normalize(author).includes(normalizedQuery)); - }); - } - getFileContent(bookId: number): Observable { return this.http.get(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'}); } @@ -331,7 +316,7 @@ export class BookService { if (currentState.books) { const updatedBooks = currentState.books.map(book => { if (book.id === bookId) { - return { ...book, dateFinished: dateFinished || undefined }; + return {...book, dateFinished: dateFinished || undefined}; } return book; }); 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 fb5cbec5c..c2f2a331b 100644 --- a/booklore-ui/src/app/core/model/app-settings.model.ts +++ b/booklore-ui/src/app/core/model/app-settings.model.ts @@ -90,6 +90,11 @@ export interface PublicReviewSettings { providers: ReviewProviderConfig[]; } +export interface KoboSettings { + convertToKepub: boolean; + conversionLimitInMb: number; +} + export interface AppSettings { autoBookSearch: boolean; similarBookRecommendation: boolean; @@ -107,6 +112,7 @@ export interface AppSettings { metadataMatchWeights: MetadataMatchWeights; metadataPersistenceSettings: MetadataPersistenceSettings; metadataPublicReviewsSettings: PublicReviewSettings; + koboSettings: KoboSettings; metadataDownloadOnBookdrop: boolean; } @@ -126,5 +132,6 @@ export enum AppSettingKey { METADATA_MATCH_WEIGHTS = 'METADATA_MATCH_WEIGHTS', METADATA_PERSISTENCE_SETTINGS = 'METADATA_PERSISTENCE_SETTINGS', METADATA_DOWNLOAD_ON_BOOKDROP = 'METADATA_DOWNLOAD_ON_BOOKDROP', - METADATA_PUBLIC_REVIEWS_SETTINGS = 'METADATA_PUBLIC_REVIEWS_SETTINGS' + METADATA_PUBLIC_REVIEWS_SETTINGS = 'METADATA_PUBLIC_REVIEWS_SETTINGS', + KOBO_SETTINGS = 'KOBO_SETTINGS' } diff --git a/booklore-ui/src/app/dashboard/components/dashboard-scroller/dashboard-scroller.component.scss b/booklore-ui/src/app/dashboard/components/dashboard-scroller/dashboard-scroller.component.scss index 65d180463..0ffa179e1 100644 --- a/booklore-ui/src/app/dashboard/components/dashboard-scroller/dashboard-scroller.component.scss +++ b/booklore-ui/src/app/dashboard/components/dashboard-scroller/dashboard-scroller.component.scss @@ -129,9 +129,9 @@ &::after { content: ''; position: absolute; - bottom: -12px; - left: 15%; - right: 15%; + bottom: -8px; + left: 10%; + right: 10%; height: 5px; background: linear-gradient( 90deg, @@ -149,8 +149,8 @@ @media (max-width: 767px) { .dashboard-scroller-card { - height: 184px; /* 80% of 230px */ - width: 108px; /* 80% of 135px */ + height: 184px; + width: 108px; flex-basis: 108px; } diff --git a/booklore-ui/src/app/metadata/book-metadata-center-component/metadata-viewer/metadata-viewer.component.scss b/booklore-ui/src/app/metadata/book-metadata-center-component/metadata-viewer/metadata-viewer.component.scss index 7f0f244ed..5eb4532e8 100644 --- a/booklore-ui/src/app/metadata/book-metadata-center-component/metadata-viewer/metadata-viewer.component.scss +++ b/booklore-ui/src/app/metadata/book-metadata-center-component/metadata-viewer/metadata-viewer.component.scss @@ -47,9 +47,40 @@ .dashboard-scroller-card { width: 115px; + flex-basis: 115px; flex-shrink: 0; flex-grow: 0; - flex-basis: 115px; + scroll-snap-align: start; + transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); + position: relative; + border-radius: 8px; + + &:hover { + transform: translateY(-4px); + + &::after { + opacity: 1; + } + } + + &::after { + content: ''; + position: absolute; + bottom: 0; + left: 7%; + right: 7%; + height: 4px; + background: linear-gradient( + 90deg, + transparent, + var(--p-primary-500), + transparent + ); + border-radius: 50%; + opacity: 0; + transition: all 0.4s ease; + filter: blur(4px); + } } .description-container { @@ -138,4 +169,3 @@ ::ng-deep .custom-tag-padding { padding: 0.1rem !important; } - diff --git a/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.html b/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.html index a6715ec2f..bca17791d 100644 --- a/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.html +++ b/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.html @@ -1,7 +1,7 @@

- Kobo Sync Settings: + Kobo Integration Token:

-@if (hasPermission) { +@if (hasKoboTokenPermission) {
@@ -50,6 +50,50 @@
+ + @if (isAdmin) { +
+

Kobo Settings (Admin Only):

+
+
+
+ + + +
+

+ Pros: KEPUB format enables enhanced Kobo features like better typography, reading stats, and faster page turns. +
+ Cons: Conversion takes extra processing time and may occasionally fail for complex layouts. + Books over the size limit below will skip conversion automatically. +

+
+ +
+
+ +
+ + +

+ Large files (100MB+) can cause conversion timeouts and server strain. Lower limits ensure faster syncing but may skip conversion of larger books. +
+ Recommended: 50-100MB for most libraries. Very large books will sync as regular EPUB regardless of this setting. +

+
+
+
+ } } @else {
diff --git a/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.ts b/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.ts index 357df11ac..b324fa8fc 100644 --- a/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.ts +++ b/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.ts @@ -8,15 +8,20 @@ import {InputText} from 'primeng/inputtext'; import {ConfirmDialog} from 'primeng/confirmdialog'; import {UserService} from '../../user-management/user.service'; import {Subject} from 'rxjs'; -import {filter, takeUntil} from 'rxjs/operators'; +import {debounceTime, filter, take, takeUntil} from 'rxjs/operators'; import {Tooltip} from 'primeng/tooltip'; +import {ToggleSwitch} from 'primeng/toggleswitch'; +import {Slider} from 'primeng/slider'; +import {AppSettingsService} from '../../../core/service/app-settings.service'; +import {SettingsHelperService} from '../../../core/service/settings-helper.service'; +import {AppSettingKey, KoboSettings} from '../../../core/model/app-settings.model'; @Component({ selector: 'app-kobo-sync-setting-component', standalone: true, templateUrl: './kobo-sync-settings-component.html', styleUrl: './kobo-sync-settings-component.scss', - imports: [FormsModule, Button, InputText, ConfirmDialog, Tooltip], + imports: [FormsModule, Button, InputText, ConfirmDialog, Tooltip, ToggleSwitch, Slider], providers: [MessageService, ConfirmationService] }) export class KoboSyncSettingsComponent implements OnInit, OnDestroy { @@ -25,34 +30,77 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { private confirmationService = inject(ConfirmationService); private clipboard = inject(Clipboard); protected userService = inject(UserService); + protected appSettingsService = inject(AppSettingsService); + protected settingsHelperService = inject(SettingsHelperService); private readonly destroy$ = new Subject(); - hasPermission = false; + private readonly sliderChange$ = new Subject(); + hasKoboTokenPermission = false; + isAdmin = false; koboToken = ''; credentialsSaved = false; showToken = false; + koboSettings: KoboSettings = { + convertToKepub: false, + conversionLimitInMb: 100 + }; + ngOnInit() { + this.setupSliderDebouncing(); + this.setupUserStateSubscription(); + } + + private setupSliderDebouncing() { + this.sliderChange$.pipe( + debounceTime(500), + takeUntil(this.destroy$) + ).subscribe(() => { + this.saveSettings(); + }); + } + + private setupUserStateSubscription() { this.userService.userState$.pipe( filter(userState => !!userState?.user && userState.loaded), takeUntil(this.destroy$) ).subscribe(userState => { - this.hasPermission = (userState.user?.permissions.canSyncKobo || userState.user?.permissions.admin) ?? false; - if (this.hasPermission) { - this.koboService.getUser().subscribe({ - next: (settings: KoboSyncSettings) => { - this.koboToken = settings.token; - this.credentialsSaved = !!settings.token; - }, - error: () => { - this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to load Kobo settings'}); - } - }); + this.hasKoboTokenPermission = (userState.user?.permissions.canSyncKobo) ?? false; + this.isAdmin = userState.user?.permissions.admin ?? false; + if (this.hasKoboTokenPermission) { + this.loadKoboToken(); + } + if (this.isAdmin) { + this.loadKoboSettings(); } }); } + private loadKoboToken() { + this.koboService.getUser().subscribe({ + next: (settings: KoboSyncSettings) => { + this.koboToken = settings.token; + this.credentialsSaved = !!settings.token; + }, + error: () => { + this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to load Kobo settings'}); + } + }); + } + + private loadKoboSettings() { + this.appSettingsService.appSettings$ + .pipe( + filter(settings => settings != null), + take(1), + ) + .subscribe(settings => { + this.koboSettings.convertToKepub = settings?.koboSettings?.convertToKepub ?? true; + this.koboSettings.conversionLimitInMb = settings?.koboSettings?.conversionLimitInMb ?? 100; + }); + } + copyText(text: string) { this.clipboard.copy(text); this.messageService.add({severity: 'success', summary: 'Copied', detail: 'Token copied to clipboard'}); @@ -84,6 +132,34 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { }); } + onToggleChange() { + this.saveSettings(); + } + + onSliderChange() { + this.sliderChange$.next(); + } + + saveSettings() { + this.settingsHelperService.saveSetting(AppSettingKey.KOBO_SETTINGS, this.koboSettings) + .subscribe({ + next: () => { + this.messageService.add({ + severity: 'success', + summary: 'Settings Saved', + detail: 'Kobo settings updated successfully' + }); + }, + error: () => { + this.messageService.add({ + severity: 'error', + summary: 'Save Failed', + detail: 'Failed to save Kobo settings' + }); + } + }); + } + openKoboDocumentation(): void { window.open('https://booklore-app.github.io/booklore-docs/docs/devices/kobo', '_blank'); }