Merge pull request #1707 from booklore-app/develop
Merge develop into master for release
This commit is contained in:
@@ -9,38 +9,44 @@ assignees: ''
|
||||
|
||||
# 🐛 Bug Report for Booklore
|
||||
|
||||
Thank you for helping us improve Booklore! Please fill out the sections below.
|
||||
Thank you for taking the time to report this bug. Your feedback helps make Booklore better for everyone!
|
||||
|
||||
Let's squash this bug together! 🔨
|
||||
|
||||
---
|
||||
|
||||
## 📝 What happened?
|
||||
<!-- Describe the bug in a few sentences -->
|
||||
<!-- Describe what went wrong -->
|
||||
|
||||
|
||||
## 🔄 Steps to Reproduce
|
||||
<!-- Walk us through the exact steps to see the bug -->
|
||||
1. Go to '...'
|
||||
2. Click on '...'
|
||||
3. Scroll down to '...'
|
||||
4. See error
|
||||
<!-- Provide detailed steps to reproduce the behavior. Be specific about what you clicked, typed, or configured -->
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
4.
|
||||
|
||||
**Result:** <!-- What happened after these steps? -->
|
||||
|
||||
## ✅ Expected Behavior
|
||||
<!-- What should have happened instead? -->
|
||||
<!-- Describe what should have happened instead -->
|
||||
|
||||
|
||||
## 📸 Screenshots / Error Messages
|
||||
<!-- Add screenshots or paste error messages (drag & drop images here) -->
|
||||
<!-- Share any screenshots or error messages here (just drag & drop) -->
|
||||
|
||||
|
||||
## 💻 Environment
|
||||
- **Version:** (e.g., v1.1.0)
|
||||
<!-- Provide details about your setup - every detail helps! -->
|
||||
- **Booklore Version:** (e.g., v1.1.0)
|
||||
- **OS:** (e.g., Windows 11, macOS Sonoma, Ubuntu 22.04)
|
||||
- **Browser:** (e.g., Chrome 120, Firefox 121, Safari 17)
|
||||
- **Installation:** (e.g., Docker, Unraid, Manual)
|
||||
- **Storage Type:** (e.g., Local HDD/SSD, Synology NAS, SMB Share, NFS Mount, S3 Bucket)
|
||||
|
||||
## 📌 Additional Context
|
||||
<!-- Recent changes? Specific books? Anything else that might help? -->
|
||||
<!-- Add any other relevant information: recent changes, specific books, configuration details, etc. -->
|
||||
|
||||
|
||||
## ✨ Possible Solution _(Optional)_
|
||||
<!-- Have ideas on how to fix this? Share them here! -->
|
||||
<!-- Share any ideas on how to fix this issue -->
|
||||
|
||||
@@ -7,16 +7,34 @@ assignees: ''
|
||||
|
||||
---
|
||||
|
||||
# Feature Request Template for Booklore
|
||||
# ✨ Feature Request for Booklore
|
||||
|
||||
**What problem or limitation are you encountering?**
|
||||
Describe the challenge or issue you’re facing that this feature would address.
|
||||
Thank you for contributing to Booklore's development. Your suggestions help shape the future of this project.
|
||||
|
||||
**What solution or improvement do you propose?**
|
||||
Explain clearly what you’d like Booklore to do or how it could work better.
|
||||
---
|
||||
|
||||
**Have you found any workarounds or alternatives?**
|
||||
Share any other solutions you’ve tried or considered, if any.
|
||||
## 📝 Description
|
||||
<!-- Describe the problem you're facing and the solution you're proposing -->
|
||||
|
||||
**Additional details**
|
||||
Add any extra context, examples, or screenshots that might help us understand your request.
|
||||
|
||||
## 🌟 Benefits
|
||||
<!-- Explain the value this feature would bring and who would benefit from it -->
|
||||
|
||||
|
||||
## 💻 Use Cases
|
||||
<!-- Describe specific scenarios where this feature would be useful -->
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
|
||||
## 📸 Visual References _(Optional)_
|
||||
<!-- Add screenshots, mockups, wireframes, or examples from other applications -->
|
||||
|
||||
|
||||
## 🎨 Technical Details _(Optional)_
|
||||
<!-- Share implementation ideas, alternative solutions, or related features -->
|
||||
|
||||
|
||||
## 📌 Additional Context
|
||||
<!-- Any other information, research, or context that would be helpful -->
|
||||
|
||||
@@ -167,6 +167,7 @@ jobs:
|
||||
docker buildx build \
|
||||
--platform linux/amd64,linux/arm64 \
|
||||
--build-arg APP_VERSION=${{ env.image_tag }} \
|
||||
--build-arg APP_REVISION=${{ github.sha }} \
|
||||
--tag booklore/booklore:${{ env.image_tag }} \
|
||||
--tag ghcr.io/booklore-app/booklore:${{ env.image_tag }} \
|
||||
--push .
|
||||
|
||||
+17
-3
@@ -14,7 +14,7 @@ COPY ./booklore-ui /angular-app/
|
||||
RUN npm run build --configuration=production
|
||||
|
||||
# Stage 2: Build the Spring Boot app with Gradle
|
||||
FROM gradle:9.1-jdk25-alpine AS springboot-build
|
||||
FROM gradle:8.14.3-jdk21-alpine AS springboot-build
|
||||
|
||||
WORKDIR /springboot-app
|
||||
|
||||
@@ -29,7 +29,21 @@ RUN apk add --no-cache yq && \
|
||||
RUN gradle clean build -x test
|
||||
|
||||
# Stage 3: Final image
|
||||
FROM eclipse-temurin:25-jre-alpine
|
||||
FROM eclipse-temurin:21.0.9_10-jre-alpine
|
||||
|
||||
ARG APP_VERSION
|
||||
ARG APP_REVISION
|
||||
|
||||
# Set OCI labels
|
||||
LABEL org.opencontainers.image.title="BookLore" \
|
||||
org.opencontainers.image.description="BookLore: A self-hosted, multi-user digital library with smart shelves, auto metadata, Kobo & KOReader sync, BookDrop imports, OPDS support, and a built-in reader for EPUB, PDF, and comics." \
|
||||
org.opencontainers.image.source="https://github.com/booklore-app/booklore" \
|
||||
org.opencontainers.image.url="https://github.com/booklore-app/booklore" \
|
||||
org.opencontainers.image.documentation="https://booklore-app.github.io/booklore-docs/docs/getting-started" \
|
||||
org.opencontainers.image.version=$APP_VERSION \
|
||||
org.opencontainers.image.revision=$APP_REVISION \
|
||||
org.opencontainers.image.licenses="GPL-3.0" \
|
||||
org.opencontainers.image.base.name="docker.io/library/eclipse-temurin:21.0.9_10-jre-alpine"
|
||||
|
||||
RUN apk update && apk add nginx gettext su-exec
|
||||
|
||||
@@ -41,4 +55,4 @@ RUN chmod +x /start.sh
|
||||
|
||||
EXPOSE 8080 80
|
||||
|
||||
CMD ["/start.sh"]
|
||||
CMD ["/start.sh"]
|
||||
|
||||
+12
-10
@@ -1,8 +1,8 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.5.1'
|
||||
id 'org.springframework.boot' version '3.5.8'
|
||||
id 'io.spring.dependency-management' version '1.1.7'
|
||||
id 'org.hibernate.orm' version '7.1.3.Final'
|
||||
id 'org.hibernate.orm' version '6.6.36.Final'
|
||||
id 'com.github.ben-manes.versions' version '0.53.0'
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ version = '0.0.1-SNAPSHOT'
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(25)
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,8 +39,7 @@ dependencies {
|
||||
|
||||
// --- Database & Migration ---
|
||||
implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.6'
|
||||
implementation 'org.flywaydb:flyway-mysql:11.13.2'
|
||||
implementation 'jakarta.persistence:jakarta.persistence-api:3.2.0'
|
||||
implementation 'org.flywaydb:flyway-mysql:11.18.0'
|
||||
|
||||
// --- Security & Authentication ---
|
||||
implementation 'io.jsonwebtoken:jjwt-api:0.13.0'
|
||||
@@ -52,18 +51,18 @@ dependencies {
|
||||
annotationProcessor 'org.projectlombok:lombok:1.18.42'
|
||||
|
||||
// --- Book & Image Processing ---
|
||||
implementation 'org.apache.pdfbox:pdfbox:3.0.5'
|
||||
implementation 'org.apache.pdfbox:pdfbox:3.0.6'
|
||||
implementation 'org.apache.pdfbox:xmpbox:3.0.6'
|
||||
implementation 'org.apache.pdfbox:jbig2-imageio:3.0.4'
|
||||
implementation 'org.apache.pdfbox:xmpbox:3.0.5'
|
||||
implementation 'com.github.jai-imageio:jai-imageio-core:1.4.0'
|
||||
implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.4.0'
|
||||
implementation 'io.documentnode:epub4j-core:4.2.2'
|
||||
|
||||
// --- UNRAR Support ---
|
||||
implementation 'com.github.junrar:junrar:7.5.5'
|
||||
implementation 'com.github.junrar:junrar:7.5.7'
|
||||
|
||||
// --- JSON & Web Scraping ---
|
||||
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.20.0'
|
||||
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.20.1'
|
||||
implementation 'org.jsoup:jsoup:1.21.2'
|
||||
|
||||
// --- Mapping (DTOs & Entities) ---
|
||||
@@ -71,10 +70,13 @@ dependencies {
|
||||
annotationProcessor 'org.mapstruct:mapstruct-processor:1.6.3'
|
||||
|
||||
// --- API Documentation ---
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.9'
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.14'
|
||||
implementation 'org.apache.commons:commons-compress:1.28.0'
|
||||
implementation 'org.apache.commons:commons-text:1.14.0'
|
||||
|
||||
// --- Template Engine ---
|
||||
implementation 'org.freemarker:freemarker:2.3.33'
|
||||
|
||||
// --- Test Dependencies ---
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testImplementation 'org.assertj:assertj-core:3.27.3'
|
||||
|
||||
BIN
Binary file not shown.
+1
-1
@@ -1,6 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
Vendored
+1
-4
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
@@ -114,7 +114,6 @@ case "$( uname )" in #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
@@ -172,7 +171,6 @@ fi
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
@@ -212,7 +210,6 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
|
||||
Vendored
+1
-2
@@ -70,11 +70,10 @@ goto fail
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
|
||||
+1
-1
@@ -24,6 +24,6 @@ public class OpdsUserDetailsService implements UserDetailsService {
|
||||
OpdsUserV2Entity userV2 = opdsUserV2Repository.findByUsername(username)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
|
||||
OpdsUserV2 mappedCredential = opdsUserV2Mapper.toDto(userV2);
|
||||
return new OpdsUserDetails(mappedCredential, null);
|
||||
return new OpdsUserDetails(mappedCredential);
|
||||
}
|
||||
}
|
||||
+2
-8
@@ -1,6 +1,5 @@
|
||||
package com.adityachandel.booklore.config.security.userdetails;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.OpdsUser;
|
||||
import com.adityachandel.booklore.model.dto.OpdsUserV2;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -15,20 +14,15 @@ import java.util.List;
|
||||
public class OpdsUserDetails implements UserDetails {
|
||||
|
||||
private final OpdsUserV2 opdsUserV2;
|
||||
private final OpdsUser opdsUser;
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
if (opdsUserV2 != null) return opdsUserV2.getUsername();
|
||||
if (opdsUser != null) return opdsUser.getUsername();
|
||||
throw new IllegalStateException("No username available");
|
||||
return opdsUserV2.getUsername();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
if (opdsUserV2 != null) return opdsUserV2.getPasswordHash();
|
||||
if (opdsUser != null) return opdsUser.getPassword();
|
||||
throw new IllegalStateException("No password available");
|
||||
return opdsUserV2.getPasswordHash();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+1
-1
@@ -64,7 +64,7 @@ public class AdditionalFileController {
|
||||
@PreAuthorize("@securityUtil.canDeleteBook() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Void> deleteAdditionalFile(
|
||||
@PathVariable Long bookId,
|
||||
@PathVariable Long fileId) throws IOException {
|
||||
@PathVariable Long fileId) {
|
||||
additionalFileService.deleteAdditionalFile(fileId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ public class FileUploadController {
|
||||
public ResponseEntity<?> uploadFile(
|
||||
@Parameter(description = "File to upload") @RequestParam("file") MultipartFile file,
|
||||
@Parameter(description = "Library ID") @RequestParam("libraryId") long libraryId,
|
||||
@Parameter(description = "Path ID") @RequestParam("pathId") long pathId) throws IOException {
|
||||
@Parameter(description = "Path ID") @RequestParam("pathId") long pathId) {
|
||||
if (file.isEmpty()) {
|
||||
throw new IllegalArgumentException("Uploaded file is missing.");
|
||||
}
|
||||
|
||||
+1
-1
@@ -165,7 +165,7 @@ public class KoboController {
|
||||
@ApiResponse(responseCode = "200", description = "Book downloaded successfully")
|
||||
@GetMapping("/v1/books/{bookId}/download")
|
||||
public void downloadBook(
|
||||
@Parameter(description = "Book ID") @PathVariable String bookId, HttpServletResponse response) throws IOException {
|
||||
@Parameter(description = "Book ID") @PathVariable String bookId, HttpServletResponse response) {
|
||||
if (StringUtils.isNumeric(bookId)) {
|
||||
bookDownloadService.downloadKoboBook(Long.parseLong(bookId), response);
|
||||
} else {
|
||||
|
||||
+18
-16
@@ -38,8 +38,7 @@ public class OpdsController {
|
||||
@ApiResponse(responseCode = "404", description = "Book not found")
|
||||
})
|
||||
@GetMapping("/{bookId}/download")
|
||||
public ResponseEntity<Resource> downloadBook(
|
||||
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
||||
public ResponseEntity<Resource> downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@@ -49,8 +48,7 @@ public class OpdsController {
|
||||
@ApiResponse(responseCode = "404", description = "Book or cover not found")
|
||||
})
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<Resource> getBookCover(
|
||||
@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
public ResponseEntity<Resource> getBookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
Resource coverImage = bookService.getBookThumbnail(bookId);
|
||||
String contentType = "image/jpeg";
|
||||
return ResponseEntity.ok()
|
||||
@@ -62,8 +60,7 @@ public class OpdsController {
|
||||
@Operation(summary = "Get OPDS root catalog", description = "Retrieve the OPDS root navigation feed.")
|
||||
@ApiResponse(responseCode = "200", description = "Root OPDS catalog returned successfully")
|
||||
@GetMapping(produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getRootCatalog(
|
||||
@Parameter(hidden = true) HttpServletRequest request) {
|
||||
public ResponseEntity<String> getRootCatalog(@Parameter(hidden = true) HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateRootNavigation(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||
@@ -73,8 +70,7 @@ public class OpdsController {
|
||||
@Operation(summary = "Get OPDS libraries navigation", description = "Retrieve the OPDS libraries navigation feed.")
|
||||
@ApiResponse(responseCode = "200", description = "Libraries navigation feed returned successfully")
|
||||
@GetMapping(value = "/libraries", produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getLibrariesNavigation(
|
||||
@Parameter(hidden = true) HttpServletRequest request) {
|
||||
public ResponseEntity<String> getLibrariesNavigation(@Parameter(hidden = true) HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateLibrariesNavigation(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||
@@ -84,19 +80,27 @@ public class OpdsController {
|
||||
@Operation(summary = "Get OPDS shelves navigation", description = "Retrieve the OPDS shelves navigation feed.")
|
||||
@ApiResponse(responseCode = "200", description = "Shelves navigation feed returned successfully")
|
||||
@GetMapping(value = "/shelves", produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getShelvesNavigation(
|
||||
@Parameter(hidden = true) HttpServletRequest request) {
|
||||
public ResponseEntity<String> getShelvesNavigation(@Parameter(hidden = true) HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateShelvesNavigation(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get OPDS magic shelves navigation", description = "Retrieve the OPDS magic shelves navigation feed.")
|
||||
@ApiResponse(responseCode = "200", description = "Magic shelves navigation feed returned successfully")
|
||||
@GetMapping(value = "/magic-shelves", produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getMagicShelvesNavigation(@Parameter(hidden = true) HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateMagicShelvesNavigation(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get OPDS catalog feed", description = "Retrieve the OPDS acquisition catalog feed.")
|
||||
@ApiResponse(responseCode = "200", description = "Catalog feed returned successfully")
|
||||
@GetMapping(value = "/catalog", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getCatalog(
|
||||
@Parameter(hidden = true) HttpServletRequest request) {
|
||||
public ResponseEntity<String> getCatalog(@Parameter(hidden = true) HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateCatalogFeed(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
||||
@@ -106,8 +110,7 @@ public class OpdsController {
|
||||
@Operation(summary = "Get recent books feed", description = "Retrieve the OPDS feed for recently added books.")
|
||||
@ApiResponse(responseCode = "200", description = "Recent books feed returned successfully")
|
||||
@GetMapping(value = "/recent", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getRecentBooks(
|
||||
@Parameter(hidden = true) HttpServletRequest request) {
|
||||
public ResponseEntity<String> getRecentBooks(@Parameter(hidden = true) HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateRecentFeed(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
||||
@@ -117,8 +120,7 @@ public class OpdsController {
|
||||
@Operation(summary = "Get surprise feed", description = "Retrieve the OPDS feed for surprise/random books.")
|
||||
@ApiResponse(responseCode = "200", description = "Surprise feed returned successfully")
|
||||
@GetMapping(value = "/surprise", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getSurpriseFeed(
|
||||
@Parameter(hidden = true) HttpServletRequest request) {
|
||||
public ResponseEntity<String> getSurpriseFeed(@Parameter(hidden = true) HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateSurpriseFeed(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
||||
|
||||
+9
-2
@@ -7,14 +7,17 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Converter
|
||||
@Slf4j
|
||||
public class BookRecommendationIdsListConverter implements AttributeConverter<Set<BookRecommendationLite>, String> {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private static final TypeReference<Set<BookRecommendationLite>> SET_TYPE_REF = new TypeReference<>() {};
|
||||
|
||||
static {
|
||||
objectMapper.registerModule(new JavaTimeModule());
|
||||
@@ -22,9 +25,13 @@ public class BookRecommendationIdsListConverter implements AttributeConverter<Se
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(Set<BookRecommendationLite> recommendations) {
|
||||
if (recommendations == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsString(recommendations);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.error("Failed to convert BookRecommendation set to JSON string: {}", recommendations, e);
|
||||
throw new RuntimeException("Error converting BookRecommendation list to JSON", e);
|
||||
}
|
||||
}
|
||||
@@ -35,9 +42,9 @@ public class BookRecommendationIdsListConverter implements AttributeConverter<Se
|
||||
return Set.of();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, new TypeReference<Set<BookRecommendationLite>>() {
|
||||
});
|
||||
return objectMapper.readValue(json, SET_TYPE_REF);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to convert JSON string to BookRecommendation set: {}", json, e);
|
||||
throw new RuntimeException("Error converting JSON to BookRecommendation list", e);
|
||||
}
|
||||
}
|
||||
|
||||
+6
-4
@@ -1,6 +1,7 @@
|
||||
package com.adityachandel.booklore.convertor;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
@@ -10,12 +11,13 @@ import java.util.Map;
|
||||
|
||||
@Converter
|
||||
@Slf4j
|
||||
public class JpaJsonConverter implements AttributeConverter<Map, String> {
|
||||
public class JpaJsonConverter implements AttributeConverter<Map<String, Object>, String> {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private static final TypeReference<Map<String, Object>> MAP_TYPE_REF = new TypeReference<>() {};
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(Map attribute) {
|
||||
public String convertToDatabaseColumn(Map<String, Object> attribute) {
|
||||
if (attribute == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -28,12 +30,12 @@ public class JpaJsonConverter implements AttributeConverter<Map, String> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map convertToEntityAttribute(String dbData) {
|
||||
public Map<String, Object> convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null || dbData.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(dbData, Map.class);
|
||||
return objectMapper.readValue(dbData, MAP_TYPE_REF);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.error("Error converting JSON to map", e);
|
||||
return null;
|
||||
|
||||
+16
-4
@@ -1,31 +1,43 @@
|
||||
package com.adityachandel.booklore.convertor;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
@Converter(autoApply = true)
|
||||
public class MapToStringConverter implements AttributeConverter<Map, String> {
|
||||
@Slf4j
|
||||
public class MapToStringConverter implements AttributeConverter<Map<String, Object>, String> {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private static final TypeReference<Map<String, Object>> MAP_TYPE_REF = new TypeReference<>() {};
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(Map attribute) {
|
||||
public String convertToDatabaseColumn(Map<String, Object> attribute) {
|
||||
if (attribute == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsString(attribute);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to convert map to JSON string: {}", attribute, e);
|
||||
throw new IllegalArgumentException("Error converting Map to String", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map convertToEntityAttribute(String dbData) {
|
||||
public Map<String, Object> convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null || dbData.trim().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(dbData, Map.class);
|
||||
return objectMapper.readValue(dbData, MAP_TYPE_REF);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to convert JSON string to map: {}", dbData, e);
|
||||
throw new IllegalArgumentException("Error converting String to Map", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ public enum ApiError {
|
||||
DEFAULT_EMAIL_RECIPIENT_NOT_FOUND(HttpStatus.NOT_FOUND, " Default Email recipient not found"),
|
||||
UNSUPPORTED_BOOK_TYPE(HttpStatus.BAD_REQUEST, "Unsupported book type for viewer settings"),
|
||||
INVALID_VIEWER_SETTING(HttpStatus.BAD_REQUEST, "Invalid viewer setting for the book"),
|
||||
FILE_READ_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Error reading files from path"),
|
||||
FILE_READ_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Error reading files from path: %s"),
|
||||
IMAGE_NOT_FOUND(HttpStatus.NOT_FOUND, "Image not found or not readable"),
|
||||
INVALID_FILE_FORMAT(HttpStatus.BAD_REQUEST, "Invalid file format, only pdf and epub are supported"),
|
||||
LIBRARY_NOT_FOUND(HttpStatus.NOT_FOUND, "Library not found with ID: %d"),
|
||||
@@ -29,6 +29,7 @@ public enum ApiError {
|
||||
INVALID_QUERY_PARAMETERS(HttpStatus.BAD_REQUEST, "Query parameters are required for the search."),
|
||||
SHELF_ALREADY_EXISTS(HttpStatus.CONFLICT, "Shelf already exists: %s"),
|
||||
SHELF_NOT_FOUND(HttpStatus.NOT_FOUND, "Shelf not found with ID: %d"),
|
||||
MAGIC_SHELF_NOT_FOUND(HttpStatus.NOT_FOUND, "Magic shelf not found with ID: %s"),
|
||||
SCHEDULE_REFRESH_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to schedule metadata refresh job. Error: %s"),
|
||||
ANOTHER_METADATA_JOB_RUNNING(HttpStatus.CONFLICT, "A metadata refresh job is currently running. Please wait for it to complete before initiating a new one."),
|
||||
METADATA_SOURCE_NOT_IMPLEMENT_OR_DOES_NOT_EXIST(HttpStatus.BAD_REQUEST, "Metadata source not implement or does not exist"),
|
||||
|
||||
+2
-1
@@ -4,8 +4,9 @@ import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.KoboSnapshotBookEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface BookEntityToKoboSnapshotBookMapper {
|
||||
|
||||
@Mapping(target = "id", ignore = true)
|
||||
|
||||
@@ -9,12 +9,13 @@ import org.mapstruct.Context;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.Named;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Mapper(componentModel = "spring", uses = {BookMetadataMapper.class, ShelfMapper.class, AdditionalFileMapper.class})
|
||||
@Mapper(componentModel = "spring", uses = {BookMetadataMapper.class, ShelfMapper.class, AdditionalFileMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface BookMapper {
|
||||
|
||||
@Mapping(source = "library.id", target = "libraryId")
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import org.mapstruct.*;
|
||||
|
||||
@Mapper(componentModel = "spring", uses = {AuthorMapper.class, CategoryMapper.class, MoodMapper.class, TagMapper.class})
|
||||
@Mapper(componentModel = "spring", uses = {AuthorMapper.class, CategoryMapper.class, MoodMapper.class, TagMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface BookMetadataMapper {
|
||||
|
||||
@AfterMapping
|
||||
|
||||
+2
-1
@@ -3,8 +3,9 @@ package com.adityachandel.booklore.mapper;
|
||||
import com.adityachandel.booklore.model.dto.BookViewerSetting;
|
||||
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface BookViewerSettingMapper {
|
||||
|
||||
BookViewerSetting toBookViewerSetting(PdfViewerPreferencesEntity entity);
|
||||
|
||||
+2
-1
@@ -5,8 +5,9 @@ import com.adityachandel.booklore.model.dto.request.CreateEmailRecipientRequest;
|
||||
import com.adityachandel.booklore.model.entity.EmailRecipientV2Entity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.MappingTarget;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface EmailRecipientV2Mapper {
|
||||
|
||||
EmailRecipientV2 toDTO(EmailRecipientV2Entity entity);
|
||||
|
||||
+2
-1
@@ -3,9 +3,10 @@ package com.adityachandel.booklore.mapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.EpubMetadata;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface EpubMetadataMapper {
|
||||
|
||||
EpubMetadataMapper INSTANCE = Mappers.getMapper(EpubMetadataMapper.class);
|
||||
|
||||
+2
-1
@@ -3,8 +3,9 @@ package com.adityachandel.booklore.mapper;
|
||||
import com.adityachandel.booklore.model.dto.EpubViewerPreferences;
|
||||
import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface EpubViewerPreferencesMapper {
|
||||
|
||||
EpubViewerPreferences toModel(EpubViewerPreferencesEntity entity);
|
||||
|
||||
+2
-1
@@ -6,10 +6,11 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface KoboReadingStateMapper {
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
+2
-1
@@ -3,11 +3,12 @@ package com.adityachandel.booklore.mapper;
|
||||
import com.adityachandel.booklore.model.dto.KoreaderUser;
|
||||
import com.adityachandel.booklore.model.entity.KoreaderUserEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface KoreaderUserMapper {
|
||||
|
||||
KoreaderUserMapper INSTANCE = Mappers.getMapper(KoreaderUserMapper.class);
|
||||
|
||||
@@ -4,8 +4,9 @@ import com.adityachandel.booklore.model.dto.Library;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface LibraryMapper {
|
||||
|
||||
@Mapping(target = "paths", source = "libraryPaths")
|
||||
|
||||
@@ -3,8 +3,9 @@ package com.adityachandel.booklore.mapper;
|
||||
import com.adityachandel.booklore.model.dto.LibraryPath;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface LibraryPathMapper {
|
||||
|
||||
LibraryPath toLibraryPath(LibraryPathEntity libraryPathEntity);
|
||||
|
||||
+2
-1
@@ -4,8 +4,9 @@ import com.adityachandel.booklore.model.MetadataClearFlags;
|
||||
import com.adityachandel.booklore.model.dto.request.BulkMetadataUpdateRequest;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface MetadataClearFlagsMapper {
|
||||
|
||||
@Mapping(target = "publisher", source = "clearPublisher")
|
||||
|
||||
@@ -4,11 +4,12 @@ import com.adityachandel.booklore.model.entity.OpdsUserV2Entity;
|
||||
import com.adityachandel.booklore.model.dto.OpdsUserV2;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface OpdsUserV2Mapper {
|
||||
|
||||
OpdsUserV2Mapper INSTANCE = Mappers.getMapper(OpdsUserV2Mapper.class);
|
||||
|
||||
+2
-1
@@ -3,8 +3,9 @@ package com.adityachandel.booklore.mapper;
|
||||
import com.adityachandel.booklore.model.dto.PdfViewerPreferences;
|
||||
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface PdfViewerPreferencesMapper {
|
||||
|
||||
PdfViewerPreferences toModel(PdfViewerPreferencesEntity entity);
|
||||
|
||||
@@ -8,11 +8,12 @@ import com.adityachandel.booklore.model.entity.*;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.Named;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Mapper(componentModel = "spring", uses = ShelfMapper.class)
|
||||
@Mapper(componentModel = "spring", uses = ShelfMapper.class, unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface BookMapperV2 {
|
||||
|
||||
@Mapping(source = "library.id", target = "libraryId")
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class GroupRule {
|
||||
private String name;
|
||||
private String type;
|
||||
private JoinType join;
|
||||
private List<Object> rules; // Can be either Rule or GroupRule
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public enum JoinType {
|
||||
@JsonProperty("and")
|
||||
AND,
|
||||
@JsonProperty("or")
|
||||
OR
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Rule {
|
||||
private String type;
|
||||
private RuleField field;
|
||||
private RuleOperator operator;
|
||||
private Object value;
|
||||
private Object valueStart;
|
||||
private Object valueEnd;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public enum RuleField {
|
||||
@JsonProperty("library")
|
||||
LIBRARY,
|
||||
@JsonProperty("title")
|
||||
TITLE,
|
||||
@JsonProperty("subtitle")
|
||||
SUBTITLE,
|
||||
@JsonProperty("authors")
|
||||
AUTHORS,
|
||||
@JsonProperty("categories")
|
||||
CATEGORIES,
|
||||
@JsonProperty("publisher")
|
||||
PUBLISHER,
|
||||
@JsonProperty("publishedDate")
|
||||
PUBLISHED_DATE,
|
||||
@JsonProperty("seriesName")
|
||||
SERIES_NAME,
|
||||
@JsonProperty("seriesNumber")
|
||||
SERIES_NUMBER,
|
||||
@JsonProperty("seriesTotal")
|
||||
SERIES_TOTAL,
|
||||
@JsonProperty("pageCount")
|
||||
PAGE_COUNT,
|
||||
@JsonProperty("language")
|
||||
LANGUAGE,
|
||||
@JsonProperty("amazonRating")
|
||||
AMAZON_RATING,
|
||||
@JsonProperty("amazonReviewCount")
|
||||
AMAZON_REVIEW_COUNT,
|
||||
@JsonProperty("goodreadsRating")
|
||||
GOODREADS_RATING,
|
||||
@JsonProperty("goodreadsReviewCount")
|
||||
GOODREADS_REVIEW_COUNT,
|
||||
@JsonProperty("hardcoverRating")
|
||||
HARDCOVER_RATING,
|
||||
@JsonProperty("hardcoverReviewCount")
|
||||
HARDCOVER_REVIEW_COUNT,
|
||||
@JsonProperty("personalRating")
|
||||
PERSONAL_RATING,
|
||||
@JsonProperty("fileType")
|
||||
FILE_TYPE,
|
||||
@JsonProperty("fileSize")
|
||||
FILE_SIZE,
|
||||
@JsonProperty("readStatus")
|
||||
READ_STATUS,
|
||||
@JsonProperty("dateFinished")
|
||||
DATE_FINISHED,
|
||||
@JsonProperty("lastReadTime")
|
||||
LAST_READ_TIME,
|
||||
@JsonProperty("metadataScore")
|
||||
METADATA_SCORE,
|
||||
@JsonProperty("moods")
|
||||
MOODS,
|
||||
@JsonProperty("tags")
|
||||
TAGS
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public enum RuleOperator {
|
||||
@JsonProperty("equals")
|
||||
EQUALS,
|
||||
@JsonProperty("not_equals")
|
||||
NOT_EQUALS,
|
||||
@JsonProperty("contains")
|
||||
CONTAINS,
|
||||
@JsonProperty("does_not_contain")
|
||||
DOES_NOT_CONTAIN,
|
||||
@JsonProperty("starts_with")
|
||||
STARTS_WITH,
|
||||
@JsonProperty("ends_with")
|
||||
ENDS_WITH,
|
||||
@JsonProperty("greater_than")
|
||||
GREATER_THAN,
|
||||
@JsonProperty("greater_than_equal_to")
|
||||
GREATER_THAN_EQUAL_TO,
|
||||
@JsonProperty("less_than")
|
||||
LESS_THAN,
|
||||
@JsonProperty("less_than_equal_to")
|
||||
LESS_THAN_EQUAL_TO,
|
||||
@JsonProperty("in_between")
|
||||
IN_BETWEEN,
|
||||
@JsonProperty("is_empty")
|
||||
IS_EMPTY,
|
||||
@JsonProperty("is_not_empty")
|
||||
IS_NOT_EMPTY,
|
||||
@JsonProperty("includes_any")
|
||||
INCLUDES_ANY,
|
||||
@JsonProperty("excludes_all")
|
||||
EXCLUDES_ALL,
|
||||
@JsonProperty("includes_all")
|
||||
INCLUDES_ALL
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.adityachandel.booklore.model.dto.kobo;
|
||||
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonNaming;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
|
||||
public class ChangedReadingState implements Entitlement {
|
||||
|
||||
private WrappedReadingState changedReadingState;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
|
||||
public static class WrappedReadingState {
|
||||
private KoboReadingState readingState;
|
||||
}
|
||||
}
|
||||
+1
@@ -15,6 +15,7 @@ import lombok.NoArgsConstructor;
|
||||
public class KoboAuthentication {
|
||||
private String accessToken;
|
||||
private String refreshToken;
|
||||
@Builder.Default
|
||||
private String tokenType = "Bearer";
|
||||
private String trackingId;
|
||||
private String userKey;
|
||||
|
||||
+1
@@ -17,6 +17,7 @@ import lombok.NoArgsConstructor;
|
||||
public class TaskCreateRequest {
|
||||
private String taskId;
|
||||
private TaskType taskType;
|
||||
@Builder.Default
|
||||
private boolean triggeredByCron = false;
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "taskType", include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
|
||||
|
||||
+3
@@ -8,4 +8,7 @@ import lombok.Data;
|
||||
public class KoboSettings {
|
||||
private boolean convertToKepub;
|
||||
private int conversionLimitInMb;
|
||||
private boolean convertCbxToEpub;
|
||||
private int conversionLimitInMbForCbx;
|
||||
private boolean forceEnableHyphenation;
|
||||
}
|
||||
|
||||
+3
-4
@@ -28,13 +28,12 @@ public class AuthorEntity {
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
AuthorEntity authorEntity = (AuthorEntity) o;
|
||||
return Objects.equals(name, authorEntity.name);
|
||||
if (!(o instanceof AuthorEntity that)) return false;
|
||||
return getId() != null && Objects.equals(getId(), that.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return name != null ? name.hashCode() : 0;
|
||||
return getClass().hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.adityachandel.booklore.model.entity;
|
||||
import com.adityachandel.booklore.convertor.BookRecommendationIdsListConverter;
|
||||
import com.adityachandel.booklore.model.dto.BookRecommendationLite;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@@ -62,6 +61,7 @@ public class BookEntity {
|
||||
private String currentHash;
|
||||
|
||||
@Column(name = "deleted")
|
||||
@Builder.Default
|
||||
private Boolean deleted = Boolean.FALSE;
|
||||
|
||||
@Column(name = "deleted_at")
|
||||
@@ -82,6 +82,9 @@ public class BookEntity {
|
||||
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
private List<BookAdditionalFileEntity> additionalFiles;
|
||||
|
||||
@OneToMany(mappedBy = "book", fetch = FetchType.LAZY)
|
||||
private List<UserBookProgressEntity> userBookProgress;
|
||||
|
||||
public Path getFullFilePath() {
|
||||
if (libraryPath == null || libraryPath.getPath() == null || fileSubPath == null || fileName == null) {
|
||||
throw new IllegalStateException("Cannot construct file path: missing library path, file subpath, or file name");
|
||||
|
||||
+2
@@ -48,6 +48,7 @@ public class BookLoreUserEntity {
|
||||
private UserPermissionsEntity permissions;
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
@Builder.Default
|
||||
private Set<ShelfEntity> shelves = new HashSet<>();
|
||||
|
||||
@ManyToMany(fetch = FetchType.EAGER)
|
||||
@@ -59,6 +60,7 @@ public class BookLoreUserEntity {
|
||||
private List<LibraryEntity> libraries;
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
|
||||
@Builder.Default
|
||||
private Set<UserSettingEntity> settings = new HashSet<>();
|
||||
|
||||
@OneToOne(mappedBy = "bookLoreUser", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
|
||||
+4
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.model.entity;
|
||||
import jakarta.persistence.Embeddable;
|
||||
import lombok.*;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -13,6 +14,9 @@ import java.util.Objects;
|
||||
@AllArgsConstructor
|
||||
public class BookMetadataAuthorKey implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long bookId;
|
||||
private Long authorId;
|
||||
|
||||
|
||||
+4
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.model.entity;
|
||||
import jakarta.persistence.Embeddable;
|
||||
import lombok.*;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -13,6 +14,9 @@ import java.util.Objects;
|
||||
@AllArgsConstructor
|
||||
public class BookMetadataCategoryKey implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long bookId;
|
||||
private Long categoryId;
|
||||
|
||||
|
||||
+31
@@ -107,93 +107,123 @@ public class BookMetadataEntity {
|
||||
|
||||
|
||||
@Column(name = "title_locked")
|
||||
@Builder.Default
|
||||
private Boolean titleLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "subtitle_locked")
|
||||
@Builder.Default
|
||||
private Boolean subtitleLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "publisher_locked")
|
||||
@Builder.Default
|
||||
private Boolean publisherLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "published_date_locked")
|
||||
@Builder.Default
|
||||
private Boolean publishedDateLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "description_locked")
|
||||
@Builder.Default
|
||||
private Boolean descriptionLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "isbn_13_locked")
|
||||
@Builder.Default
|
||||
private Boolean isbn13Locked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "isbn_10_locked")
|
||||
@Builder.Default
|
||||
private Boolean isbn10Locked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "asin_locked")
|
||||
@Builder.Default
|
||||
private Boolean asinLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "page_count_locked")
|
||||
@Builder.Default
|
||||
private Boolean pageCountLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "language_locked")
|
||||
@Builder.Default
|
||||
private Boolean languageLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "amazon_rating_locked")
|
||||
@Builder.Default
|
||||
private Boolean amazonRatingLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "amazon_review_count_locked")
|
||||
@Builder.Default
|
||||
private Boolean amazonReviewCountLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "goodreads_rating_locked")
|
||||
@Builder.Default
|
||||
private Boolean goodreadsRatingLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "goodreads_review_count_locked")
|
||||
@Builder.Default
|
||||
private Boolean goodreadsReviewCountLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "hardcover_rating_locked")
|
||||
@Builder.Default
|
||||
private Boolean hardcoverRatingLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "hardcover_review_count_locked")
|
||||
@Builder.Default
|
||||
private Boolean hardcoverReviewCountLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "personal_rating_locked")
|
||||
@Builder.Default
|
||||
private Boolean personalRatingLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "cover_locked")
|
||||
@Builder.Default
|
||||
private Boolean coverLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "series_name_locked")
|
||||
@Builder.Default
|
||||
private Boolean seriesNameLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "series_number_locked")
|
||||
@Builder.Default
|
||||
private Boolean seriesNumberLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "series_total_locked")
|
||||
@Builder.Default
|
||||
private Boolean seriesTotalLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "authors_locked")
|
||||
@Builder.Default
|
||||
private Boolean authorsLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "categories_locked")
|
||||
@Builder.Default
|
||||
private Boolean categoriesLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "moods_locked")
|
||||
@Builder.Default
|
||||
private Boolean moodsLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "tags_locked")
|
||||
@Builder.Default
|
||||
private Boolean tagsLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "goodreads_id_locked")
|
||||
@Builder.Default
|
||||
private Boolean goodreadsIdLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "hardcover_id_locked")
|
||||
@Builder.Default
|
||||
private Boolean hardcoverIdLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "google_id_locked")
|
||||
@Builder.Default
|
||||
private Boolean googleIdLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "comicvine_id_locked")
|
||||
@Builder.Default
|
||||
private Boolean comicvineIdLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "reviews_locked")
|
||||
@Builder.Default
|
||||
private Boolean reviewsLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "embedding_vector", columnDefinition = "TEXT")
|
||||
@@ -245,6 +275,7 @@ public class BookMetadataEntity {
|
||||
|
||||
@OneToMany(mappedBy = "bookMetadata", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
@Fetch(FetchMode.SUBSELECT)
|
||||
@Builder.Default
|
||||
private Set<BookReviewEntity> reviews = new HashSet<>();
|
||||
|
||||
public void applyLockToAllFields(boolean lock) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.model.entity;
|
||||
import jakarta.persistence.Embeddable;
|
||||
import lombok.*;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -13,6 +14,9 @@ import java.util.Objects;
|
||||
@AllArgsConstructor
|
||||
public class BookShelfKey implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long bookId;
|
||||
private Long shelfId;
|
||||
|
||||
|
||||
+1
@@ -31,6 +31,7 @@ public class BookdropFileEntity {
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "status", length = 20, nullable = false)
|
||||
@Builder.Default
|
||||
private Status status = Status.PENDING_REVIEW;
|
||||
|
||||
@Lob
|
||||
|
||||
+4
-2
@@ -4,6 +4,7 @@ import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@@ -23,18 +24,19 @@ public class CategoryEntity {
|
||||
private String name;
|
||||
|
||||
@ManyToMany(mappedBy = "categories", fetch = FetchType.LAZY)
|
||||
@Builder.Default
|
||||
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof CategoryEntity that)) return false;
|
||||
return name != null && name.equalsIgnoreCase(that.name);
|
||||
return getId() != null && Objects.equals(getId(), that.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return name != null ? name.toLowerCase().hashCode() : 0;
|
||||
return getClass().hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -31,5 +31,6 @@ public class KoboUserSettingsEntity {
|
||||
private Float progressMarkAsReadingThreshold = 1f;
|
||||
|
||||
@Column(name = "progress_mark_as_finished_threshold")
|
||||
@Builder.Default
|
||||
private Float progressMarkAsFinishedThreshold = 99f;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ public class LibraryEntity {
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "scan_mode", nullable = false)
|
||||
@Builder.Default
|
||||
private LibraryScanMode scanMode = LibraryScanMode.FILE_AS_BOOK;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
|
||||
+1
@@ -44,5 +44,6 @@ public class MetadataFetchJobEntity {
|
||||
private Integer completedBooks;
|
||||
|
||||
@OneToMany(mappedBy = "job", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
@Builder.Default
|
||||
private List<MetadataFetchProposalEntity> proposals = new ArrayList<>();
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@@ -23,18 +24,19 @@ public class MoodEntity {
|
||||
private String name;
|
||||
|
||||
@ManyToMany(mappedBy = "moods", fetch = FetchType.LAZY)
|
||||
@Builder.Default
|
||||
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof MoodEntity that)) return false;
|
||||
return name != null && name.equalsIgnoreCase(that.name);
|
||||
return getId() != null && Objects.equals(getId(), that.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return name != null ? name.toLowerCase().hashCode() : 0;
|
||||
return getClass().hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.util.Set;
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@EqualsAndHashCode(of = "id")
|
||||
@Entity
|
||||
@Table(name = "shelf")
|
||||
public class ShelfEntity {
|
||||
@@ -39,5 +40,6 @@ public class ShelfEntity {
|
||||
joinColumns = {@JoinColumn(name = "shelf_id")},
|
||||
inverseJoinColumns = {@JoinColumn(name = "book_id")}
|
||||
)
|
||||
@Builder.Default
|
||||
private Set<BookEntity> bookEntities = new HashSet<>();
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@@ -23,17 +24,18 @@ public class TagEntity {
|
||||
private String name;
|
||||
|
||||
@ManyToMany(mappedBy = "tags", fetch = FetchType.LAZY)
|
||||
@Builder.Default
|
||||
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof TagEntity that)) return false;
|
||||
return name != null && name.equalsIgnoreCase(that.name);
|
||||
return getId() != null && Objects.equals(getId(), that.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return name != null ? name.toLowerCase().hashCode() : 0;
|
||||
return getClass().hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
+11
-2
@@ -82,6 +82,15 @@ public class UserBookProgressEntity {
|
||||
@Column(name = "koreader_last_sync_time")
|
||||
private Instant koreaderLastSyncTime;
|
||||
|
||||
@Column(name = "kobo_last_sync_time")
|
||||
private Instant koboLastSyncTime;
|
||||
@Column(name = "kobo_progress_received_time")
|
||||
private Instant koboProgressReceivedTime;
|
||||
|
||||
@Column(name = "kobo_status_sent_time")
|
||||
private Instant koboStatusSentTime;
|
||||
|
||||
@Column(name = "kobo_progress_sent_time")
|
||||
private Instant koboProgressSentTime;
|
||||
|
||||
@Column(name = "read_status_modified_time")
|
||||
private Instant readStatusModifiedTime;
|
||||
}
|
||||
@@ -8,5 +8,6 @@ public enum ReadStatus {
|
||||
PARTIALLY_READ,
|
||||
PAUSED,
|
||||
WONT_READ,
|
||||
ABANDONED
|
||||
ABANDONED,
|
||||
UNSET
|
||||
}
|
||||
|
||||
+15
-2
@@ -19,8 +19,6 @@ import java.util.Set;
|
||||
public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpecificationExecutor<BookEntity> {
|
||||
Optional<BookEntity> findBookByIdAndLibraryId(long id, long libraryId);
|
||||
|
||||
Optional<BookEntity> findBookByFileNameAndLibraryId(String fileName, long libraryId);
|
||||
|
||||
Optional<BookEntity> findByCurrentHash(String currentHash);
|
||||
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
@@ -126,4 +124,19 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
@Param("fileName") String fileName,
|
||||
@Param("libraryId") Long libraryId,
|
||||
@Param("libraryPath") LibraryPathEntity libraryPath);
|
||||
|
||||
@Query(value = """
|
||||
SELECT *
|
||||
FROM book
|
||||
WHERE library_id = :libraryId
|
||||
AND library_path_id = :libraryPathId
|
||||
AND file_sub_path = :fileSubPath
|
||||
AND file_name = :fileName
|
||||
LIMIT 1
|
||||
""", nativeQuery = true)
|
||||
Optional<BookEntity> findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
|
||||
@Param("libraryId") Long libraryId,
|
||||
@Param("libraryPathId") Long libraryPathId,
|
||||
@Param("fileSubPath") String fileSubPath,
|
||||
@Param("fileName") String fileName);
|
||||
}
|
||||
|
||||
+26
@@ -2,6 +2,8 @@ package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
@@ -14,4 +16,28 @@ public interface UserBookProgressRepository extends JpaRepository<UserBookProgre
|
||||
Optional<UserBookProgressEntity> findByUserIdAndBookId(Long userId, Long bookId);
|
||||
|
||||
List<UserBookProgressEntity> findByUserIdAndBookIdIn(Long userId, Set<Long> bookIds);
|
||||
|
||||
@Query("""
|
||||
SELECT ubp FROM UserBookProgressEntity ubp
|
||||
WHERE ubp.user.id = :userId
|
||||
AND ubp.book.id IN (
|
||||
SELECT ksb.bookId FROM KoboSnapshotBookEntity ksb
|
||||
WHERE ksb.snapshot.id = :snapshotId
|
||||
)
|
||||
AND (
|
||||
(ubp.readStatusModifiedTime IS NOT NULL AND (
|
||||
ubp.koboStatusSentTime IS NULL
|
||||
OR ubp.readStatusModifiedTime > ubp.koboStatusSentTime
|
||||
))
|
||||
OR
|
||||
(ubp.koboProgressReceivedTime IS NOT NULL AND (
|
||||
ubp.koboProgressSentTime IS NULL
|
||||
OR ubp.koboProgressReceivedTime > ubp.koboProgressSentTime
|
||||
))
|
||||
)
|
||||
""")
|
||||
List<UserBookProgressEntity> findAllBooksNeedingKoboSync(
|
||||
@Param("userId") Long userId,
|
||||
@Param("snapshotId") String snapshotId
|
||||
);
|
||||
}
|
||||
|
||||
+449
@@ -0,0 +1,449 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.GroupRule;
|
||||
import com.adityachandel.booklore.model.dto.Rule;
|
||||
import com.adityachandel.booklore.model.dto.RuleField;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.persistence.criteria.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class BookRuleEvaluatorService {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public Specification<BookEntity> toSpecification(GroupRule groupRule, Long userId) {
|
||||
return (root, query, cb) -> {
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin = root.join("userBookProgress", JoinType.LEFT);
|
||||
|
||||
Predicate userPredicate = cb.or(
|
||||
cb.isNull(progressJoin.get("user").get("id")),
|
||||
cb.equal(progressJoin.get("user").get("id"), userId)
|
||||
);
|
||||
|
||||
Predicate rulePredicate = buildPredicate(groupRule, cb, root, progressJoin);
|
||||
|
||||
return cb.and(userPredicate, rulePredicate);
|
||||
};
|
||||
}
|
||||
|
||||
private Predicate buildPredicate(GroupRule group, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
if (group.getRules() == null || group.getRules().isEmpty()) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
|
||||
for (Object ruleObj : group.getRules()) {
|
||||
if (ruleObj == null) continue;
|
||||
|
||||
Map<String, Object> ruleMap = objectMapper.convertValue(ruleObj, new TypeReference<>() {
|
||||
});
|
||||
String type = (String) ruleMap.get("type");
|
||||
|
||||
if ("group".equals(type)) {
|
||||
GroupRule subGroup = objectMapper.convertValue(ruleObj, GroupRule.class);
|
||||
predicates.add(buildPredicate(subGroup, cb, root, progressJoin));
|
||||
} else {
|
||||
try {
|
||||
Rule rule = objectMapper.convertValue(ruleObj, Rule.class);
|
||||
Predicate rulePredicate = buildRulePredicate(rule, cb, root, progressJoin);
|
||||
if (rulePredicate != null) {
|
||||
predicates.add(rulePredicate);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to parse rule: {}, error: {}", ruleObj, e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (predicates.isEmpty()) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
|
||||
return group.getJoin() == com.adityachandel.booklore.model.dto.JoinType.AND
|
||||
? cb.and(predicates.toArray(new Predicate[0]))
|
||||
: cb.or(predicates.toArray(new Predicate[0]));
|
||||
}
|
||||
|
||||
private Predicate buildRulePredicate(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
if (rule.getField() == null || rule.getOperator() == null) return null;
|
||||
|
||||
return switch (rule.getOperator()) {
|
||||
case EQUALS -> buildEquals(rule, cb, root, progressJoin);
|
||||
case NOT_EQUALS -> buildNotEquals(rule, cb, root, progressJoin);
|
||||
case CONTAINS -> buildContains(rule, cb, root, progressJoin);
|
||||
case DOES_NOT_CONTAIN -> cb.not(buildContains(rule, cb, root, progressJoin));
|
||||
case STARTS_WITH -> buildStartsWith(rule, cb, root, progressJoin);
|
||||
case ENDS_WITH -> buildEndsWith(rule, cb, root, progressJoin);
|
||||
case GREATER_THAN -> buildGreaterThan(rule, cb, root, progressJoin);
|
||||
case GREATER_THAN_EQUAL_TO -> buildGreaterThanEqual(rule, cb, root, progressJoin);
|
||||
case LESS_THAN -> buildLessThan(rule, cb, root, progressJoin);
|
||||
case LESS_THAN_EQUAL_TO -> buildLessThanEqual(rule, cb, root, progressJoin);
|
||||
case IN_BETWEEN -> buildInBetween(rule, cb, root, progressJoin);
|
||||
case IS_EMPTY -> buildIsEmpty(rule, cb, root, progressJoin);
|
||||
case IS_NOT_EMPTY -> cb.not(buildIsEmpty(rule, cb, root, progressJoin));
|
||||
case INCLUDES_ANY -> buildIncludesAny(rule, cb, root, progressJoin);
|
||||
case EXCLUDES_ALL -> buildExcludesAll(rule, cb, root, progressJoin);
|
||||
case INCLUDES_ALL -> buildIncludesAll(rule, cb, root, progressJoin);
|
||||
};
|
||||
}
|
||||
|
||||
private Predicate buildEquals(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
List<String> ruleList = toStringList(rule.getValue());
|
||||
|
||||
if (isArrayField(rule.getField())) {
|
||||
return buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, false);
|
||||
}
|
||||
|
||||
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||
if (field == null) return cb.conjunction();
|
||||
|
||||
Object value = normalizeValue(rule.getValue(), rule.getField());
|
||||
|
||||
if (value instanceof LocalDateTime) {
|
||||
return cb.equal(field, value);
|
||||
} else if (rule.getField() == RuleField.READ_STATUS) {
|
||||
if ("UNSET".equals(value.toString())) {
|
||||
return cb.isNull(field);
|
||||
}
|
||||
return cb.equal(field, value.toString());
|
||||
} else if (value instanceof Number) {
|
||||
return cb.equal(field, value);
|
||||
}
|
||||
return cb.equal(cb.lower(field.as(String.class)), value.toString().toLowerCase());
|
||||
}
|
||||
|
||||
private Predicate buildNotEquals(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return cb.not(buildEquals(rule, cb, root, progressJoin));
|
||||
}
|
||||
|
||||
private Predicate buildContains(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
String ruleVal = rule.getValue().toString().toLowerCase();
|
||||
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
|
||||
nameField -> cb.like(cb.lower(nameField), "%" + escapeLike(ruleVal) + "%"));
|
||||
}
|
||||
|
||||
private Predicate buildStartsWith(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
String ruleVal = rule.getValue().toString().toLowerCase();
|
||||
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
|
||||
nameField -> cb.like(cb.lower(nameField), escapeLike(ruleVal) + "%"));
|
||||
}
|
||||
|
||||
private Predicate buildEndsWith(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
String ruleVal = rule.getValue().toString().toLowerCase();
|
||||
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
|
||||
nameField -> cb.like(cb.lower(nameField), "%" + escapeLike(ruleVal)));
|
||||
}
|
||||
|
||||
private Predicate buildStringPredicate(RuleField field, Root<BookEntity> root,
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin,
|
||||
CriteriaBuilder cb,
|
||||
java.util.function.Function<Expression<String>, Predicate> predicateBuilder) {
|
||||
if (isArrayField(field)) {
|
||||
Join<?, ?> arrayJoin = createArrayFieldJoin(field, root);
|
||||
Expression<String> nameField = getArrayFieldNameExpression(field, arrayJoin);
|
||||
return predicateBuilder.apply(nameField);
|
||||
}
|
||||
|
||||
Expression<?> fieldExpr = getFieldExpression(field, cb, root, progressJoin);
|
||||
if (fieldExpr == null) return cb.conjunction();
|
||||
|
||||
return predicateBuilder.apply(fieldExpr.as(String.class));
|
||||
}
|
||||
|
||||
private Predicate buildGreaterThan(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||
(field, dateValue) -> cb.greaterThan(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.gt(field.as(Number.class), numValue));
|
||||
}
|
||||
|
||||
private Predicate buildGreaterThanEqual(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||
(field, dateValue) -> cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.ge(field.as(Number.class), numValue));
|
||||
}
|
||||
|
||||
private Predicate buildLessThan(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||
(field, dateValue) -> cb.lessThan(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.lt(field.as(Number.class), numValue));
|
||||
}
|
||||
|
||||
private Predicate buildLessThanEqual(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||
(field, dateValue) -> cb.lessThanOrEqualTo(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.le(field.as(Number.class), numValue));
|
||||
}
|
||||
|
||||
private Predicate buildComparisonPredicate(Rule rule, CriteriaBuilder cb, Root<BookEntity> root,
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin,
|
||||
BiFunction<Expression<?>, LocalDateTime, Predicate> dateComparator,
|
||||
BiFunction<Expression<?>, Double, Predicate> numberComparator) {
|
||||
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||
if (field == null) return cb.conjunction();
|
||||
|
||||
Object value = normalizeValue(rule.getValue(), rule.getField());
|
||||
|
||||
if (value instanceof LocalDateTime) {
|
||||
return dateComparator.apply(field, (LocalDateTime) value);
|
||||
}
|
||||
return numberComparator.apply(field, ((Number) value).doubleValue());
|
||||
}
|
||||
|
||||
private Predicate buildInBetween(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||
if (field == null) return cb.conjunction();
|
||||
|
||||
Object start = normalizeValue(rule.getValueStart(), rule.getField());
|
||||
Object end = normalizeValue(rule.getValueEnd(), rule.getField());
|
||||
|
||||
if (start == null || end == null) return cb.conjunction();
|
||||
|
||||
if (start instanceof LocalDateTime && end instanceof LocalDateTime) {
|
||||
return cb.between(field.as(LocalDateTime.class), (LocalDateTime) start, (LocalDateTime) end);
|
||||
}
|
||||
|
||||
if (!(start instanceof Number) || !(end instanceof Number)) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
|
||||
return cb.between(field.as(Double.class), ((Number) start).doubleValue(), ((Number) end).doubleValue());
|
||||
}
|
||||
|
||||
private Predicate buildIsEmpty(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
if (isArrayField(rule.getField())) {
|
||||
Subquery<Long> subquery = cb.createQuery().subquery(Long.class);
|
||||
Root<BookEntity> subRoot = subquery.from(BookEntity.class);
|
||||
|
||||
Join<Object, Object> metadataJoin = subRoot.join("metadata", JoinType.INNER);
|
||||
joinArrayField(rule.getField(), metadataJoin);
|
||||
|
||||
subquery.select(cb.literal(1L)).where(cb.equal(subRoot.get("id"), root.get("id")));
|
||||
|
||||
return cb.not(cb.exists(subquery));
|
||||
}
|
||||
|
||||
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||
if (field == null) return cb.conjunction();
|
||||
|
||||
return cb.or(cb.isNull(field), cb.equal(cb.trim(field.as(String.class)), ""));
|
||||
}
|
||||
|
||||
private Predicate buildIncludesAny(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
List<String> ruleList = toStringList(rule.getValue());
|
||||
|
||||
if (isArrayField(rule.getField())) {
|
||||
return buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, false);
|
||||
}
|
||||
|
||||
return buildFieldInPredicate(rule.getField(), field -> field, ruleList, cb, progressJoin);
|
||||
}
|
||||
|
||||
private Predicate buildExcludesAll(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
List<String> ruleList = toStringList(rule.getValue());
|
||||
|
||||
if (isArrayField(rule.getField())) {
|
||||
return cb.not(buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, false));
|
||||
}
|
||||
|
||||
return cb.not(buildFieldInPredicate(rule.getField(), field -> field, ruleList, cb, progressJoin));
|
||||
}
|
||||
|
||||
private Predicate buildIncludesAll(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
List<String> ruleList = toStringList(rule.getValue());
|
||||
|
||||
if (isArrayField(rule.getField())) {
|
||||
return buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, true);
|
||||
}
|
||||
|
||||
return buildFieldInPredicate(rule.getField(), field -> field, ruleList, cb, progressJoin);
|
||||
}
|
||||
|
||||
private Predicate buildFieldInPredicate(RuleField ruleField,
|
||||
java.util.function.Function<Expression<?>, Expression<?>> fieldTransformer,
|
||||
List<String> ruleList,
|
||||
CriteriaBuilder cb,
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
Expression<?> field = fieldTransformer.apply(getFieldExpression(ruleField, cb, null, progressJoin));
|
||||
if (field == null) return cb.conjunction();
|
||||
|
||||
if (ruleField == RuleField.READ_STATUS) {
|
||||
boolean hasUnset = ruleList.stream().anyMatch("UNSET"::equals);
|
||||
List<String> nonUnsetValues = ruleList.stream()
|
||||
.filter(v -> !"UNSET".equals(v))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (hasUnset && !nonUnsetValues.isEmpty()) {
|
||||
return cb.or(
|
||||
cb.isNull(field),
|
||||
field.as(String.class).in(nonUnsetValues)
|
||||
);
|
||||
} else if (hasUnset) {
|
||||
return cb.isNull(field);
|
||||
} else {
|
||||
return field.as(String.class).in(nonUnsetValues);
|
||||
}
|
||||
}
|
||||
|
||||
List<String> lowerList = ruleList.stream().map(String::toLowerCase).collect(Collectors.toList());
|
||||
return cb.lower(field.as(String.class)).in(lowerList);
|
||||
}
|
||||
|
||||
private Expression<?> getFieldExpression(RuleField field, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return switch (field) {
|
||||
case LIBRARY -> root.get("library").get("id");
|
||||
case READ_STATUS -> progressJoin.get("readStatus");
|
||||
case DATE_FINISHED -> progressJoin.get("dateFinished");
|
||||
case LAST_READ_TIME -> progressJoin.get("lastReadTime");
|
||||
case FILE_SIZE -> root.get("fileSizeKb");
|
||||
case METADATA_SCORE -> root.get("metadataMatchScore");
|
||||
case TITLE -> root.get("metadata").get("title");
|
||||
case SUBTITLE -> root.get("metadata").get("subtitle");
|
||||
case PUBLISHER -> root.get("metadata").get("publisher");
|
||||
case PUBLISHED_DATE -> root.get("metadata").get("publishedDate");
|
||||
case PERSONAL_RATING -> root.get("metadata").get("personalRating");
|
||||
case PAGE_COUNT -> root.get("metadata").get("pageCount");
|
||||
case LANGUAGE -> root.get("metadata").get("language");
|
||||
case SERIES_NAME -> root.get("metadata").get("seriesName");
|
||||
case SERIES_NUMBER -> root.get("metadata").get("seriesNumber");
|
||||
case SERIES_TOTAL -> root.get("metadata").get("seriesTotal");
|
||||
case AMAZON_RATING -> root.get("metadata").get("amazonRating");
|
||||
case AMAZON_REVIEW_COUNT -> root.get("metadata").get("amazonReviewCount");
|
||||
case GOODREADS_RATING -> root.get("metadata").get("goodreadsRating");
|
||||
case GOODREADS_REVIEW_COUNT -> root.get("metadata").get("goodreadsReviewCount");
|
||||
case HARDCOVER_RATING -> root.get("metadata").get("hardcoverRating");
|
||||
case HARDCOVER_REVIEW_COUNT -> root.get("metadata").get("hardcoverReviewCount");
|
||||
case FILE_TYPE -> cb.function("SUBSTRING_INDEX", String.class,
|
||||
root.get("fileName"), cb.literal("."), cb.literal(-1));
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private boolean isArrayField(RuleField field) {
|
||||
return field == RuleField.AUTHORS || field == RuleField.CATEGORIES ||
|
||||
field == RuleField.MOODS || field == RuleField.TAGS;
|
||||
}
|
||||
|
||||
private Join<?, ?> createArrayFieldJoin(RuleField field, Root<BookEntity> root) {
|
||||
Join<Object, Object> metadataJoin = root.join("metadata", JoinType.INNER);
|
||||
return joinArrayField(field, metadataJoin);
|
||||
}
|
||||
|
||||
private Expression<String> getArrayFieldNameExpression(RuleField field, Join<?, ?> arrayJoin) {
|
||||
return arrayJoin.get("name");
|
||||
}
|
||||
|
||||
private Join<?, ?> joinArrayField(RuleField field, Join<Object, Object> metadataJoin) {
|
||||
return switch (field) {
|
||||
case AUTHORS -> metadataJoin.join("authors", JoinType.INNER);
|
||||
case CATEGORIES -> metadataJoin.join("categories", JoinType.INNER);
|
||||
case MOODS -> metadataJoin.join("moods", JoinType.INNER);
|
||||
case TAGS -> metadataJoin.join("tags", JoinType.INNER);
|
||||
default -> throw new IllegalArgumentException("Not an array field: " + field);
|
||||
};
|
||||
}
|
||||
|
||||
private Predicate buildArrayFieldPredicate(RuleField field, List<String> values, CriteriaBuilder cb, Root<BookEntity> root, boolean includesAll) {
|
||||
if (values.isEmpty()) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
if (includesAll) {
|
||||
List<Predicate> predicates = values.stream()
|
||||
.map(value -> {
|
||||
Join<?, ?> arrayJoin = createArrayFieldJoin(field, root);
|
||||
Expression<String> nameField = getArrayFieldNameExpression(field, arrayJoin);
|
||||
return cb.equal(cb.lower(nameField), value.toLowerCase());
|
||||
})
|
||||
.toList();
|
||||
|
||||
return cb.and(predicates.toArray(new Predicate[0]));
|
||||
} else {
|
||||
Join<?, ?> arrayJoin = createArrayFieldJoin(field, root);
|
||||
Expression<String> nameField = getArrayFieldNameExpression(field, arrayJoin);
|
||||
|
||||
List<String> lowerValues = values.stream()
|
||||
.map(String::toLowerCase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return cb.lower(nameField).in(lowerValues);
|
||||
}
|
||||
}
|
||||
|
||||
private Object normalizeValue(Object value, RuleField field) {
|
||||
if (value == null) return null;
|
||||
|
||||
if (field == RuleField.PUBLISHED_DATE) {
|
||||
return parseDate(value);
|
||||
}
|
||||
|
||||
if (field == RuleField.DATE_FINISHED || field == RuleField.LAST_READ_TIME) {
|
||||
LocalDateTime parsed = parseDate(value);
|
||||
if (parsed != null) {
|
||||
return parsed.atZone(ZoneId.systemDefault()).toInstant();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (field == RuleField.READ_STATUS) {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
if (value instanceof Number) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return value.toString().toLowerCase();
|
||||
}
|
||||
|
||||
private LocalDateTime parseDate(Object value) {
|
||||
if (value == null) return null;
|
||||
if (value instanceof LocalDateTime) return (LocalDateTime) value;
|
||||
|
||||
try {
|
||||
return LocalDateTime.parse(value.toString(), DateTimeFormatter.ISO_DATE_TIME);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
return LocalDate.parse(value.toString()).atStartOfDay();
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> toStringList(Object value) {
|
||||
if (value == null) return Collections.emptyList();
|
||||
if (value instanceof List) {
|
||||
return ((List<?>) value).stream()
|
||||
.map(Object::toString)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
return Collections.singletonList(value.toString());
|
||||
}
|
||||
|
||||
private String escapeLike(String value) {
|
||||
return value.replace("\\", "\\\\")
|
||||
.replace("%", "\\%")
|
||||
.replace("_", "\\_");
|
||||
}
|
||||
}
|
||||
+17
-10
@@ -15,19 +15,26 @@ import java.util.stream.Collectors;
|
||||
@Service
|
||||
public class MagicShelfService {
|
||||
|
||||
private final MagicShelfRepository repository;
|
||||
private final MagicShelfRepository magicShelfRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
public List<MagicShelf> getUserShelves() {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
return getShelvesForUser(userId);
|
||||
}
|
||||
|
||||
List<MagicShelf> shelves = repository.findAllByUserId(userId).stream()
|
||||
public List<MagicShelf> getUserShelvesForOpds(Long userId) {
|
||||
return getShelvesForUser(userId);
|
||||
}
|
||||
|
||||
private List<MagicShelf> getShelvesForUser(Long userId) {
|
||||
List<MagicShelf> shelves = magicShelfRepository.findAllByUserId(userId).stream()
|
||||
.map(this::toDto)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<Long> userShelfIds = shelves.stream().map(MagicShelf::getId).toList();
|
||||
|
||||
List<MagicShelf> publicShelves = repository.findAllByIsPublicIsTrue().stream()
|
||||
List<MagicShelf> publicShelves = magicShelfRepository.findAllByIsPublicIsTrue().stream()
|
||||
.map(this::toDto)
|
||||
.filter(shelf -> !userShelfIds.contains(shelf.getId()))
|
||||
.toList();
|
||||
@@ -40,7 +47,7 @@ public class MagicShelfService {
|
||||
public MagicShelf createOrUpdateShelf(MagicShelf dto) {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
if (dto.getId() != null) {
|
||||
MagicShelfEntity existing = repository.findById(dto.getId()).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
||||
MagicShelfEntity existing = magicShelfRepository.findById(dto.getId()).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
||||
if (!existing.getUserId().equals(userId)) {
|
||||
throw new SecurityException("You are not authorized to update this shelf");
|
||||
}
|
||||
@@ -51,22 +58,22 @@ public class MagicShelfService {
|
||||
existing.setIcon(dto.getIcon());
|
||||
existing.setFilterJson(dto.getFilterJson());
|
||||
existing.setPublic(dto.getIsPublic());
|
||||
return toDto(repository.save(existing));
|
||||
return toDto(magicShelfRepository.save(existing));
|
||||
}
|
||||
if (repository.existsByUserIdAndName(userId, dto.getName())) {
|
||||
if (magicShelfRepository.existsByUserIdAndName(userId, dto.getName())) {
|
||||
throw new IllegalArgumentException("A shelf with the same name already exists for this user.");
|
||||
}
|
||||
return toDto(repository.save(toEntity(dto, userId)));
|
||||
return toDto(magicShelfRepository.save(toEntity(dto, userId)));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteShelf(Long id) {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
||||
MagicShelfEntity shelf = magicShelfRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
||||
if (!shelf.getUserId().equals(userId)) {
|
||||
throw new SecurityException("You are not authorized to delete this shelf");
|
||||
}
|
||||
repository.deleteById(id);
|
||||
magicShelfRepository.deleteById(id);
|
||||
}
|
||||
|
||||
private MagicShelf toDto(MagicShelfEntity entity) {
|
||||
@@ -91,7 +98,7 @@ public class MagicShelfService {
|
||||
}
|
||||
|
||||
public MagicShelf getShelf(Long id) {
|
||||
MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
||||
MagicShelfEntity shelf = magicShelfRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
||||
return toDto(shelf);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +63,10 @@ public class VersionService {
|
||||
}
|
||||
|
||||
public List<ReleaseNote> fetchReleaseNotesSince(String currentVersion) {
|
||||
if ("development".equals(currentVersion)) {
|
||||
log.warn("Skipping fetch of release notes because current version is '{}', which is a local development build.", currentVersion);
|
||||
return new ArrayList<>();
|
||||
}
|
||||
log.info("Fetching release notes since version: {}", currentVersion);
|
||||
|
||||
List<ReleaseNote> updates = new ArrayList<>();
|
||||
|
||||
+2
-1
@@ -86,7 +86,8 @@ public class AppSettingService {
|
||||
builder.remoteAuthEnabled(appProperties.getRemoteAuth().isEnabled());
|
||||
|
||||
builder.defaultMetadataRefreshOptions(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.QUICK_BOOK_MATCH, MetadataRefreshOptions.class, settingPersistenceHelper.getDefaultMetadataRefreshOptions(), true));
|
||||
builder.libraryMetadataRefreshOptions(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.LIBRARY_METADATA_REFRESH_OPTIONS, new TypeReference<List<MetadataRefreshOptions>>() {}, List.of(), true));
|
||||
builder.libraryMetadataRefreshOptions(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.LIBRARY_METADATA_REFRESH_OPTIONS, new TypeReference<>() {
|
||||
}, List.of(), true));
|
||||
builder.oidcProviderDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_PROVIDER_DETAILS, OidcProviderDetails.class, null, false));
|
||||
builder.oidcAutoProvisionDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_AUTO_PROVISION_DETAILS, OidcAutoProvisionDetails.class, null, false));
|
||||
builder.metadataProviderSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_PROVIDER_SETTINGS, MetadataProviderSettings.class, settingPersistenceHelper.getDefaultMetadataProviderSettings(), true));
|
||||
|
||||
+4
-1
@@ -253,6 +253,9 @@ public class SettingPersistenceHelper {
|
||||
return KoboSettings.builder()
|
||||
.convertToKepub(false)
|
||||
.conversionLimitInMb(100)
|
||||
.convertCbxToEpub(false)
|
||||
.conversionLimitInMbForCbx(100)
|
||||
.forceEnableHyphenation(false)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+27
-2
@@ -4,9 +4,11 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Instant;
|
||||
@@ -23,8 +25,26 @@ public class BookCreatorService {
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
|
||||
public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) {
|
||||
Optional<BookEntity> existingBookOpt = bookRepository.findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName(
|
||||
libraryFile.getLibraryEntity().getId(),
|
||||
libraryFile.getLibraryPathEntity().getId(),
|
||||
libraryFile.getFileSubPath(),
|
||||
libraryFile.getFileName());
|
||||
|
||||
if (existingBookOpt.isPresent()) {
|
||||
log.warn("Book already exists for file: {}", libraryFile.getFileName());
|
||||
String newHash = FileFingerprint.generateHash(libraryFile.getFullPath());
|
||||
long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath());
|
||||
BookEntity existingBook = existingBookOpt.get();
|
||||
existingBook.setCurrentHash(newHash);
|
||||
existingBook.setInitialHash(newHash);
|
||||
existingBook.setDeleted(false);
|
||||
existingBook.setFileSizeKb(fileSizeKb);
|
||||
return existingBook;
|
||||
}
|
||||
|
||||
long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath());
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder().build();
|
||||
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.library(libraryFile.getLibraryEntity())
|
||||
.libraryPath(libraryFile.getLibraryPathEntity())
|
||||
@@ -33,8 +53,13 @@ public class BookCreatorService {
|
||||
.bookType(bookFileType)
|
||||
.fileSizeKb(fileSizeKb)
|
||||
.addedOn(Instant.now())
|
||||
.metadata(metadata)
|
||||
.build();
|
||||
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(bookEntity)
|
||||
.build();
|
||||
bookEntity.setMetadata(metadata);
|
||||
|
||||
return bookRepository.saveAndFlush(bookEntity);
|
||||
}
|
||||
|
||||
|
||||
+24
-8
@@ -7,6 +7,7 @@ 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.service.kobo.CbxConversionService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -23,6 +24,7 @@ import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
@@ -39,6 +41,7 @@ public class BookDownloadService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final KepubConversionService kepubConversionService;
|
||||
private final CbxConversionService cbxConversionService;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public ResponseEntity<Resource> downloadBook(Long bookId) {
|
||||
@@ -77,9 +80,12 @@ public class BookDownloadService {
|
||||
|
||||
public void downloadKoboBook(Long bookId, HttpServletResponse response) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
boolean isEpub = bookEntity.getBookType() == BookFileType.EPUB;
|
||||
boolean isCbx = bookEntity.getBookType() == BookFileType.CBX;
|
||||
|
||||
if (bookEntity.getBookType() != BookFileType.EPUB) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("The requested book is not an EPUB file.");
|
||||
if (!isEpub && !isCbx) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("The requested book is not an EPUB or CBX file.");
|
||||
}
|
||||
|
||||
KoboSettings koboSettings = appSettingService.getAppSettings().getKoboSettings();
|
||||
@@ -87,17 +93,25 @@ public class BookDownloadService {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Kobo settings not found.");
|
||||
}
|
||||
|
||||
|
||||
boolean asKepub = koboSettings.isConvertToKepub() && bookEntity.getFileSizeKb() <= (long) koboSettings.getConversionLimitInMb() * 1024;
|
||||
boolean convertEpubToKepub = isEpub && koboSettings.isConvertToKepub() && bookEntity.getFileSizeKb() <= (long) koboSettings.getConversionLimitInMb() * 1024;
|
||||
boolean convertCbxToEpub = isCbx && koboSettings.isConvertCbxToEpub() && bookEntity.getFileSizeKb() <= (long) koboSettings.getConversionLimitInMbForCbx() * 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());
|
||||
if (convertCbxToEpub || convertEpubToKepub) {
|
||||
tempDir = Files.createTempDirectory("kobo-conversion");
|
||||
}
|
||||
|
||||
if (convertCbxToEpub) {
|
||||
fileToSend = cbxConversionService.convertCbxToEpub(inputFile, tempDir.toFile(), bookEntity);
|
||||
}
|
||||
|
||||
if (convertEpubToKepub) {
|
||||
fileToSend = kepubConversionService.convertEpubToKepub(inputFile, tempDir.toFile(),
|
||||
koboSettings.isForceEnableHyphenation());
|
||||
}
|
||||
|
||||
setResponseHeaders(response, fileToSend);
|
||||
@@ -123,10 +137,12 @@ public class BookDownloadService {
|
||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
|
||||
}
|
||||
|
||||
private void streamFileToResponse(File file, HttpServletResponse response) throws IOException {
|
||||
private void streamFileToResponse(File file, HttpServletResponse response) {
|
||||
try (InputStream in = Files.newInputStream(file.toPath())) {
|
||||
in.transferTo(response.getOutputStream());
|
||||
response.getOutputStream().flush();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to stream file to response", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+16
-12
@@ -16,6 +16,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import com.adityachandel.booklore.model.enums.ResetProgressType;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
|
||||
import com.adityachandel.booklore.service.user.UserProgressService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
@@ -62,6 +63,7 @@ public class BookService {
|
||||
private final UserProgressService userProgressService;
|
||||
private final BookDownloadService bookDownloadService;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
private final KoboReadingStateService koboReadingStateService;
|
||||
|
||||
|
||||
private void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
@@ -70,7 +72,7 @@ public class BookService {
|
||||
.percentage(progress.getKoboProgressPercent())
|
||||
.build());
|
||||
}
|
||||
|
||||
|
||||
switch (book.getBookType()) {
|
||||
case EPUB -> {
|
||||
book.setEpubProgress(EpubProgress.builder()
|
||||
@@ -96,7 +98,7 @@ public class BookService {
|
||||
if (progress != null) {
|
||||
setBookProgress(book, progress);
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
book.setReadStatus(String.valueOf(progress.getReadStatus()));
|
||||
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
|
||||
book.setDateFinished(progress.getDateFinished());
|
||||
}
|
||||
}
|
||||
@@ -187,7 +189,7 @@ public class BookService {
|
||||
.build());
|
||||
}
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
book.setReadStatus(String.valueOf(userProgress.getReadStatus()));
|
||||
book.setReadStatus(userProgress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(userProgress.getReadStatus()));
|
||||
book.setDateFinished(userProgress.getDateFinished());
|
||||
|
||||
if (!withDescription) {
|
||||
@@ -407,8 +409,8 @@ public class BookService {
|
||||
progress.setUser(userEntity);
|
||||
progress.setBook(book);
|
||||
progress.setReadStatus(readStatus);
|
||||
progress.setReadStatusModifiedTime(Instant.now());
|
||||
|
||||
// Set dateFinished when status is READ, clear it otherwise
|
||||
if (readStatus == ReadStatus.READ) {
|
||||
progress.setDateFinished(Instant.now());
|
||||
} else {
|
||||
@@ -430,7 +432,7 @@ public class BookService {
|
||||
if (progress != null) {
|
||||
setBookProgress(book, progress);
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
book.setReadStatus(String.valueOf(progress.getReadStatus()));
|
||||
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
|
||||
book.setDateFinished(progress.getDateFinished());
|
||||
}
|
||||
|
||||
@@ -453,6 +455,11 @@ public class BookService {
|
||||
|
||||
progress.setBook(bookEntity);
|
||||
progress.setUser(userEntity.orElseThrow());
|
||||
|
||||
if (progress.getReadStatus() != null) {
|
||||
progress.setReadStatusModifiedTime(Instant.now());
|
||||
}
|
||||
|
||||
progress.setReadStatus(null);
|
||||
progress.setLastReadTime(null);
|
||||
progress.setDateFinished(null);
|
||||
@@ -474,7 +481,8 @@ public class BookService {
|
||||
progress.setKoboLocation(null);
|
||||
progress.setKoboLocationType(null);
|
||||
progress.setKoboLocationSource(null);
|
||||
progress.setKoboLastSyncTime(null);
|
||||
progress.setKoboProgressReceivedTime(null);
|
||||
koboReadingStateService.deleteReadingState(bookId);
|
||||
}
|
||||
userBookProgressRepository.save(progress);
|
||||
updatedBooks.add(bookMapper.toBook(bookEntity));
|
||||
@@ -501,11 +509,7 @@ public class BookService {
|
||||
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
|
||||
for (BookEntity bookEntity : bookEntities) {
|
||||
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
|
||||
for (ShelfEntity shelf : shelvesToAssign) {
|
||||
if (!bookEntity.getShelves().contains(shelf)) {
|
||||
bookEntity.getShelves().add(shelf);
|
||||
}
|
||||
}
|
||||
bookEntity.getShelves().addAll(shelvesToAssign);
|
||||
}
|
||||
bookRepository.saveAll(bookEntities);
|
||||
|
||||
@@ -605,7 +609,7 @@ public class BookService {
|
||||
: ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response);
|
||||
}
|
||||
|
||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
|
||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) {
|
||||
Path dir = currentDir;
|
||||
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
||||
dir = dir.toAbsolutePath().normalize();
|
||||
|
||||
+70
-24
@@ -34,7 +34,7 @@ import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.PathResource;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
@@ -97,7 +97,7 @@ public class BookDropService {
|
||||
String coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropId + ".jpg").toString();
|
||||
File coverFile = new File(coverPath);
|
||||
if (coverFile.exists() && coverFile.isFile()) {
|
||||
return new PathResource(coverFile.toPath());
|
||||
return new FileSystemResource(coverFile.toPath());
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
@@ -405,11 +405,29 @@ public class BookDropService {
|
||||
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.move(tempPath, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.deleteIfExists(source);
|
||||
|
||||
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
|
||||
|
||||
return processMovedFile(bookdropFile, target.toFile(), library, path, metadata);
|
||||
BookdropFileResult result;
|
||||
try {
|
||||
result = processMovedFile(bookdropFile, target.toFile(), library, path, metadata);
|
||||
} catch (Exception e) {
|
||||
cleanupTargetFile(target, bookdropFile.getId(), "processing exception");
|
||||
return failureResult(bookdropFile.getFileName(), "Processing failed: " + e.getMessage());
|
||||
}
|
||||
|
||||
if (result.isSuccess()) {
|
||||
try {
|
||||
Files.delete(source);
|
||||
log.info("Successfully deleted source file '{}' after successful import for file id={}", source, bookdropFile.getId());
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete source file '{}' after successful import for file id={}: {}", source, bookdropFile.getId(), e.getMessage());
|
||||
}
|
||||
} else {
|
||||
cleanupTargetFile(target, bookdropFile.getId(), "logical failure");
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to move file id={}, name={} from '{}' to '{}': {}", bookdropFile.getId(), bookdropFile.getFileName(), source, target, e.getMessage(), e);
|
||||
@@ -424,7 +442,7 @@ public class BookDropService {
|
||||
File targetFile,
|
||||
LibraryEntity library,
|
||||
LibraryPathEntity path,
|
||||
BookMetadata metadata) throws Exception {
|
||||
BookMetadata metadata) {
|
||||
FileProcessResult fileProcessResult = processFileInLibrary(targetFile.getName(), library, path, targetFile,
|
||||
BookFileExtension.fromFileName(bookdropFile.getFileName())
|
||||
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
|
||||
@@ -463,34 +481,52 @@ public class BookDropService {
|
||||
bookdropFileRepository.deleteById(bookdropFile.getId());
|
||||
bookdropNotificationService.sendBookdropFileSummaryNotification();
|
||||
|
||||
File cachedCover = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFile.getId() + ".jpg").toFile();
|
||||
if (cachedCover.exists()) {
|
||||
boolean deleted = cachedCover.delete();
|
||||
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
|
||||
Path cachedCoverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", bookdropFile.getId() + ".jpg");
|
||||
if (Files.exists(cachedCoverPath)) {
|
||||
try {
|
||||
Files.delete(cachedCoverPath);
|
||||
log.debug("Deleted cached cover image for bookdropId={}", bookdropFile.getId());
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete cached cover image for bookdropId={}: {}", bookdropFile.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupFailedMove(Path target) {
|
||||
try {
|
||||
if (Files.exists(target)) {
|
||||
Files.deleteIfExists(target);
|
||||
if (Files.deleteIfExists(target)) {
|
||||
log.info("Cleaned up partially created target file: {}", target);
|
||||
} else {
|
||||
log.debug("No partially created target file to cleanup: {}", target);
|
||||
}
|
||||
} catch (Exception cleanupException) {
|
||||
log.warn("Failed to cleanup target file after move error: {}", target, cleanupException);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to cleanup partially created target file: {}: {}", target, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupTempFile(Path tempPath) {
|
||||
if (tempPath != null) {
|
||||
try {
|
||||
Files.deleteIfExists(tempPath);
|
||||
Files.delete(tempPath);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to cleanup temp file: {}", tempPath, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupTargetFile(Path target, Long fileId, String reason) {
|
||||
try {
|
||||
if (Files.deleteIfExists(target)) {
|
||||
log.info("Cleaned up target file '{}' after {} for file id={}", target, reason, fileId);
|
||||
} else {
|
||||
log.debug("Target file '{}' not present, nothing to cleanup for file id={}", target, fileId);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to cleanup target file '{}' after {} for file id={}: {}",
|
||||
target, reason, fileId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private FileProcessResult processFileInLibrary(String fileName, LibraryEntity library, LibraryPathEntity path, File file, BookFileType type) {
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.libraryEntity(library)
|
||||
@@ -520,19 +556,25 @@ public class BookDropService {
|
||||
|
||||
private void deleteFilesAndCovers(List<BookdropFileEntity> filesToDelete, AtomicInteger deletedFiles, AtomicInteger deletedCovers) {
|
||||
for (BookdropFileEntity entity : filesToDelete) {
|
||||
try {
|
||||
Path filePath = Path.of(entity.getFilePath());
|
||||
if (Files.exists(filePath) && Files.isRegularFile(filePath) && Files.deleteIfExists(filePath)) {
|
||||
Path filePath = Path.of(entity.getFilePath());
|
||||
if (Files.exists(filePath) && Files.isRegularFile(filePath)) {
|
||||
try {
|
||||
Files.delete(filePath);
|
||||
deletedFiles.incrementAndGet();
|
||||
log.debug("Deleted file from disk: id={}, path={}", entity.getId(), filePath);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete file from disk for bookdropId={}: {}", entity.getId(), e.getMessage());
|
||||
}
|
||||
Path coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", entity.getId() + ".jpg");
|
||||
if (Files.exists(coverPath) && Files.deleteIfExists(coverPath)) {
|
||||
}
|
||||
Path coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", entity.getId() + ".jpg");
|
||||
if (Files.exists(coverPath)) {
|
||||
try {
|
||||
Files.delete(coverPath);
|
||||
deletedCovers.incrementAndGet();
|
||||
log.debug("Deleted cover image: id={}, path={}", entity.getId(), coverPath);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete cover image for bookdropId={}: {}", entity.getId(), e.getMessage());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete file or cover for bookdropId={}: {}", entity.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -544,9 +586,13 @@ public class BookDropService {
|
||||
.forEach(p -> {
|
||||
try (Stream<Path> subPaths = Files.list(p)) {
|
||||
if (subPaths.findAny().isEmpty()) {
|
||||
Files.deleteIfExists(p);
|
||||
deletedDirs.incrementAndGet();
|
||||
log.debug("Deleted empty directory: {}", p);
|
||||
try {
|
||||
Files.delete(p);
|
||||
deletedDirs.incrementAndGet();
|
||||
log.debug("Deleted empty directory: {}", p);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete empty directory: {}: {}", p, e.getMessage());
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete folder: {}", p, e);
|
||||
|
||||
+3
-1
@@ -44,6 +44,7 @@ public class BackgroundUploadService {
|
||||
|
||||
deleteExistingBackgroundFiles(userId);
|
||||
fileService.saveBackgroundImage(originalImage, filename, userId);
|
||||
originalImage.flush(); // Release resources after saving
|
||||
|
||||
String fileUrl = FileService.getBackgroundUrl(filename, userId);
|
||||
return new UploadResponse(fileUrl);
|
||||
@@ -60,10 +61,11 @@ public class BackgroundUploadService {
|
||||
String extension = getFileExtension(originalFilename);
|
||||
String filename = "1." + extension;
|
||||
|
||||
BufferedImage originalImage = FileService.downloadImageFromUrl(imageUrl);
|
||||
BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl);
|
||||
deleteExistingBackgroundFiles(userId);
|
||||
|
||||
fileService.saveBackgroundImage(originalImage, filename, userId);
|
||||
originalImage.flush(); // Release resources after saving
|
||||
|
||||
String fileUrl = FileService.getBackgroundUrl(filename, userId);
|
||||
return new UploadResponse(fileUrl);
|
||||
|
||||
+1
-1
@@ -106,7 +106,7 @@ public class FileMoveHelper {
|
||||
return Paths.get(path, newRelativePathStr);
|
||||
}
|
||||
|
||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) throws IOException {
|
||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) {
|
||||
Path dir = currentDir;
|
||||
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
||||
dir = dir.toAbsolutePath().normalize();
|
||||
|
||||
+10
-5
@@ -74,11 +74,16 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
try {
|
||||
Optional<BufferedImage> imageOptional = extractImagesFromArchive(file);
|
||||
if (imageOptional.isPresent()) {
|
||||
boolean saved = fileService.saveCoverImages(imageOptional.get(), bookEntity.getId());
|
||||
if (saved) {
|
||||
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
bookMetadataRepository.save(bookEntity.getMetadata());
|
||||
return true;
|
||||
BufferedImage image = imageOptional.get();
|
||||
try {
|
||||
boolean saved = fileService.saveCoverImages(image, bookEntity.getId());
|
||||
if (saved) {
|
||||
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
bookMetadataRepository.save(bookEntity.getMetadata());
|
||||
return true;
|
||||
}
|
||||
} finally {
|
||||
image.flush(); // Release resources after processing
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
+7
-1
@@ -151,6 +151,12 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
|
||||
|
||||
private boolean saveCoverImage(Resource coverImage, long bookId) throws IOException {
|
||||
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(coverImage.getData()));
|
||||
return fileService.saveCoverImages(originalImage, bookId);
|
||||
try {
|
||||
return fileService.saveCoverImages(originalImage, bookId);
|
||||
} finally {
|
||||
if (originalImage != null) {
|
||||
originalImage.flush(); // Release resources after processing
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
-2
@@ -66,6 +66,19 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
bookMetadataRepository.save(bookEntity.getMetadata());
|
||||
return saved;
|
||||
} catch (OutOfMemoryError e) {
|
||||
// Note: Catching OOM is generally discouraged, but for batch processing
|
||||
// of potentially large/corrupted PDFs, we prefer graceful degradation
|
||||
// over crashing the entire service.
|
||||
log.error("Out of memory (heap space exhausted) while generating cover for '{}'. Skipping cover generation.", bookEntity.getFileName());
|
||||
System.gc(); // Hint to JVM to reclaim memory
|
||||
return false;
|
||||
} catch (NegativeArraySizeException e) {
|
||||
// This can appear on corrupted PDF, or PDF with such large images that the
|
||||
// initial memory buffer is already bigger than the entire JVM heap, therefore
|
||||
// it leads to NegativeArrayException (basically run out of memory, and overflows)
|
||||
log.warn("Corrupted PDF structure for '{}'. Skipping cover generation.", bookEntity.getFileName());
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to generate cover for '{}': {}", bookEntity.getFileName(), e.getMessage());
|
||||
return false;
|
||||
@@ -139,7 +152,18 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
}
|
||||
|
||||
private boolean generateCoverImageAndSave(Long bookId, PDDocument document) throws IOException {
|
||||
BufferedImage coverImage = new PDFRenderer(document).renderImageWithDPI(0, 300, ImageType.RGB);
|
||||
return fileService.saveCoverImages(coverImage, bookId);
|
||||
BufferedImage coverImage = null;
|
||||
try {
|
||||
coverImage = new PDFRenderer(document).renderImageWithDPI(0, 150, ImageType.RGB);
|
||||
return fileService.saveCoverImages(coverImage, bookId);
|
||||
} catch (OutOfMemoryError e) {
|
||||
log.error("Out of memory (heap space exhausted) while generating cover for bookId {}. Skipping cover generation.", bookId);
|
||||
System.gc(); // Hint to JVM to reclaim memory
|
||||
return false;
|
||||
} finally {
|
||||
if (coverImage != null) {
|
||||
coverImage.flush(); // Release native resources
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+631
@@ -0,0 +1,631 @@
|
||||
package com.adityachandel.booklore.service.kobo;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||
import com.adityachandel.booklore.model.entity.TagEntity;
|
||||
import freemarker.cache.ClassTemplateLoader;
|
||||
import freemarker.template.Configuration;
|
||||
import freemarker.template.Template;
|
||||
import freemarker.template.TemplateException;
|
||||
import freemarker.template.TemplateExceptionHandler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
import com.github.junrar.exception.RarException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.FileSystemUtils;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageWriteParam;
|
||||
import javax.imageio.ImageWriter;
|
||||
import javax.imageio.IIOImage;
|
||||
import javax.imageio.stream.ImageOutputStream;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Service for converting comic book archive files (CBX) to EPUB format.
|
||||
* <p>
|
||||
* This service supports the following comic book archive formats:
|
||||
* <ul>
|
||||
* <li><b>CBZ</b> - Comic book ZIP archive</li>
|
||||
* <li><b>CBR</b> - Comic book RAR archive</li>
|
||||
* <li><b>CB7</b> - Comic book 7z archive</li>
|
||||
* </ul>
|
||||
* </p>
|
||||
* <p>
|
||||
* Supported image formats within archives: JPG, JPEG, PNG, WEBP, GIF, BMP
|
||||
* </p>
|
||||
*
|
||||
* <h3>Size Limits</h3>
|
||||
* <ul>
|
||||
* <li>Maximum individual image size: 50 MB</li>
|
||||
* </ul>
|
||||
*
|
||||
* @see KepubConversionService
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CbxConversionService {
|
||||
|
||||
private static final String IMAGE_ROOT_PATH = "OEBPS/Images/";
|
||||
private static final String HTML_ROOT_PATH = "OEBPS/Text/";
|
||||
private static final String CONTENT_OPF_PATH = "OEBPS/content.opf";
|
||||
private static final String NAV_XHTML_PATH = "OEBPS/nav.xhtml";
|
||||
private static final String TOC_NCX_PATH = "OEBPS/toc.ncx";
|
||||
private static final String STYLESHEET_CSS_PATH = "OEBPS/Styles/stylesheet.css";
|
||||
private static final String COVER_IMAGE_PATH = "OEBPS/Images/cover.jpg";
|
||||
private static final String MIMETYPE_CONTENT = "application/epub+zip";
|
||||
private static final long MAX_IMAGE_SIZE_BYTES = 50L * 1024 * 1024;
|
||||
private static final String EXTRACTED_IMAGES_SUBDIR = "cbx_extracted_images";
|
||||
|
||||
private final Configuration freemarkerConfig;
|
||||
|
||||
public CbxConversionService() {
|
||||
this.freemarkerConfig = initializeFreemarkerConfiguration();
|
||||
}
|
||||
|
||||
public record EpubContentFileGroup(String contentKey, String imagePath, String htmlPath) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a comic book archive (CBZ, CBR, or CB7) to EPUB format.
|
||||
* <p>
|
||||
* The conversion process:
|
||||
* <ol>
|
||||
* <li>Extracts all images from the archive to a temporary directory</li>
|
||||
* <li>Creates an EPUB structure with one XHTML page per image</li>
|
||||
* <li>Includes proper EPUB metadata from the book entity</li>
|
||||
* <li>JPEG images are passed through directly; other formats are converted to JPEG (85% quality)</li>
|
||||
* </ol>
|
||||
* </p>
|
||||
*
|
||||
* @param cbxFile the comic book archive file (must be CBZ, CBR, or CB7)
|
||||
* @param tempDir the temporary directory where the output EPUB will be created
|
||||
* @param bookEntity the book metadata to include in the EPUB
|
||||
* @return the converted EPUB file
|
||||
* @throws IOException if file I/O operations fail
|
||||
* @throws TemplateException if EPUB template processing fails
|
||||
* @throws RarException if RAR extraction fails (for CBR files)
|
||||
* @throws IllegalArgumentException if the file format is not supported
|
||||
* @throws IllegalStateException if no valid images are found in the archive
|
||||
*/
|
||||
public File convertCbxToEpub(File cbxFile, File tempDir, BookEntity bookEntity)
|
||||
throws IOException, TemplateException, RarException {
|
||||
validateInputs(cbxFile, tempDir);
|
||||
|
||||
log.info("Starting CBX to EPUB conversion for: {}", cbxFile.getName());
|
||||
|
||||
File outputFile = executeCbxConversion(cbxFile, tempDir, bookEntity);
|
||||
|
||||
log.info("Successfully converted {} to {} (size: {} bytes)",
|
||||
cbxFile.getName(), outputFile.getName(), outputFile.length());
|
||||
return outputFile;
|
||||
}
|
||||
|
||||
private File executeCbxConversion(File cbxFile, File tempDir, BookEntity bookEntity)
|
||||
throws IOException, TemplateException, RarException {
|
||||
|
||||
Path epubFilePath = Paths.get(tempDir.getAbsolutePath(), cbxFile.getName() + ".epub");
|
||||
File epubFile = epubFilePath.toFile();
|
||||
|
||||
Path extractedImagesDir = Paths.get(tempDir.getAbsolutePath(), EXTRACTED_IMAGES_SUBDIR);
|
||||
Files.createDirectories(extractedImagesDir);
|
||||
|
||||
List<Path> imagePaths = extractImagesFromCbx(cbxFile, extractedImagesDir);
|
||||
if (imagePaths.isEmpty()) {
|
||||
throw new IllegalStateException("No valid images found in CBX file: " + cbxFile.getName());
|
||||
}
|
||||
|
||||
log.debug("Extracted {} images from CBX file to disk", imagePaths.size());
|
||||
|
||||
try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(epubFile))) {
|
||||
addMimetypeEntry(zipOut);
|
||||
addMetaInfContainer(zipOut);
|
||||
addStylesheet(zipOut);
|
||||
|
||||
List<EpubContentFileGroup> contentGroups = addImagesAndPages(zipOut, imagePaths);
|
||||
|
||||
addContentOpf(zipOut, bookEntity, contentGroups);
|
||||
addTocNcx(zipOut, bookEntity, contentGroups);
|
||||
addNavXhtml(zipOut, bookEntity, contentGroups);
|
||||
}
|
||||
|
||||
deleteDirectory(extractedImagesDir);
|
||||
|
||||
return epubFile;
|
||||
}
|
||||
|
||||
private void deleteDirectory(Path directory) {
|
||||
try {
|
||||
FileSystemUtils.deleteRecursively(directory);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete directory {}: {}", directory, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void validateInputs(File cbxFile, File tempDir) {
|
||||
if (cbxFile == null || !cbxFile.isFile()) {
|
||||
throw new IllegalArgumentException("Invalid CBX file: " + cbxFile);
|
||||
}
|
||||
|
||||
if (!isSupportedCbxFormat(cbxFile.getName())) {
|
||||
throw new IllegalArgumentException("Unsupported file format: " + cbxFile.getName() +
|
||||
". Supported formats: CBZ, CBR, CB7");
|
||||
}
|
||||
|
||||
if (tempDir == null || !tempDir.isDirectory()) {
|
||||
throw new IllegalArgumentException("Invalid temp directory: " + tempDir);
|
||||
}
|
||||
}
|
||||
|
||||
private Configuration initializeFreemarkerConfiguration() {
|
||||
Configuration config = new Configuration(Configuration.VERSION_2_3_33);
|
||||
config.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/templates/epub"));
|
||||
config.setDefaultEncoding(StandardCharsets.UTF_8.name());
|
||||
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
|
||||
config.setLogTemplateExceptions(false);
|
||||
config.setWrapUncheckedExceptions(true);
|
||||
return config;
|
||||
}
|
||||
|
||||
private List<Path> extractImagesFromCbx(File cbxFile, Path extractedImagesDir) throws IOException, RarException {
|
||||
String fileName = cbxFile.getName().toLowerCase();
|
||||
|
||||
if (fileName.endsWith(".cbz")) {
|
||||
return extractImagesFromZip(cbxFile, extractedImagesDir);
|
||||
} else if (fileName.endsWith(".cbr")) {
|
||||
return extractImagesFromRar(cbxFile, extractedImagesDir);
|
||||
} else if (fileName.endsWith(".cb7")) {
|
||||
return extractImagesFrom7z(cbxFile, extractedImagesDir);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unsupported archive format: " + fileName);
|
||||
}
|
||||
}
|
||||
|
||||
private List<Path> extractImagesFromZip(File cbzFile, Path extractedImagesDir) throws IOException {
|
||||
List<Path> imagePaths = new ArrayList<>();
|
||||
|
||||
try (ZipFile zipFile = ZipFile.builder().setFile(cbzFile).get()) {
|
||||
for (ZipArchiveEntry entry : Collections.list(zipFile.getEntries())) {
|
||||
if (entry.isDirectory() || !isImageFile(entry.getName())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
validateImageSize(entry.getName(), entry.getSize());
|
||||
|
||||
try (InputStream inputStream = zipFile.getInputStream(entry)) {
|
||||
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName()));
|
||||
Files.copy(inputStream, outputPath);
|
||||
imagePaths.add(outputPath);
|
||||
} catch (Exception e) {
|
||||
log.warn("Error extracting image {}: {}", entry.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("Found {} image entries in CBZ file", imagePaths.size());
|
||||
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
||||
return imagePaths;
|
||||
}
|
||||
|
||||
private List<Path> extractImagesFromRar(File cbrFile, Path extractedImagesDir) throws IOException, RarException {
|
||||
List<Path> imagePaths = new ArrayList<>();
|
||||
|
||||
try (Archive rarFile = new Archive(cbrFile)) {
|
||||
for (FileHeader fileHeader : rarFile) {
|
||||
if (fileHeader.isDirectory() || !isImageFile(fileHeader.getFileName())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
validateImageSize(fileHeader.getFileName(), fileHeader.getFullUnpackSize());
|
||||
|
||||
try (InputStream inputStream = rarFile.getInputStream(fileHeader)) {
|
||||
Path outputPath = extractedImagesDir.resolve(extractFileName(fileHeader.getFileName()));
|
||||
Files.copy(inputStream, outputPath);
|
||||
imagePaths.add(outputPath);
|
||||
} catch (Exception e) {
|
||||
log.warn("Error extracting image {}: {}", fileHeader.getFileName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("Found {} image entries in CBR file", imagePaths.size());
|
||||
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
||||
return imagePaths;
|
||||
}
|
||||
|
||||
private List<Path> extractImagesFrom7z(File cb7File, Path extractedImagesDir) throws IOException {
|
||||
List<Path> imagePaths = new ArrayList<>();
|
||||
|
||||
try (SevenZFile sevenZFile = SevenZFile.builder().setFile(cb7File).get()) {
|
||||
SevenZArchiveEntry entry;
|
||||
while ((entry = sevenZFile.getNextEntry()) != null) {
|
||||
if (entry.isDirectory() || !isImageFile(entry.getName())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
validateImageSize(entry.getName(), entry.getSize());
|
||||
|
||||
try {
|
||||
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName()));
|
||||
try (InputStream entryInputStream = sevenZFile.getInputStream(entry);
|
||||
OutputStream fileOutputStream = Files.newOutputStream(outputPath)) {
|
||||
entryInputStream.transferTo(fileOutputStream);
|
||||
}
|
||||
imagePaths.add(outputPath);
|
||||
} catch (Exception e) {
|
||||
log.warn("Error extracting image {}: {}", entry.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("Found {} image entries in CB7 file", imagePaths.size());
|
||||
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
||||
return imagePaths;
|
||||
}
|
||||
|
||||
private String extractFileName(String entryPath) {
|
||||
return Path.of(entryPath).getFileName().toString();
|
||||
}
|
||||
|
||||
private void validateImageSize(String imageName, long size) throws IOException {
|
||||
if (size > MAX_IMAGE_SIZE_BYTES) {
|
||||
throw new IOException(String.format("Image '%s' exceeds maximum size limit: %d bytes (max: %d bytes)",
|
||||
imageName, size, MAX_IMAGE_SIZE_BYTES));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isImageFile(String fileName) {
|
||||
String lowerName = fileName.toLowerCase();
|
||||
|
||||
boolean isImage = lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") ||
|
||||
lowerName.endsWith(".png") || lowerName.endsWith(".webp") ||
|
||||
lowerName.endsWith(".gif") || lowerName.endsWith(".bmp");
|
||||
|
||||
return isImage;
|
||||
}
|
||||
|
||||
private boolean isJpegFile(Path path) {
|
||||
Set<String> jpegExtensions = Set.of(".jpg", ".jpeg");
|
||||
String fileName = path.getFileName().toString().toLowerCase();
|
||||
int lastDot = fileName.lastIndexOf('.');
|
||||
if (lastDot > 0) {
|
||||
String extension = fileName.substring(lastDot);
|
||||
return jpegExtensions.contains(extension);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void addMimetypeEntry(ZipArchiveOutputStream zipOut) throws IOException {
|
||||
byte[] mimetypeBytes = MIMETYPE_CONTENT.getBytes(StandardCharsets.UTF_8);
|
||||
ZipArchiveEntry mimetypeEntry = new ZipArchiveEntry("mimetype");
|
||||
mimetypeEntry.setMethod(ZipArchiveEntry.STORED);
|
||||
mimetypeEntry.setSize(mimetypeBytes.length);
|
||||
mimetypeEntry.setCrc(calculateCrc32(mimetypeBytes));
|
||||
|
||||
zipOut.putArchiveEntry(mimetypeEntry);
|
||||
zipOut.write(mimetypeBytes);
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private void addMetaInfContainer(ZipArchiveOutputStream zipOut) throws IOException, TemplateException {
|
||||
Map<String, Object> model = new HashMap<>();
|
||||
model.put("contentOpfPath", CONTENT_OPF_PATH);
|
||||
|
||||
String containerXml = processTemplate("xml/container.xml.ftl", model);
|
||||
|
||||
ZipArchiveEntry containerEntry = new ZipArchiveEntry("META-INF/container.xml");
|
||||
zipOut.putArchiveEntry(containerEntry);
|
||||
zipOut.write(containerXml.getBytes(StandardCharsets.UTF_8));
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private void addStylesheet(ZipArchiveOutputStream zipOut) throws IOException {
|
||||
String stylesheetContent = loadResourceAsString("/templates/epub/css/stylesheet.css");
|
||||
|
||||
ZipArchiveEntry stylesheetEntry = new ZipArchiveEntry(STYLESHEET_CSS_PATH);
|
||||
zipOut.putArchiveEntry(stylesheetEntry);
|
||||
zipOut.write(stylesheetContent.getBytes(StandardCharsets.UTF_8));
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private List<EpubContentFileGroup> addImagesAndPages(ZipArchiveOutputStream zipOut, List<Path> imagePaths)
|
||||
throws IOException, TemplateException {
|
||||
|
||||
List<EpubContentFileGroup> contentGroups = new ArrayList<>();
|
||||
|
||||
if (!imagePaths.isEmpty()) {
|
||||
addImageToZipFromPath(zipOut, COVER_IMAGE_PATH, imagePaths.get(0));
|
||||
}
|
||||
|
||||
for (int i = 0; i < imagePaths.size(); i++) {
|
||||
Path imageSourcePath = imagePaths.get(i);
|
||||
String contentKey = String.format("page-%04d", i + 1);
|
||||
String imageFileName = contentKey + ".jpg";
|
||||
String htmlFileName = contentKey + ".xhtml";
|
||||
|
||||
String imagePath = IMAGE_ROOT_PATH + imageFileName;
|
||||
String htmlPath = HTML_ROOT_PATH + htmlFileName;
|
||||
|
||||
addImageToZipFromPath(zipOut, imagePath, imageSourcePath);
|
||||
|
||||
String htmlContent = generatePageHtml(imageFileName, i + 1);
|
||||
ZipArchiveEntry htmlEntry = new ZipArchiveEntry(htmlPath);
|
||||
zipOut.putArchiveEntry(htmlEntry);
|
||||
zipOut.write(htmlContent.getBytes(StandardCharsets.UTF_8));
|
||||
zipOut.closeArchiveEntry();
|
||||
|
||||
contentGroups.add(new EpubContentFileGroup(contentKey, imagePath, htmlPath));
|
||||
}
|
||||
|
||||
return contentGroups;
|
||||
}
|
||||
|
||||
private void addImageToZipFromPath(ZipArchiveOutputStream zipOut, String epubImagePath, Path sourceImagePath)
|
||||
throws IOException {
|
||||
ZipArchiveEntry imageEntry = new ZipArchiveEntry(epubImagePath);
|
||||
zipOut.putArchiveEntry(imageEntry);
|
||||
|
||||
if (isJpegFile(sourceImagePath)) {
|
||||
try (InputStream fis = Files.newInputStream(sourceImagePath)) {
|
||||
fis.transferTo(zipOut);
|
||||
}
|
||||
} else {
|
||||
try (InputStream fis = Files.newInputStream(sourceImagePath)) {
|
||||
BufferedImage image = ImageIO.read(fis);
|
||||
if (image != null) {
|
||||
writeJpegImage(image, zipOut, 0.85f);
|
||||
} else {
|
||||
log.warn("Could not decode image {}, copying raw bytes", sourceImagePath.getFileName());
|
||||
try (InputStream rawStream = Files.newInputStream(sourceImagePath)) {
|
||||
rawStream.transferTo(zipOut);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private void writeJpegImage(BufferedImage image, ZipArchiveOutputStream zipOut, float quality)
|
||||
throws IOException {
|
||||
BufferedImage rgbImage = image;
|
||||
if (image.getType() != BufferedImage.TYPE_INT_RGB) {
|
||||
rgbImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
|
||||
rgbImage.getGraphics().drawImage(image, 0, 0, null);
|
||||
rgbImage.getGraphics().dispose();
|
||||
}
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
|
||||
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
|
||||
if (!writers.hasNext()) {
|
||||
throw new IOException("No JPEG image writer available");
|
||||
}
|
||||
ImageWriter writer = writers.next();
|
||||
|
||||
ImageWriteParam param = writer.getDefaultWriteParam();
|
||||
|
||||
if (param.canWriteCompressed()) {
|
||||
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
||||
param.setCompressionQuality(quality);
|
||||
}
|
||||
|
||||
try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) {
|
||||
writer.setOutput(ios);
|
||||
writer.write(null, new IIOImage(rgbImage, null, null), param);
|
||||
} finally {
|
||||
writer.dispose();
|
||||
}
|
||||
|
||||
zipOut.write(baos.toByteArray());
|
||||
}
|
||||
|
||||
private String generatePageHtml(String imageFileName, int pageNumber) throws IOException, TemplateException {
|
||||
Map<String, Object> model = new HashMap<>();
|
||||
model.put("imageFileName", "../Images/" + imageFileName);
|
||||
model.put("pageNumber", pageNumber);
|
||||
model.put("stylesheetPath", "../Styles/stylesheet.css");
|
||||
|
||||
return processTemplate("xml/image_page.xhtml.ftl", model);
|
||||
}
|
||||
|
||||
private void addContentOpf(ZipArchiveOutputStream zipOut, BookEntity bookEntity,
|
||||
List<EpubContentFileGroup> contentGroups) throws IOException, TemplateException {
|
||||
|
||||
Map<String, Object> model = createBookMetadataModel(bookEntity);
|
||||
|
||||
List<EpubContentFileGroup> relativeContentGroups = contentGroups.stream()
|
||||
.map(group -> new EpubContentFileGroup(
|
||||
group.contentKey(),
|
||||
makeRelativeToOebps(group.imagePath()),
|
||||
makeRelativeToOebps(group.htmlPath())
|
||||
))
|
||||
.toList();
|
||||
|
||||
model.put("contentFileGroups", relativeContentGroups);
|
||||
model.put("coverImagePath", makeRelativeToOebps(COVER_IMAGE_PATH));
|
||||
model.put("tocNcxPath", makeRelativeToOebps(TOC_NCX_PATH));
|
||||
model.put("navXhtmlPath", makeRelativeToOebps(NAV_XHTML_PATH));
|
||||
model.put("stylesheetCssPath", makeRelativeToOebps(STYLESHEET_CSS_PATH));
|
||||
model.put("firstPageId", contentGroups.isEmpty() ? "" : "page_" + contentGroups.get(0).contentKey());
|
||||
|
||||
String contentOpf = processTemplate("xml/content.opf.ftl", model);
|
||||
|
||||
ZipArchiveEntry contentEntry = new ZipArchiveEntry(CONTENT_OPF_PATH);
|
||||
zipOut.putArchiveEntry(contentEntry);
|
||||
zipOut.write(contentOpf.getBytes(StandardCharsets.UTF_8));
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private void addTocNcx(ZipArchiveOutputStream zipOut, BookEntity bookEntity,
|
||||
List<EpubContentFileGroup> contentGroups) throws IOException, TemplateException {
|
||||
|
||||
Map<String, Object> model = createBookMetadataModel(bookEntity);
|
||||
model.put("contentFileGroups", contentGroups);
|
||||
|
||||
String tocNcx = processTemplate("xml/toc.xml.ftl", model);
|
||||
|
||||
ZipArchiveEntry tocEntry = new ZipArchiveEntry(TOC_NCX_PATH);
|
||||
zipOut.putArchiveEntry(tocEntry);
|
||||
zipOut.write(tocNcx.getBytes(StandardCharsets.UTF_8));
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private void addNavXhtml(ZipArchiveOutputStream zipOut, BookEntity bookEntity,
|
||||
List<EpubContentFileGroup> contentGroups) throws IOException, TemplateException {
|
||||
|
||||
Map<String, Object> model = createBookMetadataModel(bookEntity);
|
||||
model.put("contentFileGroups", contentGroups);
|
||||
|
||||
String navXhtml = processTemplate("xml/nav.xhtml.ftl", model);
|
||||
|
||||
ZipArchiveEntry navEntry = new ZipArchiveEntry(NAV_XHTML_PATH);
|
||||
zipOut.putArchiveEntry(navEntry);
|
||||
zipOut.write(navXhtml.getBytes(StandardCharsets.UTF_8));
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
|
||||
private Map<String, Object> createBookMetadataModel(BookEntity bookEntity) {
|
||||
Map<String, Object> model = new HashMap<>();
|
||||
|
||||
if (bookEntity != null && bookEntity.getMetadata() != null) {
|
||||
var metadata = bookEntity.getMetadata();
|
||||
|
||||
model.put("title", metadata.getTitle() != null ? metadata.getTitle() : "Unknown Comic");
|
||||
model.put("language", metadata.getLanguage() != null ? metadata.getLanguage() : "en");
|
||||
|
||||
if (metadata.getSubtitle() != null && !metadata.getSubtitle().trim().isEmpty()) {
|
||||
model.put("subtitle", metadata.getSubtitle());
|
||||
}
|
||||
if (metadata.getDescription() != null && !metadata.getDescription().trim().isEmpty()) {
|
||||
model.put("description", metadata.getDescription());
|
||||
}
|
||||
|
||||
if (metadata.getSeriesName() != null && !metadata.getSeriesName().trim().isEmpty()) {
|
||||
model.put("seriesName", metadata.getSeriesName());
|
||||
}
|
||||
if (metadata.getSeriesNumber() != null) {
|
||||
model.put("seriesNumber", metadata.getSeriesNumber());
|
||||
}
|
||||
if (metadata.getSeriesTotal() != null) {
|
||||
model.put("seriesTotal", metadata.getSeriesTotal());
|
||||
}
|
||||
|
||||
if (metadata.getPublisher() != null && !metadata.getPublisher().trim().isEmpty()) {
|
||||
model.put("publisher", metadata.getPublisher());
|
||||
}
|
||||
if (metadata.getPublishedDate() != null) {
|
||||
model.put("publishedDate", metadata.getPublishedDate().toString());
|
||||
}
|
||||
if (metadata.getPageCount() != null && metadata.getPageCount() > 0) {
|
||||
model.put("pageCount", metadata.getPageCount());
|
||||
}
|
||||
|
||||
if (metadata.getIsbn13() != null && !metadata.getIsbn13().trim().isEmpty()) {
|
||||
model.put("isbn13", metadata.getIsbn13());
|
||||
}
|
||||
if (metadata.getIsbn10() != null && !metadata.getIsbn10().trim().isEmpty()) {
|
||||
model.put("isbn10", metadata.getIsbn10());
|
||||
}
|
||||
if (metadata.getAsin() != null && !metadata.getAsin().trim().isEmpty()) {
|
||||
model.put("asin", metadata.getAsin());
|
||||
}
|
||||
if (metadata.getGoodreadsId() != null && !metadata.getGoodreadsId().trim().isEmpty()) {
|
||||
model.put("goodreadsId", metadata.getGoodreadsId());
|
||||
}
|
||||
|
||||
if (metadata.getAuthors() != null && !metadata.getAuthors().isEmpty()) {
|
||||
model.put("authors", metadata.getAuthors().stream()
|
||||
.map(AuthorEntity::getName)
|
||||
.toList());
|
||||
}
|
||||
|
||||
if (metadata.getCategories() != null && !metadata.getCategories().isEmpty()) {
|
||||
model.put("categories", metadata.getCategories().stream()
|
||||
.map(CategoryEntity::getName)
|
||||
.toList());
|
||||
}
|
||||
|
||||
if (metadata.getTags() != null && !metadata.getTags().isEmpty()) {
|
||||
model.put("tags", metadata.getTags().stream()
|
||||
.map(TagEntity::getName)
|
||||
.toList());
|
||||
}
|
||||
|
||||
model.put("identifier", "urn:uuid:" + UUID.randomUUID());
|
||||
} else {
|
||||
model.put("title", "Unknown Comic");
|
||||
model.put("language", "en");
|
||||
model.put("identifier", "urn:uuid:" + UUID.randomUUID());
|
||||
}
|
||||
|
||||
model.put("modified", Instant.now().toString());
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
private String processTemplate(String templateName, Map<String, Object> model)
|
||||
throws IOException, TemplateException {
|
||||
try {
|
||||
Template template = freemarkerConfig.getTemplate(templateName);
|
||||
StringWriter writer = new StringWriter();
|
||||
template.process(model, writer);
|
||||
return writer.toString();
|
||||
} catch (IOException e) {
|
||||
throw new IOException("Failed to load template: " + templateName, e);
|
||||
} catch (TemplateException e) {
|
||||
throw new TemplateException("Failed to process template: " + templateName, e, null);
|
||||
}
|
||||
}
|
||||
|
||||
private String loadResourceAsString(String resourcePath) throws IOException {
|
||||
try (InputStream inputStream = getClass().getResourceAsStream(resourcePath)) {
|
||||
if (inputStream == null) {
|
||||
throw new IOException("Resource not found: " + resourcePath);
|
||||
}
|
||||
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
private String makeRelativeToOebps(String fullPath) {
|
||||
Path oebpsPath = Paths.get("OEBPS");
|
||||
Path targetPath = Paths.get(fullPath);
|
||||
|
||||
if (targetPath.startsWith(oebpsPath)) {
|
||||
return oebpsPath.relativize(targetPath).toString().replace('\\', '/');
|
||||
}
|
||||
|
||||
return fullPath;
|
||||
}
|
||||
|
||||
private long calculateCrc32(byte[] data) {
|
||||
java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
|
||||
crc32.update(data);
|
||||
return crc32.getValue();
|
||||
}
|
||||
|
||||
public boolean isSupportedCbxFormat(String fileName) {
|
||||
if (fileName == null) {
|
||||
return false;
|
||||
}
|
||||
String lowerName = fileName.toLowerCase();
|
||||
return lowerName.endsWith(".cbz") ||
|
||||
lowerName.endsWith(".cbr") ||
|
||||
lowerName.endsWith(".cb7");
|
||||
}
|
||||
|
||||
}
|
||||
+9
-4
@@ -28,11 +28,11 @@ public class KepubConversionService {
|
||||
private static final String BIN_LINUX_ARM = "kepubify-linux-arm";
|
||||
private static final String BIN_LINUX_ARM64 = "kepubify-linux-arm64";
|
||||
|
||||
public File convertEpubToKepub(File epubFile, File tempDir) throws IOException, InterruptedException {
|
||||
public File convertEpubToKepub(File epubFile, File tempDir, boolean forceEnableHyphenation) throws IOException, InterruptedException {
|
||||
validateInputs(epubFile);
|
||||
|
||||
Path kepubifyBinary = setupKepubifyBinary();
|
||||
File outputFile = executeKepubifyConversion(epubFile, tempDir, kepubifyBinary);
|
||||
File outputFile = executeKepubifyConversion(epubFile, tempDir, kepubifyBinary, forceEnableHyphenation);
|
||||
|
||||
log.info("Successfully converted {} to {} (size: {} bytes)", epubFile.getName(), outputFile.getName(), outputFile.length());
|
||||
return outputFile;
|
||||
@@ -98,9 +98,14 @@ public class KepubConversionService {
|
||||
throw new IllegalStateException("Unsupported operating system or architecture: " + osName + " / " + osArch);
|
||||
}
|
||||
|
||||
private File executeKepubifyConversion(File epubFile, File tempDir, Path kepubifyBinary) throws IOException, InterruptedException {
|
||||
private File executeKepubifyConversion(File epubFile, File tempDir, Path kepubifyBinary, boolean forceEnableHyphenation) throws IOException, InterruptedException {
|
||||
ProcessBuilder pb;
|
||||
|
||||
if (forceEnableHyphenation)
|
||||
pb = new ProcessBuilder(kepubifyBinary.toAbsolutePath().toString(), "--hyphenate", "-o", tempDir.getAbsolutePath(), epubFile.getAbsolutePath());
|
||||
else
|
||||
pb = new ProcessBuilder(kepubifyBinary.toAbsolutePath().toString(), "-o", tempDir.getAbsolutePath(), epubFile.getAbsolutePath());
|
||||
|
||||
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());
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.adityachandel.booklore.service.kobo;
|
||||
|
||||
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.service.appsettings.AppSettingService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class KoboCompatibilityService {
|
||||
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public boolean isBookSupportedForKobo(BookEntity book) {
|
||||
if (book == null) {
|
||||
throw new IllegalArgumentException("Book cannot be null");
|
||||
}
|
||||
|
||||
BookFileType bookType = book.getBookType();
|
||||
if (bookType == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (bookType == BookFileType.EPUB) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (bookType == BookFileType.CBX) {
|
||||
return isCbxConversionEnabled() && meetsCbxConversionSizeLimit(book);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isCbxConversionEnabled() {
|
||||
try {
|
||||
KoboSettings koboSettings = appSettingService.getAppSettings().getKoboSettings();
|
||||
return koboSettings != null && koboSettings.isConvertCbxToEpub();
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean meetsCbxConversionSizeLimit(BookEntity book) {
|
||||
if (book == null || book.getBookType() != BookFileType.CBX) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
KoboSettings koboSettings = appSettingService.getAppSettings().getKoboSettings();
|
||||
if (koboSettings == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
long fileSizeKb = book.getFileSizeKb() != null ? book.getFileSizeKb() : 0;
|
||||
long limitKb = (long) koboSettings.getConversionLimitInMbForCbx() * 1024;
|
||||
|
||||
return fileSizeKb <= limitKb;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+73
-33
@@ -2,14 +2,9 @@ package com.adityachandel.booklore.service.kobo;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.mapper.KoboReadingStateMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
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.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.KoboBookFormat;
|
||||
import com.adityachandel.booklore.model.enums.KoboReadStatus;
|
||||
@@ -19,6 +14,7 @@ import com.adityachandel.booklore.service.book.BookQueryService;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.util.kobo.KoboUrlBuilder;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
@@ -32,12 +28,14 @@ import java.util.stream.Collectors;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
@Slf4j
|
||||
public class KoboEntitlementService {
|
||||
|
||||
private static final Pattern NON_ALPHANUMERIC_LOWERCASE_PATTERN = Pattern.compile("[^a-z0-9]");
|
||||
private final KoboUrlBuilder koboUrlBuilder;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final AppSettingService appSettingService;
|
||||
private final KoboCompatibilityService koboCompatibilityService;
|
||||
private final UserBookProgressRepository progressRepository;
|
||||
private final KoboReadingStateRepository readingStateRepository;
|
||||
private final KoboReadingStateMapper readingStateMapper;
|
||||
@@ -48,7 +46,7 @@ public class KoboEntitlementService {
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
|
||||
return books.stream()
|
||||
.filter(bookEntity -> bookEntity.getBookType() == BookFileType.EPUB)
|
||||
.filter(koboCompatibilityService::isBookSupportedForKobo)
|
||||
.map(book -> NewEntitlement.builder()
|
||||
.newEntitlement(BookEntitlementContainer.builder()
|
||||
.bookEntitlement(buildBookEntitlement(book, removed))
|
||||
@@ -62,7 +60,7 @@ public class KoboEntitlementService {
|
||||
public List<ChangedEntitlement> generateChangedEntitlements(Set<Long> bookIds, String token, boolean removed) {
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
return books.stream()
|
||||
.filter(bookEntity -> bookEntity.getBookType() == BookFileType.EPUB)
|
||||
.filter(koboCompatibilityService::isBookSupportedForKobo)
|
||||
.map(book -> {
|
||||
KoboBookMetadata metadata;
|
||||
if (removed) {
|
||||
@@ -87,39 +85,72 @@ public class KoboEntitlementService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<ChangedReadingState> generateChangedReadingStates(List<UserBookProgressEntity> progressEntries) {
|
||||
OffsetDateTime now = getCurrentUtc();
|
||||
String timestamp = now.toString();
|
||||
|
||||
return progressEntries.stream()
|
||||
.map(progress -> buildChangedReadingState(progress, timestamp, now))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private ChangedReadingState buildChangedReadingState(UserBookProgressEntity progress, String timestamp, OffsetDateTime now) {
|
||||
String entitlementId = String.valueOf(progress.getBook().getId());
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = progress.getKoboProgressPercent() != null
|
||||
? readingStateBuilder.buildBookmarkFromProgress(progress, now)
|
||||
: readingStateBuilder.buildEmptyBookmark(now);
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.created(timestamp)
|
||||
.lastModified(timestamp)
|
||||
.priorityTimestamp(timestamp)
|
||||
.statusInfo(readingStateBuilder.buildStatusInfoFromProgress(progress, timestamp))
|
||||
.currentBookmark(bookmark)
|
||||
.statistics(KoboReadingState.Statistics.builder().lastModified(timestamp).build())
|
||||
.build();
|
||||
|
||||
return ChangedReadingState.builder()
|
||||
.changedReadingState(ChangedReadingState.WrappedReadingState.builder()
|
||||
.readingState(readingState)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private KoboReadingState createInitialReadingState(BookEntity book) {
|
||||
OffsetDateTime now = getCurrentUtc();
|
||||
OffsetDateTime createdOn = getCreatedOn(book);
|
||||
String entitlementId = String.valueOf(book.getId());
|
||||
|
||||
KoboReadingState existingState = readingStateRepository.findByEntitlementId(entitlementId)
|
||||
.map(readingStateMapper::toDto)
|
||||
.orElse(null);
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark;
|
||||
if (existingState != null && existingState.getCurrentBookmark() != null) {
|
||||
bookmark = existingState.getCurrentBookmark();
|
||||
} else {
|
||||
bookmark = progressRepository
|
||||
.findByUserIdAndBookId(authenticationService.getAuthenticatedUser().getId(), book.getId())
|
||||
.filter(progress -> progress.getKoboProgressPercent() != null)
|
||||
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now))
|
||||
.orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now));
|
||||
}
|
||||
|
||||
return KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.created(createdOn.toString())
|
||||
.lastModified(now.toString())
|
||||
.statusInfo(KoboReadingState.StatusInfo.builder()
|
||||
Optional<UserBookProgressEntity> userProgress = progressRepository
|
||||
.findByUserIdAndBookId(authenticationService.getAuthenticatedUser().getId(), book.getId());
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = existingState != null && existingState.getCurrentBookmark() != null
|
||||
? existingState.getCurrentBookmark()
|
||||
: userProgress
|
||||
.filter(progress -> progress.getKoboProgressPercent() != null)
|
||||
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now))
|
||||
.orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now));
|
||||
|
||||
KoboReadingState.StatusInfo statusInfo = userProgress
|
||||
.map(progress -> readingStateBuilder.buildStatusInfoFromProgress(progress, now.toString()))
|
||||
.orElseGet(() -> KoboReadingState.StatusInfo.builder()
|
||||
.lastModified(now.toString())
|
||||
.status(KoboReadStatus.READY_TO_READ)
|
||||
.timesStartedReading(0)
|
||||
.build())
|
||||
.build());
|
||||
|
||||
return KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.created(getCreatedOn(book).toString())
|
||||
.lastModified(now.toString())
|
||||
.statusInfo(statusInfo)
|
||||
.currentBookmark(bookmark)
|
||||
.statistics(KoboReadingState.Statistics.builder()
|
||||
.lastModified(now.toString())
|
||||
.build())
|
||||
.statistics(KoboReadingState.Statistics.builder().lastModified(now.toString()).build())
|
||||
.priorityTimestamp(now.toString())
|
||||
.build();
|
||||
}
|
||||
@@ -145,7 +176,7 @@ public class KoboEntitlementService {
|
||||
public KoboBookMetadata getMetadataForBook(long bookId, String token) {
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(Set.of(bookId))
|
||||
.stream()
|
||||
.filter(bookEntity -> bookEntity.getBookType() == BookFileType.EPUB)
|
||||
.filter(koboCompatibilityService::isBookSupportedForKobo)
|
||||
.toList();
|
||||
return mapToKoboMetadata(books.getFirst(), token);
|
||||
}
|
||||
@@ -180,8 +211,16 @@ public class KoboEntitlementService {
|
||||
|
||||
KoboBookFormat bookFormat = KoboBookFormat.EPUB3;
|
||||
KoboSettings koboSettings = appSettingService.getAppSettings().getKoboSettings();
|
||||
if (koboSettings != null && koboSettings.isConvertToKepub()) {
|
||||
bookFormat = KoboBookFormat.KEPUB;
|
||||
|
||||
boolean isEpubFile = book.getBookType() == BookFileType.EPUB;
|
||||
boolean isCbxFile = book.getBookType() == BookFileType.CBX;
|
||||
|
||||
if (koboSettings != null) {
|
||||
if (isEpubFile && koboSettings.isConvertToKepub()) {
|
||||
bookFormat = KoboBookFormat.KEPUB;
|
||||
} else if (isCbxFile && koboSettings.isConvertCbxToEpub()) {
|
||||
bookFormat = KoboBookFormat.EPUB3;
|
||||
}
|
||||
}
|
||||
|
||||
return KoboBookMetadata.builder()
|
||||
@@ -205,6 +244,7 @@ public class KoboEntitlementService {
|
||||
.description(metadata.getDescription())
|
||||
.contributors(authors)
|
||||
.series(series)
|
||||
.language(metadata.getLanguage())
|
||||
.downloadUrls(List.of(
|
||||
KoboBookMetadata.DownloadUrl.builder()
|
||||
.url(downloadUrl)
|
||||
@@ -222,4 +262,4 @@ public class KoboEntitlementService {
|
||||
private OffsetDateTime getCreatedOn(BookEntity book) {
|
||||
return book.getAddedOn() != null ? book.getAddedOn().atOffset(ZoneOffset.UTC) : getCurrentUtc();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -5,7 +5,6 @@ import com.adityachandel.booklore.model.entity.KoboDeletedBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.entity.KoboSnapshotBookEntity;
|
||||
import com.adityachandel.booklore.model.entity.ShelfEntity;
|
||||
import com.adityachandel.booklore.model.entity.KoboLibrarySnapshotEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.ShelfType;
|
||||
import com.adityachandel.booklore.repository.KoboDeletedBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||
@@ -29,6 +28,7 @@ public class KoboLibrarySnapshotService {
|
||||
private final ShelfRepository shelfRepository;
|
||||
private final BookEntityToKoboSnapshotBookMapper mapper;
|
||||
private final KoboDeletedBookProgressRepository koboDeletedBookProgressRepository;
|
||||
private final KoboCompatibilityService koboCompatibilityService;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<KoboLibrarySnapshotEntity> findByIdAndUserId(String id, Long userId) {
|
||||
@@ -118,7 +118,7 @@ public class KoboLibrarySnapshotService {
|
||||
|
||||
private List<KoboSnapshotBookEntity> mapBooksToKoboSnapshotBook(ShelfEntity shelf, KoboLibrarySnapshotEntity snapshot) {
|
||||
return shelf.getBookEntities().stream()
|
||||
.filter(bookEntity -> bookEntity.getBookType() == BookFileType.EPUB)
|
||||
.filter(koboCompatibilityService::isBookSupportedForKobo)
|
||||
.map(book -> {
|
||||
KoboSnapshotBookEntity snapshotBook = mapper.toKoboSnapshotBook(book);
|
||||
snapshotBook.setSnapshot(snapshot);
|
||||
@@ -130,4 +130,5 @@ public class KoboLibrarySnapshotService {
|
||||
public void deleteById(String id) {
|
||||
koboLibrarySnapshotRepository.deleteById(id);
|
||||
}
|
||||
|
||||
}
|
||||
+58
-1
@@ -6,7 +6,9 @@ import com.adityachandel.booklore.model.dto.BookloreSyncToken;
|
||||
import com.adityachandel.booklore.model.dto.kobo.*;
|
||||
import com.adityachandel.booklore.model.entity.KoboSnapshotBookEntity;
|
||||
import com.adityachandel.booklore.model.entity.KoboLibrarySnapshotEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.repository.KoboDeletedBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.util.RequestUtils;
|
||||
import com.adityachandel.booklore.util.kobo.BookloreSyncTokenGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
@@ -17,9 +19,11 @@ import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -32,9 +36,11 @@ public class KoboLibrarySyncService {
|
||||
private final KoboLibrarySnapshotService koboLibrarySnapshotService;
|
||||
private final KoboEntitlementService entitlementService;
|
||||
private final KoboDeletedBookProgressRepository koboDeletedBookProgressRepository;
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final KoboServerProxy koboServerProxy;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Transactional
|
||||
public ResponseEntity<?> syncLibrary(BookLoreUser user, String token) {
|
||||
HttpServletRequest request = RequestUtils.getCurrentRequest();
|
||||
BookloreSyncToken syncToken = Optional.ofNullable(tokenGenerator.fromRequestHeaders(request)).orElse(new BookloreSyncToken());
|
||||
@@ -68,6 +74,10 @@ public class KoboLibrarySyncService {
|
||||
|
||||
entitlements.addAll(entitlementService.generateNewEntitlements(addedIds, token, false));
|
||||
entitlements.addAll(entitlementService.generateChangedEntitlements(removedIds, token, true));
|
||||
|
||||
if (!shouldContinueSync) {
|
||||
entitlements.addAll(syncReadingStatesToKobo(user.getId(), currSnapshot.getId()));
|
||||
}
|
||||
} else {
|
||||
int maxRemaining = 5;
|
||||
List<KoboSnapshotBookEntity> all = new ArrayList<>();
|
||||
@@ -80,6 +90,10 @@ public class KoboLibrarySyncService {
|
||||
}
|
||||
Set<Long> ids = all.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet());
|
||||
entitlements.addAll(entitlementService.generateNewEntitlements(ids, token, false));
|
||||
|
||||
if (!shouldContinueSync) {
|
||||
entitlements.addAll(syncReadingStatesToKobo(user.getId(), currSnapshot.getId()));
|
||||
}
|
||||
}
|
||||
|
||||
if (!shouldContinueSync) {
|
||||
@@ -131,4 +145,47 @@ public class KoboLibrarySyncService {
|
||||
.header(KoboHeaders.X_KOBO_SYNCTOKEN, tokenGenerator.toBase64(syncToken))
|
||||
.body(entitlements);
|
||||
}
|
||||
}
|
||||
|
||||
private List<ChangedReadingState> syncReadingStatesToKobo(Long userId, String snapshotId) {
|
||||
List<UserBookProgressEntity> booksNeedingSync =
|
||||
userBookProgressRepository.findAllBooksNeedingKoboSync(userId, snapshotId);
|
||||
|
||||
if (booksNeedingSync.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
List<ChangedReadingState> changedStates = entitlementService.generateChangedReadingStates(booksNeedingSync);
|
||||
|
||||
Instant sentTime = Instant.now();
|
||||
for (UserBookProgressEntity progress : booksNeedingSync) {
|
||||
if (needsStatusSync(progress)) {
|
||||
progress.setKoboStatusSentTime(sentTime);
|
||||
}
|
||||
if (needsProgressSync(progress)) {
|
||||
progress.setKoboProgressSentTime(sentTime);
|
||||
}
|
||||
}
|
||||
userBookProgressRepository.saveAll(booksNeedingSync);
|
||||
|
||||
log.info("Synced {} reading states to Kobo", changedStates.size());
|
||||
return changedStates;
|
||||
}
|
||||
|
||||
private boolean needsStatusSync(UserBookProgressEntity progress) {
|
||||
Instant modifiedTime = progress.getReadStatusModifiedTime();
|
||||
if (modifiedTime == null) {
|
||||
return false;
|
||||
}
|
||||
Instant sentTime = progress.getKoboStatusSentTime();
|
||||
return sentTime == null || modifiedTime.isAfter(sentTime);
|
||||
}
|
||||
|
||||
private boolean needsProgressSync(UserBookProgressEntity progress) {
|
||||
Instant receivedTime = progress.getKoboProgressReceivedTime();
|
||||
if (receivedTime == null) {
|
||||
return false;
|
||||
}
|
||||
Instant sentTime = progress.getKoboProgressSentTime();
|
||||
return sentTime == null || receivedTime.isAfter(sentTime);
|
||||
}
|
||||
}
|
||||
|
||||
+35
-3
@@ -2,6 +2,8 @@ package com.adityachandel.booklore.service.kobo;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.kobo.KoboReadingState;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.enums.KoboReadStatus;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Instant;
|
||||
@@ -24,14 +26,14 @@ public class KoboReadingStateBuilder {
|
||||
|
||||
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) {
|
||||
KoboReadingState.CurrentBookmark.Location location = Optional.ofNullable(progress.getKoboLocation())
|
||||
.map(loc -> KoboReadingState.CurrentBookmark.Location.builder()
|
||||
.value(loc)
|
||||
.map(koboLocation -> KoboReadingState.CurrentBookmark.Location.builder()
|
||||
.value(koboLocation)
|
||||
.type(progress.getKoboLocationType())
|
||||
.source(progress.getKoboLocationSource())
|
||||
.build())
|
||||
.orElse(null);
|
||||
|
||||
String lastModified = Optional.ofNullable(progress.getKoboLastSyncTime())
|
||||
String lastModified = Optional.ofNullable(progress.getKoboProgressReceivedTime())
|
||||
.map(this::formatTimestamp)
|
||||
.or(() -> Optional.ofNullable(defaultTime).map(OffsetDateTime::toString))
|
||||
.orElse(null);
|
||||
@@ -48,15 +50,45 @@ public class KoboReadingStateBuilder {
|
||||
public KoboReadingState buildReadingStateFromProgress(String entitlementId, UserBookProgressEntity progress) {
|
||||
KoboReadingState.CurrentBookmark bookmark = buildBookmarkFromProgress(progress);
|
||||
String lastModified = bookmark.getLastModified();
|
||||
KoboReadingState.StatusInfo statusInfo = buildStatusInfoFromProgress(progress, lastModified);
|
||||
|
||||
return KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(bookmark)
|
||||
.statusInfo(statusInfo)
|
||||
.created(lastModified)
|
||||
.lastModified(lastModified)
|
||||
.build();
|
||||
}
|
||||
|
||||
public KoboReadingState.StatusInfo buildStatusInfoFromProgress(UserBookProgressEntity progress, String lastModified) {
|
||||
KoboReadStatus koboStatus = mapReadStatusToKoboStatus(progress.getReadStatus());
|
||||
int timesStartedReading = koboStatus == KoboReadStatus.READY_TO_READ ? 0 : 1;
|
||||
|
||||
KoboReadingState.StatusInfo.StatusInfoBuilder builder = KoboReadingState.StatusInfo.builder()
|
||||
.lastModified(lastModified)
|
||||
.status(koboStatus)
|
||||
.timesStartedReading(timesStartedReading);
|
||||
|
||||
if (koboStatus == KoboReadStatus.FINISHED && progress.getDateFinished() != null) {
|
||||
builder.lastTimeFinished(formatTimestamp(progress.getDateFinished()));
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
public KoboReadStatus mapReadStatusToKoboStatus(ReadStatus readStatus) {
|
||||
if (readStatus == null) {
|
||||
return KoboReadStatus.READY_TO_READ;
|
||||
}
|
||||
|
||||
return switch (readStatus) {
|
||||
case READ -> KoboReadStatus.FINISHED;
|
||||
case PARTIALLY_READ, READING, RE_READING, PAUSED -> KoboReadStatus.READING;
|
||||
case UNREAD, WONT_READ, ABANDONED, UNSET -> KoboReadStatus.READY_TO_READ;
|
||||
};
|
||||
}
|
||||
|
||||
private String formatTimestamp(Instant instant) {
|
||||
return instant.atOffset(ZoneOffset.UTC).toString();
|
||||
}
|
||||
|
||||
+55
-32
@@ -31,6 +31,8 @@ import java.util.stream.Collectors;
|
||||
@RequiredArgsConstructor
|
||||
public class KoboReadingStateService {
|
||||
|
||||
private static final int STATUS_SYNC_BUFFER_SECONDS = 10;
|
||||
|
||||
private final KoboReadingStateRepository repository;
|
||||
private final KoboReadingStateMapper mapper;
|
||||
private final UserBookProgressRepository progressRepository;
|
||||
@@ -88,6 +90,11 @@ public class KoboReadingStateService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteReadingState(Long bookId) {
|
||||
repository.findByEntitlementId(String.valueOf(bookId)).ifPresent(repository::delete);
|
||||
}
|
||||
|
||||
public KoboReadingStateWrapper getReadingState(String entitlementId) {
|
||||
Optional<KoboReadingState> readingState = repository.findByEntitlementId(entitlementId)
|
||||
.map(mapper::toDto)
|
||||
@@ -105,11 +112,7 @@ public class KoboReadingStateService {
|
||||
|
||||
return progressRepository.findByUserIdAndBookId(user.getId(), bookId)
|
||||
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null)
|
||||
.map(progress -> {
|
||||
log.info("Constructed reading state from UserBookProgress for book: {}, progress: {}%",
|
||||
entitlementId, progress.getKoboProgressPercent());
|
||||
return readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress);
|
||||
});
|
||||
.map(progress -> readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress));
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("Invalid entitlement ID format when constructing reading state: {}", entitlementId);
|
||||
return Optional.empty();
|
||||
@@ -155,43 +158,63 @@ public class KoboReadingStateService {
|
||||
}
|
||||
}
|
||||
|
||||
progress.setKoboLastSyncTime(Instant.now());
|
||||
progress.setLastReadTime(Instant.now());
|
||||
Instant now = Instant.now();
|
||||
progress.setKoboProgressReceivedTime(now);
|
||||
progress.setLastReadTime(now);
|
||||
|
||||
if (progress.getKoboProgressPercent() != null) {
|
||||
updateKoboReadStatus(progress, progress.getKoboProgressPercent() / 100.0);
|
||||
updateReadStatusFromKoboProgress(progress, now);
|
||||
}
|
||||
|
||||
progressRepository.save(progress);
|
||||
|
||||
log.info("Synced Kobo progress to BookLore: userId={}, bookId={}, progress={}%",
|
||||
userId, bookId, progress.getKoboProgressPercent());
|
||||
|
||||
log.debug("Synced Kobo progress: bookId={}, progress={}%", bookId, progress.getKoboProgressPercent());
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("Invalid entitlement ID format: {}", readingState.getEntitlementId());
|
||||
}
|
||||
}
|
||||
|
||||
private void updateKoboReadStatus(UserBookProgressEntity userProgress, double progressFraction) {
|
||||
KoboSyncSettings settings = koboSettingsService.getCurrentUserSettings();
|
||||
|
||||
double progressPercent = progressFraction * 100.0;
|
||||
float finishedThreshold = settings.getProgressMarkAsFinishedThreshold() != null
|
||||
? settings.getProgressMarkAsFinishedThreshold()
|
||||
: 99f;
|
||||
float readingThreshold = settings.getProgressMarkAsReadingThreshold() != null
|
||||
? settings.getProgressMarkAsReadingThreshold()
|
||||
: 1f;
|
||||
|
||||
if (progressPercent >= finishedThreshold) {
|
||||
userProgress.setReadStatus(ReadStatus.READ);
|
||||
if (userProgress.getDateFinished() == null) {
|
||||
userProgress.setDateFinished(Instant.now());
|
||||
}
|
||||
} else if (progressPercent >= readingThreshold) {
|
||||
userProgress.setReadStatus(ReadStatus.READING);
|
||||
} else {
|
||||
userProgress.setReadStatus(ReadStatus.UNREAD);
|
||||
private void updateReadStatusFromKoboProgress(UserBookProgressEntity userProgress, Instant now) {
|
||||
if (shouldPreserveCurrentStatus(userProgress, now)) {
|
||||
return;
|
||||
}
|
||||
|
||||
double koboProgressPercent = userProgress.getKoboProgressPercent();
|
||||
|
||||
ReadStatus derivedStatus = deriveStatusFromProgress(koboProgressPercent);
|
||||
userProgress.setReadStatus(derivedStatus);
|
||||
|
||||
if (derivedStatus == ReadStatus.READ && userProgress.getDateFinished() == null) {
|
||||
userProgress.setDateFinished(Instant.now());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean shouldPreserveCurrentStatus(UserBookProgressEntity progress, Instant now) {
|
||||
Instant statusModifiedTime = progress.getReadStatusModifiedTime();
|
||||
if (statusModifiedTime == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Instant statusSentTime = progress.getKoboStatusSentTime();
|
||||
|
||||
boolean hasPendingStatusUpdate = statusSentTime == null || statusModifiedTime.isAfter(statusSentTime);
|
||||
if (hasPendingStatusUpdate) {
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean withinSyncBufferWindow = now.isBefore(statusSentTime.plusSeconds(STATUS_SYNC_BUFFER_SECONDS));
|
||||
return withinSyncBufferWindow;
|
||||
}
|
||||
|
||||
private ReadStatus deriveStatusFromProgress(double progressPercent) {
|
||||
KoboSyncSettings settings = koboSettingsService.getCurrentUserSettings();
|
||||
|
||||
float finishedThreshold = settings.getProgressMarkAsFinishedThreshold() != null
|
||||
? settings.getProgressMarkAsFinishedThreshold() : 99f;
|
||||
float readingThreshold = settings.getProgressMarkAsReadingThreshold() != null
|
||||
? settings.getProgressMarkAsReadingThreshold() : 1f;
|
||||
|
||||
if (progressPercent >= finishedThreshold) return ReadStatus.READ;
|
||||
if (progressPercent >= readingThreshold) return ReadStatus.READING;
|
||||
return ReadStatus.UNREAD;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-3
@@ -5,7 +5,6 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||
@@ -23,7 +22,6 @@ public class FileAsBookProcessor implements LibraryFileProcessor {
|
||||
|
||||
private final BookEventBroadcaster bookEventBroadcaster;
|
||||
private final BookFileProcessorRegistry processorRegistry;
|
||||
private final NotificationService notificationService;
|
||||
|
||||
@Override
|
||||
public LibraryScanMode getScanMode() {
|
||||
@@ -40,7 +38,7 @@ public class FileAsBookProcessor implements LibraryFileProcessor {
|
||||
|
||||
if (result != null) {
|
||||
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
|
||||
log.info("Processed file: {}", libraryFile.getFileName());
|
||||
log.debug("Processed file: {}", libraryFile.getFileName());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-4
@@ -19,6 +19,7 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -39,13 +40,19 @@ public class LibraryProcessingService {
|
||||
private final EntityManager entityManager;
|
||||
|
||||
@Transactional
|
||||
public void processLibrary(long libraryId) throws IOException {
|
||||
public void processLibrary(long libraryId) {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started processing library: " + libraryEntity.getName()));
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity, processor);
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished processing library: " + libraryEntity.getName()));
|
||||
try {
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity, processor);
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished processing library: " + libraryEntity.getName()));
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to process library {}: {}", libraryEntity.getName(), e.getMessage(), e);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.error("Failed to process library: " + libraryEntity.getName() + " - " + e.getMessage()));
|
||||
throw new UncheckedIOException("Library processing failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
|
||||
-4
@@ -130,8 +130,6 @@ public class LibraryService {
|
||||
libraryProcessingService.processLibrary(libraryId);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
} catch (IOException e) {
|
||||
log.error("Error while parsing library books", e);
|
||||
}
|
||||
log.info("Parsing task completed!");
|
||||
});
|
||||
@@ -171,8 +169,6 @@ public class LibraryService {
|
||||
libraryProcessingService.processLibrary(libraryId);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
} catch (IOException e) {
|
||||
log.error("Error while parsing library books", e);
|
||||
}
|
||||
log.info("Parsing task completed!");
|
||||
});
|
||||
|
||||
+2
-2
@@ -74,6 +74,8 @@ public class BookMetadataUpdater {
|
||||
MetadataClearFlags clearFlags = wrapper.getClearFlags();
|
||||
BookMetadataEntity metadata = bookEntity.getMetadata();
|
||||
|
||||
updateLocks(newMetadata, metadata);
|
||||
|
||||
boolean thumbnailRequiresUpdate = StringUtils.hasText(newMetadata.getThumbnailUrl());
|
||||
boolean hasMetadataChanges = MetadataChangeDetector.isDifferent(newMetadata, metadata, clearFlags);
|
||||
boolean hasValueChanges = MetadataChangeDetector.hasValueChanges(newMetadata, metadata, clearFlags);
|
||||
@@ -82,8 +84,6 @@ public class BookMetadataUpdater {
|
||||
return;
|
||||
}
|
||||
|
||||
updateLocks(newMetadata, metadata);
|
||||
|
||||
if (metadata.areAllFieldsLocked()) {
|
||||
log.warn("All fields are locked for book ID {}. Skipping update.", bookId);
|
||||
return;
|
||||
|
||||
+4
-20
@@ -111,11 +111,7 @@ public class MetadataManagementService {
|
||||
|
||||
for (BookMetadataEntity metadata : booksWithOldAuthor) {
|
||||
metadata.getAuthors().remove(oldAuthor);
|
||||
for (AuthorEntity targetAuthor : targetAuthors) {
|
||||
if (!metadata.getAuthors().contains(targetAuthor)) {
|
||||
metadata.getAuthors().add(targetAuthor);
|
||||
}
|
||||
}
|
||||
metadata.getAuthors().addAll(targetAuthors);
|
||||
}
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithOldAuthor);
|
||||
@@ -156,11 +152,7 @@ public class MetadataManagementService {
|
||||
|
||||
for (BookMetadataEntity metadata : booksWithOldCategory) {
|
||||
metadata.getCategories().remove(oldCategory);
|
||||
for (CategoryEntity targetCategory : targetCategories) {
|
||||
if (!metadata.getCategories().contains(targetCategory)) {
|
||||
metadata.getCategories().add(targetCategory);
|
||||
}
|
||||
}
|
||||
metadata.getCategories().addAll(targetCategories);
|
||||
}
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithOldCategory);
|
||||
@@ -201,11 +193,7 @@ public class MetadataManagementService {
|
||||
|
||||
for (BookMetadataEntity metadata : booksWithOldMood) {
|
||||
metadata.getMoods().remove(oldMood);
|
||||
for (MoodEntity targetMood : targetMoods) {
|
||||
if (!metadata.getMoods().contains(targetMood)) {
|
||||
metadata.getMoods().add(targetMood);
|
||||
}
|
||||
}
|
||||
metadata.getMoods().addAll(targetMoods);
|
||||
}
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithOldMood);
|
||||
@@ -246,11 +234,7 @@ public class MetadataManagementService {
|
||||
|
||||
for (BookMetadataEntity metadata : booksWithOldTag) {
|
||||
metadata.getTags().remove(oldTag);
|
||||
for (TagEntity targetTag : targetTags) {
|
||||
if (!metadata.getTags().contains(targetTag)) {
|
||||
metadata.getTags().add(targetTag);
|
||||
}
|
||||
}
|
||||
metadata.getTags().addAll(targetTags);
|
||||
}
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithOldTag);
|
||||
|
||||
-3
@@ -258,9 +258,6 @@ public class MetadataRefreshService {
|
||||
}
|
||||
|
||||
private void saveProposal(MetadataFetchJobEntity job, Long bookId, BookMetadata metadata) throws JsonProcessingException {
|
||||
if (job.getProposals() == null) {
|
||||
job.setProposals(new ArrayList<>());
|
||||
}
|
||||
MetadataFetchProposalEntity proposal = MetadataFetchProposalEntity.builder()
|
||||
.job(job)
|
||||
.bookId(bookId)
|
||||
|
||||
+5
-5
@@ -672,7 +672,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
|
||||
// ==== 7z (.cb7) helpers ====
|
||||
private SevenZArchiveEntry findSevenZComicInfoEntry(SevenZFile sevenZ) throws IOException {
|
||||
private SevenZArchiveEntry findSevenZComicInfoEntry(SevenZFile sevenZ) {
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (e == null || e.isDirectory()) continue;
|
||||
String name = e.getName();
|
||||
@@ -683,7 +683,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
return null;
|
||||
}
|
||||
|
||||
private SevenZArchiveEntry findSevenZEntryByName(SevenZFile sevenZ, String imageName) throws IOException {
|
||||
private SevenZArchiveEntry findSevenZEntryByName(SevenZFile sevenZ, String imageName) {
|
||||
if (imageName == null) return null;
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (e == null || e.isDirectory()) continue;
|
||||
@@ -696,7 +696,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
return null;
|
||||
}
|
||||
|
||||
private SevenZArchiveEntry findSevenZImageEntryByIndex(SevenZFile sevenZ, int index) throws IOException {
|
||||
private SevenZArchiveEntry findSevenZImageEntryByIndex(SevenZFile sevenZ, int index) {
|
||||
int count = 0;
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (!e.isDirectory() && isImageEntry(e.getName())) {
|
||||
@@ -707,7 +707,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
return null;
|
||||
}
|
||||
|
||||
private SevenZArchiveEntry findFirstAlphabeticalSevenZImageEntry(SevenZFile sevenZ) throws IOException {
|
||||
private SevenZArchiveEntry findFirstAlphabeticalSevenZImageEntry(SevenZFile sevenZ) {
|
||||
List<SevenZArchiveEntry> images = new ArrayList<>();
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (!e.isDirectory() && isImageEntry(e.getName())) {
|
||||
@@ -741,7 +741,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
return images;
|
||||
}
|
||||
|
||||
private java.util.List<SevenZArchiveEntry> listSevenZImageEntries(SevenZFile sevenZ) throws IOException {
|
||||
private java.util.List<SevenZArchiveEntry> listSevenZImageEntries(SevenZFile sevenZ) {
|
||||
java.util.List<SevenZArchiveEntry> images = new java.util.ArrayList<>();
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (!e.isDirectory() && isImageEntry(e.getName())) images.add(e);
|
||||
|
||||
+2
-2
@@ -137,14 +137,14 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
if ("calibre:pages".equals(name) || "pagecount".equals(name) || "schema:pagecount".equals(prop) || "media:pagecount".equals(prop) || "booklore:page_count".equals(prop)) {
|
||||
safeParseInt(content, builderMeta::pageCount);
|
||||
} else if (name.equals("calibre:user_metadata:#pagecount")) {
|
||||
} else if ("calibre:user_metadata:#pagecount".equals(name)) {
|
||||
try {
|
||||
JSONObject jsonroot = new JSONObject(content);
|
||||
Object value = jsonroot.opt("#value#");
|
||||
safeParseInt(String.valueOf(value), builderMeta::pageCount);
|
||||
} catch (JSONException ignored) {
|
||||
}
|
||||
} else if (prop.equals("calibre:user_metadata")) {
|
||||
} else if ("calibre:user_metadata".equals(prop)) {
|
||||
try {
|
||||
JSONObject jsonroot = new JSONObject(content);
|
||||
JSONObject pages = jsonroot.getJSONObject("#pagecount");
|
||||
|
||||
+10
-4
@@ -47,14 +47,20 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
@Override
|
||||
public byte[] extractCover(File file) {
|
||||
BufferedImage coverImage = null;
|
||||
try (PDDocument pdf = Loader.loadPDF(file)) {
|
||||
BufferedImage coverImage = new PDFRenderer(pdf).renderImageWithDPI(0, 300, ImageType.RGB);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ImageIO.write(coverImage, "jpg", baos);
|
||||
return baos.toByteArray();
|
||||
coverImage = new PDFRenderer(pdf).renderImageWithDPI(0, 300, ImageType.RGB);
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
ImageIO.write(coverImage, "jpg", baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract cover from PDF: {}", file.getAbsolutePath(), e);
|
||||
return null;
|
||||
} finally {
|
||||
if (coverImage != null) {
|
||||
coverImage.flush(); // Release native resources
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-1
@@ -236,7 +236,6 @@ public class DoubanBookParser implements BookParser {
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Error parsing search result item: {}", e.getMessage());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-1
@@ -20,6 +20,7 @@ import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -59,7 +60,8 @@ public class HardcoverParser implements BookParser {
|
||||
if (doc.getAuthorNames() == null || doc.getAuthorNames().isEmpty()) return false;
|
||||
|
||||
List<String> actualAuthorTokens = doc.getAuthorNames().stream()
|
||||
.flatMap(name -> List.of(WHITESPACE_PATTERN.split(name.toLowerCase())).stream())
|
||||
.map(String::toLowerCase)
|
||||
.flatMap(WHITESPACE_PATTERN::splitAsStream)
|
||||
.toList();
|
||||
List<String> searchAuthorTokens = List.of(WHITESPACE_PATTERN.split(searchAuthor.toLowerCase()));
|
||||
|
||||
|
||||
+11
-2
@@ -130,9 +130,11 @@ public class AppMigrationService {
|
||||
try (var stream = Files.walk(thumbsDir)) {
|
||||
stream.filter(Files::isRegularFile)
|
||||
.forEach(path -> {
|
||||
BufferedImage originalImage = null;
|
||||
BufferedImage resized = null;
|
||||
try {
|
||||
// Load original image
|
||||
BufferedImage originalImage = ImageIO.read(path.toFile());
|
||||
originalImage = ImageIO.read(path.toFile());
|
||||
if (originalImage == null) {
|
||||
log.warn("Skipping non-image file: {}", path);
|
||||
return;
|
||||
@@ -150,7 +152,7 @@ public class AppMigrationService {
|
||||
ImageIO.write(originalImage, "jpg", coverFile.toFile());
|
||||
|
||||
// Resize and save thumbnail.jpg
|
||||
BufferedImage resized = FileService.resizeImage(originalImage, 250, 350);
|
||||
resized = FileService.resizeImage(originalImage, 250, 350);
|
||||
Path thumbnailFile = bookDir.resolve("thumbnail.jpg");
|
||||
ImageIO.write(resized, "jpg", thumbnailFile.toFile());
|
||||
|
||||
@@ -158,6 +160,13 @@ public class AppMigrationService {
|
||||
} catch (IOException e) {
|
||||
log.error("Error processing file {}", path, e);
|
||||
throw new UncheckedIOException(e);
|
||||
} finally {
|
||||
if (originalImage != null) {
|
||||
originalImage.flush();
|
||||
}
|
||||
if (resized != null) {
|
||||
resized.flush();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
-1
@@ -46,7 +46,6 @@ public class MonitoringTask {
|
||||
log.warn("WatchKey is no longer valid: {}", directory);
|
||||
// Clean up but DO NOT break
|
||||
eventPublisher.publishEvent(new WatchKeyInvalidatedEvent(this, directory));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.adityachandel.booklore.service.opds;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.GroupRule;
|
||||
import com.adityachandel.booklore.model.dto.Library;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.MagicShelfEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.MagicShelfRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.BookRuleEvaluatorService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class MagicShelfBookService {
|
||||
|
||||
private final MagicShelfRepository magicShelfRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final BookMapper bookMapper;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
private final BookRuleEvaluatorService ruleEvaluatorService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public Page<Book> getBooksByMagicShelfId(Long userId, Long magicShelfId, int page, int size) {
|
||||
MagicShelfEntity shelf = validateMagicShelfAccess(userId, magicShelfId);
|
||||
try {
|
||||
GroupRule groupRule = objectMapper.readValue(shelf.getFilterJson(), GroupRule.class);
|
||||
Specification<BookEntity> specification = ruleEvaluatorService.toSpecification(groupRule, userId);
|
||||
specification = specification.and(createLibraryFilterSpecification(userId));
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<BookEntity> booksPage = bookRepository.findAll(specification, pageable);
|
||||
|
||||
return booksPage.map(bookMapper::toBook).map(book -> filterBook(book, userId));
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to parse or execute magic shelf rules", e);
|
||||
throw new RuntimeException("Failed to parse or execute magic shelf rules: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public String getMagicShelfName(Long magicShelfId) {
|
||||
return magicShelfRepository.findById(magicShelfId)
|
||||
.map(s -> s.getName() + " - Magic Shelf")
|
||||
.orElse("Magic Shelf Books");
|
||||
}
|
||||
|
||||
private MagicShelfEntity validateMagicShelfAccess(Long userId, Long magicShelfId) {
|
||||
MagicShelfEntity shelf = magicShelfRepository.findById(magicShelfId)
|
||||
.orElseThrow(() -> ApiError.MAGIC_SHELF_NOT_FOUND.createException(magicShelfId));
|
||||
|
||||
if (userId == null) {
|
||||
if (!shelf.isPublic()) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not allowed to access this magic shelf");
|
||||
}
|
||||
return shelf;
|
||||
}
|
||||
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
|
||||
if (entity.getPermissions() == null ||
|
||||
(!entity.getPermissions().isPermissionAccessOpds() && !entity.getPermissions().isPermissionAdmin())) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not allowed to access this resource");
|
||||
}
|
||||
|
||||
boolean isOwner = shelf.getUserId().equals(userId);
|
||||
boolean isPublic = shelf.isPublic();
|
||||
boolean isAdmin = entity.getPermissions().isPermissionAdmin();
|
||||
|
||||
if (!isOwner && !isPublic && !isAdmin) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not allowed to access this magic shelf");
|
||||
}
|
||||
|
||||
return shelf;
|
||||
}
|
||||
|
||||
private Specification<BookEntity> createLibraryFilterSpecification(Long userId) {
|
||||
return (root, query, cb) -> {
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
if (user.getPermissions() != null && user.getPermissions().isAdmin()) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
|
||||
Set<Long> userLibraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
return root.get("library").get("id").in(userLibraryIds);
|
||||
};
|
||||
}
|
||||
|
||||
private Book filterBook(Book dto, Long userId) {
|
||||
if (dto.getShelves() != null && userId != null) {
|
||||
dto.setShelves(dto.getShelves().stream()
|
||||
.filter(shelf -> userId.equals(shelf.getUserId()))
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
+59
-90
@@ -1,6 +1,5 @@
|
||||
package com.adityachandel.booklore.service.opds;
|
||||
|
||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
@@ -36,17 +35,11 @@ public class OpdsBookService {
|
||||
private final ShelfRepository shelfRepository;
|
||||
private final LibraryService libraryService;
|
||||
|
||||
public List<Library> getAccessibleLibraries(OpdsUserDetails details) {
|
||||
if (details == null || details.getOpdsUserV2() == null) {
|
||||
try {
|
||||
return libraryService.getAllLibraries();
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to get all libraries", e);
|
||||
return List.of();
|
||||
}
|
||||
public List<Library> getAccessibleLibraries(Long userId) {
|
||||
if (userId == null) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
Long userId = details.getOpdsUserV2().getUserId();
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
@@ -58,24 +51,57 @@ public class OpdsBookService {
|
||||
return user.getAssignedLibraries();
|
||||
}
|
||||
|
||||
public Page<Book> getBooksPage(OpdsUserDetails details, String query, Long libraryId, Long shelfId, int page, int size) {
|
||||
OpdsUser opdsUser = details.getOpdsUser();
|
||||
|
||||
if (opdsUser != null) {
|
||||
return getBooksPageForLegacyUser(query, libraryId, shelfId, page, size);
|
||||
public Page<Book> getBooksPage(Long userId, String query, Long libraryId, Long shelfId, int page, int size) {
|
||||
if (userId == null) {
|
||||
throw ApiError.FORBIDDEN.createException("Authentication required");
|
||||
}
|
||||
|
||||
return getBooksPageForV2User(details.getOpdsUserV2(), query, libraryId, shelfId, page, size);
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
|
||||
if (entity.getPermissions() == null ||
|
||||
(!entity.getPermissions().isPermissionAccessOpds() && !entity.getPermissions().isPermissionAdmin())) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not allowed to access this resource");
|
||||
}
|
||||
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
boolean isAdmin = user.getPermissions().isAdmin();
|
||||
Set<Long> userLibraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (shelfId != null) {
|
||||
validateShelfAccess(shelfId, user.getId(), isAdmin);
|
||||
return getBooksByShelfIdPageInternal(shelfId, page, size);
|
||||
}
|
||||
|
||||
if (libraryId != null) {
|
||||
validateLibraryAccess(libraryId, userLibraryIds, isAdmin);
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInLibrariesPageInternal(query, Set.of(libraryId), page, size)
|
||||
: getBooksByLibraryIdsPageInternal(Set.of(libraryId), page, size);
|
||||
return applyBookFilters(books, userId);
|
||||
}
|
||||
|
||||
if (isAdmin) {
|
||||
return query != null && !query.isBlank()
|
||||
? searchByMetadataPageInternal(query, page, size)
|
||||
: getAllBooksPageInternal(page, size);
|
||||
}
|
||||
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInLibrariesPageInternal(query, userLibraryIds, page, size)
|
||||
: getBooksByLibraryIdsPageInternal(userLibraryIds, page, size);
|
||||
return applyBookFilters(books, userId);
|
||||
}
|
||||
|
||||
public Page<Book> getRecentBooksPage(OpdsUserDetails details, int page, int size) {
|
||||
if (details == null || details.getOpdsUser() != null) {
|
||||
return getRecentBooksPageInternal(page, size);
|
||||
public Page<Book> getRecentBooksPage(Long userId, int page, int size) {
|
||||
if (userId == null) {
|
||||
throw ApiError.FORBIDDEN.createException("Authentication required");
|
||||
}
|
||||
|
||||
OpdsUserV2 v2 = details.getOpdsUserV2();
|
||||
BookLoreUserEntity entity = userRepository.findById(v2.getUserId())
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(v2.getUserId()));
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
@@ -87,7 +113,7 @@ public class OpdsBookService {
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Page<Book> books = getRecentBooksByLibraryIdsPageInternal(libraryIds, page, size);
|
||||
return applyBookFilters(books, v2.getUserId());
|
||||
return applyBookFilters(books, userId);
|
||||
}
|
||||
|
||||
public String getLibraryName(Long libraryId) {
|
||||
@@ -114,58 +140,21 @@ public class OpdsBookService {
|
||||
return shelfRepository.findByUserId(userId);
|
||||
}
|
||||
|
||||
private Page<Book> getBooksPageForLegacyUser(String query, Long libraryId, Long shelfId, int page, int size) {
|
||||
if (shelfId != null) {
|
||||
return getBooksByShelfIdPageInternal(shelfId, page, size);
|
||||
}
|
||||
if (libraryId != null) {
|
||||
Page<Book> books = getBooksByLibraryIdsPageInternal(Set.of(libraryId), page, size);
|
||||
return applyBookFilters(books, null);
|
||||
}
|
||||
if (query != null && !query.isBlank()) {
|
||||
return searchByMetadataPageInternal(query, page, size);
|
||||
}
|
||||
return getAllBooksPageInternal(page, size);
|
||||
}
|
||||
|
||||
private Page<Book> getBooksPageForV2User(OpdsUserV2 opdsUserV2, String query, Long libraryId, Long shelfId, int page, int size) {
|
||||
BookLoreUserEntity entity = userRepository.findById(opdsUserV2.getUserId())
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(opdsUserV2.getUserId()));
|
||||
|
||||
if (entity.getPermissions() == null ||
|
||||
(!entity.getPermissions().isPermissionAccessOpds() && !entity.getPermissions().isPermissionAdmin())) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not allowed to access this resource");
|
||||
public List<Book> getRandomBooks(Long userId, int count) {
|
||||
List<Library> accessibleLibraries = getAccessibleLibraries(userId);
|
||||
if (accessibleLibraries == null || accessibleLibraries.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
boolean isAdmin = user.getPermissions().isAdmin();
|
||||
Set<Long> userLibraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
List<Long> libraryIds = accessibleLibraries.stream().map(Library::getId).toList();
|
||||
List<Long> ids = bookOpdsRepository.findRandomBookIdsByLibraryIds(libraryIds);
|
||||
|
||||
if (shelfId != null) {
|
||||
validateShelfAccess(shelfId, user.getId(), isAdmin);
|
||||
return getBooksByShelfIdPageInternal(shelfId, page, size);
|
||||
if (ids.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
if (libraryId != null) {
|
||||
validateLibraryAccess(libraryId, userLibraryIds, isAdmin);
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInLibrariesPageInternal(query, Set.of(libraryId), page, size)
|
||||
: getBooksByLibraryIdsPageInternal(Set.of(libraryId), page, size);
|
||||
return applyBookFilters(books, opdsUserV2.getUserId());
|
||||
}
|
||||
|
||||
if (isAdmin) {
|
||||
return query != null && !query.isBlank()
|
||||
? searchByMetadataPageInternal(query, page, size)
|
||||
: getAllBooksPageInternal(page, size);
|
||||
}
|
||||
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInLibrariesPageInternal(query, userLibraryIds, page, size)
|
||||
: getBooksByLibraryIdsPageInternal(userLibraryIds, page, size);
|
||||
return applyBookFilters(books, opdsUserV2.getUserId());
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(ids.stream().limit(count).toList());
|
||||
return books.stream().map(bookMapper::toBook).toList();
|
||||
}
|
||||
|
||||
private Page<Book> getAllBooksPageInternal(int page, int size) {
|
||||
@@ -294,24 +283,4 @@ public class OpdsBookService {
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<Book> getRandomBooks(OpdsUserDetails details, int count) {
|
||||
List<Long> ids;
|
||||
List<Library> accessibleLibraries = getAccessibleLibraries(details);
|
||||
if (accessibleLibraries == null || accessibleLibraries.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> libraryIds = accessibleLibraries.stream().map(Library::getId).toList();
|
||||
|
||||
if (libraryIds.size() == 1 && libraryIds.getFirst() == null) {
|
||||
ids = bookOpdsRepository.findRandomBookIds();
|
||||
} else {
|
||||
ids = bookOpdsRepository.findRandomBookIdsByLibraryIds(libraryIds);
|
||||
}
|
||||
if (ids.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(ids.stream().limit(count).toList());
|
||||
return books.stream().map(bookMapper::toBook).toList();
|
||||
}
|
||||
}
|
||||
|
||||
+89
-15
@@ -4,6 +4,8 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.Library;
|
||||
import com.adityachandel.booklore.model.dto.MagicShelf;
|
||||
import com.adityachandel.booklore.service.MagicShelfService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -23,6 +25,8 @@ public class OpdsFeedService {
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final OpdsBookService opdsBookService;
|
||||
private final MagicShelfService magicShelfService;
|
||||
private final MagicShelfBookService magicShelfBookService;
|
||||
|
||||
public String generateRootNavigation(HttpServletRequest request) {
|
||||
var feed = new StringBuilder("""
|
||||
@@ -76,6 +80,16 @@ public class OpdsFeedService {
|
||||
</entry>
|
||||
""".formatted(now()));
|
||||
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>Magic Shelves</title>
|
||||
<id>urn:booklore:navigation:magic-shelves</id>
|
||||
<updated>%s</updated>
|
||||
<link rel="subsection" href="/api/v1/opds/magic-shelves" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<content type="text">Browse your smart, dynamic shelves</content>
|
||||
</entry>
|
||||
""".formatted(now()));
|
||||
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>Surprise Me</title>
|
||||
@@ -91,8 +105,8 @@ public class OpdsFeedService {
|
||||
}
|
||||
|
||||
public String generateLibrariesNavigation(HttpServletRequest request) {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
List<Library> libraries = opdsBookService.getAccessibleLibraries(details);
|
||||
Long userId = getUserId();
|
||||
List<Library> libraries = opdsBookService.getAccessibleLibraries(userId);
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -128,7 +142,7 @@ public class OpdsFeedService {
|
||||
}
|
||||
|
||||
public String generateShelvesNavigation(HttpServletRequest request) {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
Long userId = getUserId();
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -141,8 +155,7 @@ public class OpdsFeedService {
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
|
||||
""".formatted(now()));
|
||||
|
||||
if (details != null && details.getOpdsUserV2() != null) {
|
||||
Long userId = details.getOpdsUserV2().getUserId();
|
||||
if (userId != null) {
|
||||
var shelves = opdsBookService.getUserShelves(userId);
|
||||
|
||||
if (shelves != null) {
|
||||
@@ -169,18 +182,66 @@ public class OpdsFeedService {
|
||||
return feed.toString();
|
||||
}
|
||||
|
||||
public String generateMagicShelvesNavigation(HttpServletRequest request) {
|
||||
Long userId = getUserId();
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:opds="http://opds-spec.org/2010/catalog">
|
||||
<id>urn:booklore:navigation:magic-shelves</id>
|
||||
<title>Magic Shelves</title>
|
||||
<updated>%s</updated>
|
||||
<link rel="self" href="/api/v1/opds/magic-shelves" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="start" href="/api/v1/opds" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
|
||||
""".formatted(now()));
|
||||
|
||||
if (userId != null) {
|
||||
var magicShelves = magicShelfService.getUserShelvesForOpds(userId);
|
||||
|
||||
if (magicShelves != null) {
|
||||
for (var shelf : magicShelves) {
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>%s</title>
|
||||
<id>urn:booklore:magic-shelf:%d</id>
|
||||
<updated>%s</updated>
|
||||
<link rel="subsection" href="%s" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
|
||||
<content type="text">Smart, dynamic shelf collection</content>
|
||||
</entry>
|
||||
""".formatted(
|
||||
escapeXml(shelf.getName()),
|
||||
shelf.getId(),
|
||||
now(),
|
||||
escapeXml("/api/v1/opds/catalog?magicShelfId=" + shelf.getId())
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
feed.append("</feed>");
|
||||
return feed.toString();
|
||||
}
|
||||
|
||||
public String generateCatalogFeed(HttpServletRequest request) {
|
||||
Long libraryId = parseLongParam(request, "libraryId", null);
|
||||
Long shelfId = parseLongParam(request, "shelfId", null);
|
||||
Long magicShelfId = parseLongParam(request, "magicShelfId", null);
|
||||
String query = request.getParameter("q");
|
||||
int page = Math.max(1, parseLongParam(request, "page", 1L).intValue());
|
||||
int size = Math.min(parseLongParam(request, "size", (long) DEFAULT_PAGE_SIZE).intValue(), MAX_PAGE_SIZE);
|
||||
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
Page<Book> booksPage = opdsBookService.getBooksPage(details, query, libraryId, shelfId, page - 1, size);
|
||||
Long userId = getUserId();
|
||||
Page<Book> booksPage;
|
||||
|
||||
String feedTitle = determineFeedTitle(libraryId, shelfId);
|
||||
String feedId = determineFeedId(libraryId, shelfId);
|
||||
if (magicShelfId != null) {
|
||||
booksPage = magicShelfBookService.getBooksByMagicShelfId(userId, magicShelfId, page - 1, size);
|
||||
} else {
|
||||
booksPage = opdsBookService.getBooksPage(userId, query, libraryId, shelfId, page - 1, size);
|
||||
}
|
||||
|
||||
String feedTitle = determineFeedTitle(libraryId, shelfId, magicShelfId);
|
||||
String feedId = determineFeedId(libraryId, shelfId, magicShelfId);
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -213,11 +274,11 @@ public class OpdsFeedService {
|
||||
}
|
||||
|
||||
public String generateRecentFeed(HttpServletRequest request) {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
Long userId = getUserId();
|
||||
int page = Math.max(1, parseLongParam(request, "page", 1L).intValue());
|
||||
int size = Math.min(parseLongParam(request, "size", (long) DEFAULT_PAGE_SIZE).intValue(), MAX_PAGE_SIZE);
|
||||
|
||||
Page<Book> booksPage = opdsBookService.getRecentBooksPage(details, page - 1, size);
|
||||
Page<Book> booksPage = opdsBookService.getRecentBooksPage(userId, page - 1, size);
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -242,9 +303,9 @@ public class OpdsFeedService {
|
||||
}
|
||||
|
||||
public String generateSurpriseFeed(HttpServletRequest request) {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
Long userId = getUserId();
|
||||
int count = 25;
|
||||
List<Book> books = opdsBookService.getRandomBooks(details, count);
|
||||
List<Book> books = opdsBookService.getRandomBooks(userId, count);
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -382,7 +443,10 @@ public class OpdsFeedService {
|
||||
}
|
||||
}
|
||||
|
||||
private String determineFeedTitle(Long libraryId, Long shelfId) {
|
||||
private String determineFeedTitle(Long libraryId, Long shelfId, Long magicShelfId) {
|
||||
if (magicShelfId != null) {
|
||||
return magicShelfBookService.getMagicShelfName(magicShelfId);
|
||||
}
|
||||
if (shelfId != null) {
|
||||
return opdsBookService.getShelfName(shelfId);
|
||||
}
|
||||
@@ -392,7 +456,10 @@ public class OpdsFeedService {
|
||||
return "Booklore Catalog";
|
||||
}
|
||||
|
||||
private String determineFeedId(Long libraryId, Long shelfId) {
|
||||
private String determineFeedId(Long libraryId, Long shelfId, Long magicShelfId) {
|
||||
if (magicShelfId != null) {
|
||||
return "urn:booklore:magic-shelf:" + magicShelfId;
|
||||
}
|
||||
if (shelfId != null) {
|
||||
return "urn:booklore:shelf:" + shelfId;
|
||||
}
|
||||
@@ -435,4 +502,11 @@ public class OpdsFeedService {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
private Long getUserId() {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
return details != null && details.getOpdsUserV2() != null
|
||||
? details.getOpdsUserV2().getUserId()
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user