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/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/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'); }