feat(kobo): add optional EPUB → KEpub conversion for Kobo downloads (#969)
This commit is contained in:
+9
-7
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> 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);
|
||||
}
|
||||
|
||||
+3
-1
@@ -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),
|
||||
|
||||
+1
@@ -30,4 +30,5 @@ public class AppSettings {
|
||||
private MetadataMatchWeights metadataMatchWeights;
|
||||
private MetadataPersistenceSettings metadataPersistenceSettings;
|
||||
private MetadataPublicReviewsSettings metadataPublicReviewsSettings;
|
||||
private KoboSettings koboSettings;
|
||||
}
|
||||
+11
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum KoboBookFormat {
|
||||
EPUB3,
|
||||
KEPUB,
|
||||
}
|
||||
+117
@@ -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<Resource> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Resource> 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<ByteArrayResource> getBookContent(long bookId) throws IOException {
|
||||
|
||||
+11
-1
@@ -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<NewEntitlement> generateNewEntitlements(Set<Long> bookIds, String token, boolean removed) {
|
||||
List<BookEntity> 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()
|
||||
))
|
||||
|
||||
+1
@@ -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")));
|
||||
|
||||
+7
@@ -200,4 +200,11 @@ public class SettingPersistenceHelper {
|
||||
))
|
||||
.build();
|
||||
}
|
||||
|
||||
public KoboSettings getDefaultKoboSettings() {
|
||||
return KoboSettings.builder()
|
||||
.convertToKepub(false)
|
||||
.conversionLimitInMb(100)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+113
@@ -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];
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -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
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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'
|
||||
}
|
||||
|
||||
+46
-2
@@ -1,7 +1,7 @@
|
||||
<p-confirmDialog></p-confirmDialog>
|
||||
|
||||
<p class="text-lg flex items-center gap-2 px-4 pt-4 pb-2">
|
||||
Kobo Sync Settings:
|
||||
Kobo Integration Token:
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Click to view Kobo setup documentation"
|
||||
tooltipPosition="right"
|
||||
@@ -10,7 +10,7 @@
|
||||
</i>
|
||||
</p>
|
||||
|
||||
@if (hasPermission) {
|
||||
@if (hasKoboTokenPermission) {
|
||||
<form #koboForm="ngForm" class="px-4 py-2">
|
||||
<div class="flex flex-col px-4 py-4 space-y-4">
|
||||
<div class="flex flex-col gap-1 max-w-[33rem]">
|
||||
@@ -50,6 +50,50 @@
|
||||
</p-button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@if (isAdmin) {
|
||||
<div class="px-4 py-4">
|
||||
<p class="text-lg mb-4">Kobo Settings (Admin Only):</p>
|
||||
<div class="flex flex-col px-4 py-4 space-y-6 max-w-[75rem]">
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<p-toggle-switch
|
||||
id="convertToKepub"
|
||||
[(ngModel)]="koboSettings.convertToKepub"
|
||||
(ngModelChange)="onToggleChange()">
|
||||
</p-toggle-switch>
|
||||
<label for="convertToKepub" class="font-medium">Convert to KEPUB</label>
|
||||
</div>
|
||||
<p class="text-zinc-400 text-sm">
|
||||
<strong>Pros:</strong> KEPUB format enables enhanced Kobo features like better typography, reading stats, and faster page turns.
|
||||
<br>
|
||||
<strong>Cons:</strong> Conversion takes extra processing time and may occasionally fail for complex layouts.
|
||||
Books over the size limit below will skip conversion automatically.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex items-center gap-6">
|
||||
<label for="conversionLimit" class="font-medium">Conversion Size Limit: {{ koboSettings.conversionLimitInMb }} MB</label>
|
||||
</div>
|
||||
<p-slider
|
||||
class="max-w-64"
|
||||
id="conversionLimit"
|
||||
[(ngModel)]="koboSettings.conversionLimitInMb"
|
||||
[min]="1"
|
||||
[max]="250"
|
||||
[step]="1"
|
||||
(ngModelChange)="onSliderChange()">
|
||||
</p-slider>
|
||||
<p class="text-zinc-400 text-sm">
|
||||
Large files (100MB+) can cause conversion timeouts and server strain. Lower limits ensure faster syncing but may skip conversion of larger books.
|
||||
<br>
|
||||
<strong>Recommended:</strong> 50-100MB for most libraries. Very large books will sync as regular EPUB regardless of this setting.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
} @else {
|
||||
<div class="px-4 py-4 m-4 rounded-lg bg-red-700/30 border border-red-600 text-red-200 flex items-center gap-2 max-w-lg">
|
||||
<i class="pi pi-lock text-red-400 text-xl"></i>
|
||||
|
||||
+90
-14
@@ -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<void>();
|
||||
hasPermission = false;
|
||||
private readonly sliderChange$ = new Subject<void>();
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user