Merge pull request #1830 from booklore-app/develop

Merge develop into master for release
This commit is contained in:
Aditya Chandel
2025-12-12 08:45:48 -07:00
committed by GitHub
291 changed files with 14237 additions and 2819 deletions
+3 -1
View File
@@ -41,4 +41,6 @@ out/
.vscode/
local/
booklore-api/src/main/resources/application-local.yaml
### Dev config, books, and data ###
booklore-api/src/main/resources/application-local.yaml
/shared/
+22 -9
View File
@@ -41,10 +41,24 @@ cd booklore
## 🧱 Local Development Setup
Either run `docker compose -f dev.docker-compose.yml up` or install & run everything Locally (described below).
Booklore has a simple all-in-one Docker development stack, or you can install & run everything manually.
### 1. Prerequisites
### Development using Docker stack
Run `docker compose -f dev.docker-compose.yml up`
- Dev web server is accessible at `http://localhost:4200/`
- Dev database is accessible at `http://localhost:3366/`
- Remote java debugging is accessible at `http://localhost:5005/`
All ports are configurable using environment variables - see dev.docker-compose.yml
---
### Development on local machine
#### 1. Prerequisites
- **Java 21+**
- **Node.js 18+**
@@ -53,7 +67,7 @@ Either run `docker compose -f dev.docker-compose.yml up` or install & run every
---
### 2. Frontend Setup
#### 2. Frontend Setup
To set up the Angular frontend:
@@ -69,9 +83,9 @@ The dev server runs at `http://localhost:4200/`.
---
### 3. Backend Setup
#### 3. Backend Setup
#### a. Configure `application-dev.yml`
##### a. Configure `application-dev.yml`
Create or edit `booklore-api/src/main/resources/application-dev.yml`:
@@ -90,7 +104,7 @@ spring:
> 🔧 Replace `/path/to/...` with actual local paths
#### b. Run the Backend
##### b. Run the Backend
```bash
cd booklore-api
@@ -183,15 +197,14 @@ Please be respectful, inclusive, and collaborative. Harassment, abuse, or discri
## 💬 Community & Support
- Use [GitHub Discussions](https://github.com/adityachandelgit/BookLore/discussions)
- Discord server: https://discord.gg/Ee5hd458Uz
---
## 📄 License
Booklore is open-source and licensed under the MIT License. See [`LICENSE`](./LICENSE) for details.
Booklore is open-source and licensed under the GPL-3.0 License. See [`LICENSE`](./LICENSE) for details.
---
Happy contributing!
Happy contributing!
+7
View File
@@ -72,6 +72,7 @@ dependencies {
// --- API Documentation ---
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.14'
implementation 'org.apache.commons:commons-compress:1.28.0'
implementation 'org.tukaani:xz:1.11' // Required by commons-compress for 7z support
implementation 'org.apache.commons:commons-text:1.14.0'
// --- Template Engine ---
@@ -94,3 +95,9 @@ test {
jvmArgs("-XX:+EnableDynamicAgentLoading")
}
bootRun {
def debug = System.getenv('REMOTE_DEBUG_ENABLED')
if (debug.equals("true")) {
jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005")
}
}
@@ -27,6 +27,7 @@ public class AppProperties {
private String headerEmail;
private String headerGroups;
private String adminGroup;
private String groupsDelimiter = "\\s+"; // Default to whitespace for backward compatibility
}
@Getter
@@ -6,6 +6,7 @@ import com.adityachandel.booklore.config.security.filter.DualJwtAuthenticationFi
import com.adityachandel.booklore.config.security.filter.KoboAuthFilter;
import com.adityachandel.booklore.config.security.filter.KoreaderAuthFilter;
import com.adityachandel.booklore.config.security.service.OpdsUserDetailsService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -29,8 +30,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
@AllArgsConstructor
@EnableMethodSecurity
@Configuration
@@ -141,7 +141,7 @@ public class DualJwtAuthenticationFilter extends OncePerRequestFilter {
} catch (Exception e) {
log.error("OIDC authentication failed", e);
throw ApiError.GENERIC_UNAUTHORIZED.createException("OIDC JWT validation failed");
throw ApiError.GENERIC_UNAUTHORIZED.createException("OIDC JWT validation failed: " + e.getMessage());
}
}
@@ -3,19 +3,25 @@ package com.adityachandel.booklore.config.security.service;
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.source.DefaultJWKSetCache;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.jwk.source.JWKSourceBuilder;
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jose.util.DefaultResourceRetriever;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import java.net.URI;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
@@ -42,19 +48,25 @@ public class DynamicOidcJwtProcessor {
throw new IllegalStateException("OIDC issuer URI is not configured in app settings.");
}
String discoveryUri = providerDetails.getIssuerUri() + "/.well-known/openid-configuration";
String discoveryUri = providerDetails.getIssuerUri().replaceAll("/$", "") + "/.well-known/openid-configuration";
log.info("Fetching OIDC discovery document from {}", discoveryUri);
URI jwksUri = fetchJwksUri(discoveryUri);
Duration ttl = Duration.ofHours(6);
Duration refresh = Duration.ofHours(1);
JWKSource<SecurityContext> jwkSource = JWKSourceBuilder.create(jwksUri.toURL())
.cache(ttl.toMillis(), refresh.toMillis())
.build();
JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource);
DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(10000, 10000);
DefaultJWKSetCache jwkSetCache = new DefaultJWKSetCache(ttl.toMillis(), refresh.toMillis(), TimeUnit.MILLISECONDS);
JWKSource<SecurityContext> jwkSource = new RemoteJWKSet<>(jwksUri.toURL(), resourceRetriever, jwkSetCache);
Set<JWSAlgorithm> jwsAlgs = new HashSet<>();
jwsAlgs.addAll(JWSAlgorithm.Family.RSA);
jwsAlgs.addAll(JWSAlgorithm.Family.EC);
jwsAlgs.addAll(JWSAlgorithm.Family.RSA);
JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(jwsAlgs, jwkSource);
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
jwtProcessor.setJWSKeySelector(keySelector);
@@ -62,7 +74,14 @@ public class DynamicOidcJwtProcessor {
}
private URI fetchJwksUri(String discoveryUri) throws Exception {
var restClient = org.springframework.web.client.RestClient.create();
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(10000);
factory.setReadTimeout(10000);
var restClient = org.springframework.web.client.RestClient.builder()
.requestFactory(factory)
.build();
var discoveryDoc = restClient.get()
.uri(discoveryUri)
.retrieve()
@@ -46,7 +46,7 @@ public class AdditionalFileController {
@PathVariable Long bookId,
@RequestParam("file") MultipartFile file,
@RequestParam AdditionalFileType additionalFileType,
@RequestParam(required = false) String description) throws IOException {
@RequestParam(required = false) String description) {
AdditionalFile additionalFile = fileUploadService.uploadAdditionalFile(bookId, file, additionalFileType, description);
return ResponseEntity.ok(additionalFile);
}
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookRecommendation;
import com.adityachandel.booklore.model.dto.BookViewerSettings;
import com.adityachandel.booklore.model.dto.request.PersonalRatingUpdateRequest;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.dto.request.ReadStatusUpdateRequest;
import com.adityachandel.booklore.model.dto.request.ShelvesAssignmentRequest;
@@ -186,4 +187,28 @@ public class BookController {
List<Book> updatedBooks = bookService.resetProgress(bookIds, type);
return ResponseEntity.ok(updatedBooks);
}
@Operation(summary = "Update personal rating", description = "Update the personal rating for one or more books.")
@ApiResponse(responseCode = "200", description = "Personal rating updated successfully")
@PutMapping("/personal-rating")
public ResponseEntity<List<Book>> updatePersonalRating(
@Parameter(description = "Personal rating update request") @RequestBody @Valid PersonalRatingUpdateRequest request) {
List<Book> updatedBooks = bookService.updatePersonalRating(request.ids(), request.rating());
return ResponseEntity.ok(updatedBooks);
}
@Operation(summary = "Reset personal rating", description = "Reset the personal rating for one or more books.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Personal rating reset successfully"),
@ApiResponse(responseCode = "400", description = "No book IDs provided")
})
@PostMapping("/reset-personal-rating")
public ResponseEntity<List<Book>> resetPersonalRating(
@Parameter(description = "List of book IDs to reset personal rating for") @RequestBody List<Long> bookIds) {
if (bookIds == null || bookIds.isEmpty()) {
throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided");
}
List<Book> updatedBooks = bookService.resetPersonalRating(bookIds);
return ResponseEntity.ok(updatedBooks);
}
}
@@ -0,0 +1,49 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.BookMark;
import com.adityachandel.booklore.model.dto.CreateBookMarkRequest;
import com.adityachandel.booklore.service.book.BookMarkService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/bookmarks")
@Tag(name = "Bookmarks", description = "Endpoints for managing book bookmarks")
public class BookMarkController {
private final BookMarkService bookMarkService;
@Operation(summary = "Get bookmarks for a book", description = "Retrieve all bookmarks for a specific book.")
@ApiResponse(responseCode = "200", description = "Bookmarks returned successfully")
@GetMapping("/book/{bookId}")
public List<BookMark> getBookmarksForBook(
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return bookMarkService.getBookmarksForBook(bookId);
}
@Operation(summary = "Create a bookmark", description = "Create a new bookmark for a book.")
@ApiResponse(responseCode = "200", description = "Bookmark created successfully")
@PostMapping
public BookMark createBookmark(
@Parameter(description = "Bookmark creation request") @Valid @RequestBody CreateBookMarkRequest request) {
return bookMarkService.createBookmark(request);
}
@Operation(summary = "Delete a bookmark", description = "Delete a specific bookmark by its ID.")
@ApiResponse(responseCode = "204", description = "Bookmark deleted successfully")
@DeleteMapping("/{bookmarkId}")
public ResponseEntity<Void> deleteBookmark(
@Parameter(description = "ID of the bookmark to delete") @PathVariable Long bookmarkId) {
bookMarkService.deleteBookmark(bookmarkId);
return ResponseEntity.noContent().build();
}
}
@@ -4,6 +4,7 @@ import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.bookdrop.BookDropService;
import com.adityachandel.booklore.service.reader.CbxReaderService;
import com.adityachandel.booklore.service.reader.PdfReaderService;
import com.adityachandel.booklore.service.IconService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@@ -36,6 +37,7 @@ public class BookMediaController {
private final PdfReaderService pdfReaderService;
private final CbxReaderService cbxReaderService;
private final BookDropService bookDropService;
private final IconService iconService;
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book thumbnail returned successfully")
@@ -0,0 +1,68 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.request.SvgIconBatchRequest;
import com.adityachandel.booklore.model.dto.request.SvgIconCreateRequest;
import com.adityachandel.booklore.model.dto.response.SvgIconBatchResponse;
import com.adityachandel.booklore.service.IconService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@Tag(name = "Icons", description = "Endpoints for managing SVG icons")
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/icons")
public class IconController {
private final IconService iconService;
@Operation(summary = "Save an SVG icon", description = "Saves an SVG icon to the system.")
@ApiResponse(responseCode = "200", description = "SVG icon saved successfully")
@PostMapping
public ResponseEntity<?> saveSvgIcon(@Valid @RequestBody SvgIconCreateRequest svgIconCreateRequest) {
iconService.saveSvgIcon(svgIconCreateRequest);
return ResponseEntity.ok().build();
}
@Operation(summary = "Save multiple SVG icons", description = "Saves multiple SVG icons to the system in batch.")
@ApiResponse(responseCode = "200", description = "Batch save completed with detailed results")
@PostMapping("/batch")
public ResponseEntity<SvgIconBatchResponse> saveBatchSvgIcons(@Valid @RequestBody SvgIconBatchRequest request) {
SvgIconBatchResponse response = iconService.saveBatchSvgIcons(request.getIcons());
return ResponseEntity.ok(response);
}
@Operation(summary = "Get SVG icon content", description = "Retrieve the SVG content of an icon by its name.")
@ApiResponse(responseCode = "200", description = "SVG icon content retrieved successfully")
@GetMapping("/{svgName}/content")
public ResponseEntity<String> getSvgIconContent(@Parameter(description = "SVG icon name") @PathVariable String svgName) {
String svgContent = iconService.getSvgIcon(svgName);
return ResponseEntity.ok()
.header("Content-Type", "image/svg+xml")
.body(svgContent);
}
@Operation(summary = "Get paginated icon names", description = "Retrieve a paginated list of icon names (default 50 per page).")
@ApiResponse(responseCode = "200", description = "Icon names retrieved successfully")
@GetMapping
public ResponseEntity<Page<String>> getIconNames(
@Parameter(description = "Page number") @RequestParam(defaultValue = "0") int page,
@Parameter(description = "Page size") @RequestParam(defaultValue = "50") int size) {
Page<String> response = iconService.getIconNames(page, size);
return ResponseEntity.ok(response);
}
@Operation(summary = "Delete an SVG icon", description = "Deletes an SVG icon by its name.")
@ApiResponse(responseCode = "200", description = "SVG icon deleted successfully")
@DeleteMapping("/{svgName}")
public ResponseEntity<?> deleteSvgIcon(@Parameter(description = "SVG icon name") @PathVariable String svgName) {
iconService.deleteSvgIcon(svgName);
return ResponseEntity.ok().build();
}
}
@@ -3,7 +3,6 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.KoboSyncSettings;
import com.adityachandel.booklore.service.kobo.KoboSettingsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
@@ -31,31 +30,19 @@ public class KoboSettingsController {
@Operation(summary = "Create or update Kobo token", description = "Create or update the Kobo sync token for the current user. Requires sync permission or admin.")
@ApiResponse(responseCode = "200", description = "Token created/updated successfully")
@PutMapping
@PutMapping("/token")
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<KoboSyncSettings> createOrUpdateToken() {
KoboSyncSettings updated = koboService.createOrUpdateToken();
return ResponseEntity.ok(updated);
}
@Operation(summary = "Toggle Kobo sync", description = "Enable or disable Kobo sync for the current user. Requires sync permission or admin.")
@ApiResponse(responseCode = "204", description = "Sync toggled successfully")
@PutMapping("/sync")
@Operation(summary = "Update Kobo settings", description = "Update Kobo sync settings for the current user. Requires sync permission or admin.")
@ApiResponse(responseCode = "200", description = "Settings updated successfully")
@PutMapping
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<Void> toggleSync(
@Parameter(description = "Enable or disable sync") @RequestParam boolean enabled) {
koboService.setSyncEnabled(enabled);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Update progress thresholds", description = "Update the progress thresholds for marking books as reading or finished. Requires sync permission or admin.")
@ApiResponse(responseCode = "200", description = "Thresholds updated successfully")
@PutMapping("/progress-thresholds")
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<KoboSyncSettings> updateProgressThresholds(
@Parameter(description = "Progress percentage to mark as reading (0-100)") @RequestParam(required = false) Float readingThreshold,
@Parameter(description = "Progress percentage to mark as finished (0-100)") @RequestParam(required = false) Float finishedThreshold) {
KoboSyncSettings updated = koboService.updateProgressThresholds(readingThreshold, finishedThreshold);
public ResponseEntity<KoboSyncSettings> updateSettings(@RequestBody KoboSyncSettings settings) {
KoboSyncSettings updated = koboService.updateSettings(settings);
return ResponseEntity.ok(updated);
}
}
@@ -13,6 +13,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -35,8 +36,8 @@ public class LibraryController {
@Operation(summary = "Get a library by ID", description = "Retrieve details of a specific library by its ID.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Library details returned successfully"),
@ApiResponse(responseCode = "404", description = "Library not found")
@ApiResponse(responseCode = "200", description = "Library details returned successfully"),
@ApiResponse(responseCode = "404", description = "Library not found")
})
@GetMapping("/{libraryId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
@@ -50,7 +51,7 @@ public class LibraryController {
@PostMapping
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<Library> createLibrary(
@Parameter(description = "Library creation request") @RequestBody CreateLibraryRequest request) {
@Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) {
return ResponseEntity.ok(libraryService.createLibrary(request));
}
@@ -60,7 +61,7 @@ public class LibraryController {
@CheckLibraryAccess(libraryIdParam = "libraryId")
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<Library> updateLibrary(
@Parameter(description = "Library update request") @RequestBody CreateLibraryRequest request,
@Parameter(description = "Library update request") @Validated @RequestBody CreateLibraryRequest request,
@Parameter(description = "ID of the library") @PathVariable Long libraryId) {
return ResponseEntity.ok(libraryService.updateLibrary(request, libraryId));
}
@@ -72,8 +72,8 @@ public class MetadataController {
.updateThumbnail(true)
.mergeCategories(mergeCategories)
.replaceMode(MetadataReplaceMode.REPLACE_ALL)
.mergeMoods(true)
.mergeTags(true)
.mergeMoods(false)
.mergeTags(false)
.build();
bookMetadataUpdater.setBookMetadata(context);
@@ -0,0 +1,305 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.exception.APIException;
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
import com.adityachandel.booklore.model.dto.settings.OidcAutoProvisionDetails;
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.user.UserProvisioningService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
/**
* Controller for handling OIDC authentication for mobile applications.
*
* Mobile apps cannot use the standard web-based OIDC callback because they need
* to receive tokens via a custom URL scheme (e.g., booknexus://callback).
*
* This controller provides endpoints that:
* 1. Accept the OIDC authorization code from the mobile app
* 2. Exchange it for OIDC tokens with the identity provider
* 3. Validate the tokens and provision/authenticate the user
* 4. Return Booklore JWT tokens to the mobile app
*/
@Tag(name = "Mobile OIDC", description = "Endpoints for mobile app OIDC authentication")
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/api/v1/auth/mobile")
public class MobileOidcController {
private static final Pattern TRAILING_SLASHES_PATTERN = Pattern.compile("/+$");
private final AppSettingService appSettingService;
private final UserRepository userRepository;
private final UserProvisioningService userProvisioningService;
private final AuthenticationService authenticationService;
private final BookLoreUserTransformer bookLoreUserTransformer;
private final ObjectMapper objectMapper;
private static final ConcurrentMap<String, Object> userLocks = new ConcurrentHashMap<>();
@Operation(
summary = "Exchange OIDC authorization code for tokens",
description = "Exchanges an OIDC authorization code for Booklore JWT tokens. " +
"The mobile app should call this endpoint after receiving the authorization code " +
"from the OIDC provider. This endpoint will exchange the code for OIDC tokens, " +
"validate them, provision the user if needed, and return Booklore JWT tokens."
)
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Tokens issued successfully"),
@ApiResponse(responseCode = "400", description = "Invalid request or OIDC error"),
@ApiResponse(responseCode = "401", description = "Authentication failed"),
@ApiResponse(responseCode = "403", description = "OIDC is not enabled")
})
@PostMapping("/oidc/callback")
public ResponseEntity<Map<String, String>> handleOidcCallback(
@Parameter(description = "Authorization code from OIDC provider")
@RequestParam("code") String code,
@Parameter(description = "PKCE code verifier used when initiating the auth request")
@RequestParam("code_verifier") String codeVerifier,
@Parameter(description = "Redirect URI that was used in the authorization request")
@RequestParam("redirect_uri") String redirectUri) {
log.info("Mobile OIDC callback received");
// Verify OIDC is enabled
if (!appSettingService.getAppSettings().isOidcEnabled()) {
throw ApiError.FORBIDDEN.createException("OIDC is not enabled on this server");
}
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
if (providerDetails == null || providerDetails.getIssuerUri() == null) {
throw ApiError.FORBIDDEN.createException("OIDC is not properly configured");
}
try {
// Discover token endpoint
String tokenEndpoint = discoverTokenEndpoint(providerDetails.getIssuerUri());
// Exchange authorization code for tokens
Map<String, Object> tokenResponse = exchangeCodeForTokens(
tokenEndpoint,
code,
codeVerifier,
redirectUri,
providerDetails.getClientId()
);
// Extract and validate ID token
String idToken = (String) tokenResponse.get("id_token");
if (idToken == null) {
// Some providers may only return access_token, try to use that
idToken = (String) tokenResponse.get("access_token");
}
if (idToken == null) {
throw ApiError.GENERIC_UNAUTHORIZED.createException("No token received from OIDC provider");
}
// Parse the JWT to extract claims
SignedJWT signedJWT = SignedJWT.parse(idToken);
JWTClaimsSet claims = signedJWT.getJWTClaimsSet();
// Extract user information using claim mappings
OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping();
String username = claims.getStringClaim(claimMapping.getUsername());
String email = claims.getStringClaim(claimMapping.getEmail());
String name = claims.getStringClaim(claimMapping.getName());
if (username == null || username.isEmpty()) {
// Fall back to email or subject if username claim is not available
username = email != null ? email : claims.getSubject();
}
log.info("Mobile OIDC: Authenticating user '{}'", username);
// Find or provision user
BookLoreUserEntity userEntity = findOrProvisionUser(username, email, name);
// Generate Booklore JWT tokens
return authenticationService.loginUser(userEntity);
} catch (APIException e) {
throw e;
} catch (Exception e) {
log.error("Mobile OIDC authentication failed", e);
throw ApiError.GENERIC_UNAUTHORIZED.createException("OIDC authentication failed: " + e.getMessage());
}
}
@Operation(
summary = "Mobile OIDC redirect callback",
description = "Alternative endpoint that redirects to a mobile app URL scheme with tokens. " +
"Use this if your mobile app prefers to receive tokens via URL redirect rather than API response."
)
@ApiResponses({
@ApiResponse(responseCode = "302", description = "Redirect to mobile app with tokens"),
@ApiResponse(responseCode = "400", description = "Invalid request or OIDC error"),
@ApiResponse(responseCode = "403", description = "OIDC is not enabled")
})
@GetMapping("/oidc/redirect")
public ResponseEntity<Void> handleOidcRedirect(
@Parameter(description = "Authorization code from OIDC provider")
@RequestParam("code") String code,
@Parameter(description = "PKCE code verifier used when initiating the auth request")
@RequestParam("code_verifier") String codeVerifier,
@Parameter(description = "Redirect URI that was used in the authorization request")
@RequestParam("redirect_uri") String redirectUri,
@Parameter(description = "Mobile app URL scheme to redirect to (e.g., booknexus://callback)")
@RequestParam("app_redirect_uri") String appRedirectUri) {
try {
// Use the callback handler to get tokens
ResponseEntity<Map<String, String>> tokenResponse = handleOidcCallback(code, codeVerifier, redirectUri);
Map<String, String> tokens = tokenResponse.getBody();
if (tokens == null) {
throw ApiError.GENERIC_UNAUTHORIZED.createException("Failed to obtain tokens");
}
// Build redirect URL with tokens as query parameters
StringBuilder redirectUrl = new StringBuilder(appRedirectUri);
redirectUrl.append(appRedirectUri.contains("?") ? "&" : "?");
redirectUrl.append("access_token=").append(URLEncoder.encode(tokens.get("accessToken"), StandardCharsets.UTF_8));
redirectUrl.append("&refresh_token=").append(URLEncoder.encode(tokens.get("refreshToken"), StandardCharsets.UTF_8));
if (tokens.containsKey("isDefaultPassword")) {
redirectUrl.append("&is_default_password=").append(URLEncoder.encode(tokens.get("isDefaultPassword"), StandardCharsets.UTF_8));
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(redirectUrl.toString()));
log.info("Mobile OIDC: Redirecting to app with tokens");
return new ResponseEntity<>(headers, HttpStatus.FOUND);
} catch (APIException e) {
// Redirect to app with error
String errorRedirect = appRedirectUri +
(appRedirectUri.contains("?") ? "&" : "?") +
"error=" + URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(errorRedirect));
return new ResponseEntity<>(headers, HttpStatus.FOUND);
}
}
/**
* Discover the token endpoint from the OIDC provider's well-known configuration.
*/
private String discoverTokenEndpoint(String issuerUri) throws Exception {
String discoveryUrl = TRAILING_SLASHES_PATTERN.matcher(issuerUri).replaceAll("") + "/.well-known/openid-configuration";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity(discoveryUrl, String.class);
if (!response.getStatusCode().is2xxSuccessful() || response.getBody() == null) {
throw new RuntimeException("Failed to fetch OIDC discovery document");
}
JsonNode discoveryDoc = objectMapper.readTree(response.getBody());
JsonNode tokenEndpointNode = discoveryDoc.get("token_endpoint");
if (tokenEndpointNode == null || tokenEndpointNode.isNull()) {
// Fall back to standard path
return TRAILING_SLASHES_PATTERN.matcher(issuerUri).replaceAll("") + "/protocol/openid-connect/token";
}
return tokenEndpointNode.asText();
}
/**
* Exchange the authorization code for tokens with the OIDC provider.
*/
private Map<String, Object> exchangeCodeForTokens(
String tokenEndpoint,
String code,
String codeVerifier,
String redirectUri,
String clientId) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("grant_type", "authorization_code");
body.add("client_id", clientId);
body.add("code", code);
body.add("redirect_uri", redirectUri);
body.add("code_verifier", codeVerifier);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);
try {
ResponseEntity<String> response = restTemplate.postForEntity(tokenEndpoint, request, String.class);
if (!response.getStatusCode().is2xxSuccessful() || response.getBody() == null) {
throw new RuntimeException("Token exchange failed with status: " + response.getStatusCode());
}
return objectMapper.readValue(response.getBody(), Map.class);
} catch (Exception e) {
log.error("Token exchange failed: {}", e.getMessage());
throw new RuntimeException("Failed to exchange authorization code: " + e.getMessage(), e);
}
}
/**
* Find existing user or provision a new one based on OIDC claims.
*/
private BookLoreUserEntity findOrProvisionUser(String username, String email, String name) {
OidcAutoProvisionDetails provisionDetails = appSettingService.getAppSettings().getOidcAutoProvisionDetails();
boolean autoProvision = provisionDetails != null && provisionDetails.isEnableAutoProvisioning();
return userRepository.findByUsername(username)
.orElseGet(() -> {
if (!autoProvision) {
log.warn("User '{}' not found and auto-provisioning is disabled.", username);
throw ApiError.GENERIC_UNAUTHORIZED.createException("User not found and auto-provisioning is disabled.");
}
Object lock = userLocks.computeIfAbsent(username, k -> new Object());
try {
synchronized (lock) {
return userRepository.findByUsername(username)
.orElseGet(() -> {
log.info("Mobile OIDC: Provisioning new user '{}'", username);
return userProvisioningService.provisionOidcUser(username, email, name, provisionDetails);
});
}
} finally {
userLocks.remove(username);
}
});
}
}
@@ -97,6 +97,16 @@ public class OpdsController {
.body(feed);
}
@Operation(summary = "Get OPDS authors navigation", description = "Retrieve the OPDS authors navigation feed.")
@ApiResponse(responseCode = "200", description = "Authors navigation feed returned successfully")
@GetMapping(value = "/authors", produces = OPDS_CATALOG_MEDIA_TYPE)
public ResponseEntity<String> getAuthorsNavigation(@Parameter(hidden = true) HttpServletRequest request) {
String feed = opdsFeedService.generateAuthorsNavigation(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)
@@ -54,7 +54,8 @@ public enum ApiError {
FILE_NOT_FOUND(HttpStatus.NOT_FOUND, "File not found: %s"),
SHELF_CANNOT_BE_DELETED(HttpStatus.FORBIDDEN, "'%s' shelf can't be deleted" ),
TASK_NOT_FOUND(HttpStatus.NOT_FOUND, "Scheduled task not found: %s"),
TASK_ALREADY_RUNNING(HttpStatus.CONFLICT, "Task is already running: %s"),;
TASK_ALREADY_RUNNING(HttpStatus.CONFLICT, "Task is already running: %s"),
ICON_ALREADY_EXISTS(HttpStatus.CONFLICT, "SVG icon with name '%s' already exists"),;
private final HttpStatus status;
private final String message;
@@ -0,0 +1,11 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.BookMark;
import com.adityachandel.booklore.model.entity.BookMarkEntity;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@Mapper(componentModel = "spring")
public interface BookMarkMapper {
BookMark toDto(BookMarkEntity entity);
}
@@ -61,14 +61,17 @@ public class BookLoreUserTransformer {
case NEW_PDF_READER_SETTING -> userSettings.setNewPdfReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.NewPdfReaderSetting.class));
case SIDEBAR_LIBRARY_SORTING -> userSettings.setSidebarLibrarySorting(objectMapper.readValue(value, SidebarSortOption.class));
case SIDEBAR_SHELF_SORTING -> userSettings.setSidebarShelfSorting(objectMapper.readValue(value, SidebarSortOption.class));
case SIDEBAR_MAGIC_SHELF_SORTING -> userSettings.setSidebarMagicShelfSorting(objectMapper.readValue(value, SidebarSortOption.class));
case ENTITY_VIEW_PREFERENCES -> userSettings.setEntityViewPreferences(objectMapper.readValue(value, BookLoreUser.UserSettings.EntityViewPreferences.class));
case TABLE_COLUMN_PREFERENCE -> userSettings.setTableColumnPreference(objectMapper.readValue(value, new TypeReference<>() {}));
case DASHBOARD_CONFIG -> userSettings.setDashboardConfig(objectMapper.readValue(value, BookLoreUser.UserSettings.DashboardConfig.class));
}
} else {
switch (settingKey) {
case FILTER_MODE -> userSettings.setFilterMode(value);
case FILTER_SORTING_MODE -> userSettings.setFilterSortingMode(value);
case METADATA_CENTER_VIEW_MODE -> userSettings.setMetadataCenterViewMode(value);
case ENABLE_SERIES_VIEW -> userSettings.setEnableSeriesView(Boolean.parseBoolean(value));
}
}
} catch (IllegalArgumentException e) {
@@ -28,7 +28,6 @@ public class MetadataClearFlags {
private boolean goodreadsReviewCount;
private boolean hardcoverRating;
private boolean hardcoverReviewCount;
private boolean personalRating;
private boolean authors;
private boolean categories;
private boolean moods;
@@ -32,6 +32,7 @@ public class Book {
private CbxProgress cbxProgress;
private KoProgress koreaderProgress;
private KoboProgress koboProgress;
private Integer personalRating;
private Set<Shelf> shelves;
private String readStatus;
private Instant dateFinished;
@@ -47,11 +47,14 @@ public class BookLoreUser {
public CbxReaderSetting cbxReaderSetting;
public SidebarSortOption sidebarLibrarySorting;
public SidebarSortOption sidebarShelfSorting;
public SidebarSortOption sidebarMagicShelfSorting;
public EntityViewPreferences entityViewPreferences;
public List<TableColumnPreference> tableColumnPreference;
public String filterMode;
public String filterSortingMode;
public String metadataCenterViewMode;
public boolean koReaderEnabled;
public boolean enableSeriesView;
public DashboardConfig dashboardConfig;
@Data
@@ -0,0 +1,20 @@
package com.adityachandel.booklore.model.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BookMark {
private Long id;
private Long bookId;
private String cfi;
private String title;
private LocalDateTime createdAt;
}
@@ -29,7 +29,6 @@ public class BookMetadata {
private String isbn10;
private Integer pageCount;
private String language;
private Double rating;
private String asin;
private Double amazonRating;
private Integer amazonReviewCount;
@@ -43,7 +42,6 @@ public class BookMetadata {
private String doubanId;
private Double doubanRating;
private Integer doubanReviewCount;
private Double personalRating;
private String googleId;
private Instant coverUpdatedOn;
private Set<String> authors;
@@ -72,7 +70,6 @@ public class BookMetadata {
private Boolean googleIdLocked;
private Boolean pageCountLocked;
private Boolean languageLocked;
private Boolean personalRatingLocked;
private Boolean amazonRatingLocked;
private Boolean amazonReviewCountLocked;
private Boolean goodreadsRatingLocked;
@@ -0,0 +1,20 @@
package com.adityachandel.booklore.model.dto;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CreateBookMarkRequest {
@NotNull
private Long bookId;
@NotEmpty
private String cfi;
private String title;
}
@@ -31,7 +31,6 @@ public class EpubMetadata {
private Integer pageCount;
private String language;
private String asin;
private Double personalRating;
private Double amazonRating;
private Integer amazonReviewCount;
private String goodreadsId;
@@ -11,4 +11,5 @@ public class KoboSyncSettings {
private boolean syncEnabled;
private Float progressMarkAsReadingThreshold;
private Float progressMarkAsFinishedThreshold;
private boolean autoAddToShelf;
}
@@ -1,6 +1,7 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.IconType;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
@@ -16,6 +17,7 @@ public class Library {
private String name;
private Sort sort;
private String icon;
private IconType iconType;
private String fileNamingPattern;
private boolean watch;
private List<LibraryPath> paths;
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.enums.IconType;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
@@ -18,6 +19,8 @@ public class MagicShelf {
@Size(max = 64, message = "Icon must not exceed 64 characters")
private String icon;
private IconType iconType;
@NotNull(message = "Filter JSON must not be null")
@Size(min = 2, message = "Filter JSON must not be empty")
private String filterJson;
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.enums.IconType;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
@@ -11,6 +12,7 @@ public class Shelf {
private Long id;
private String name;
private String icon;
private IconType iconType;
private Sort sort;
private Long userId;
}
@@ -52,5 +52,6 @@ public class BookEntitlement {
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class ActivePeriod {
private String from;
private String to;
}
}
@@ -2,10 +2,12 @@ package com.adityachandel.booklore.model.dto.request;
import com.adityachandel.booklore.model.dto.LibraryPath;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.IconType;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Data;
@@ -15,12 +17,18 @@ import java.util.List;
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public class CreateLibraryRequest {
@NotBlank
@NotBlank(message = "Library name must not be empty.")
private String name;
@NotBlank
@NotBlank(message = "Library icon must not be empty.")
private String icon;
@NotEmpty
@NotNull(message = "Library icon type must not be null.")
private IconType iconType;
@NotEmpty(message = "Library paths must not be empty.")
private List<LibraryPath> paths;
private boolean watch;
private LibraryScanMode scanMode;
private BookFileType defaultBookFormat;
@@ -0,0 +1,6 @@
package com.adityachandel.booklore.model.dto.request;
import java.util.List;
public record PersonalRatingUpdateRequest(List<Long> ids, Integer rating) {
}
@@ -1,6 +1,8 @@
package com.adityachandel.booklore.model.dto.request;
import com.adityachandel.booklore.model.enums.IconType;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import lombok.Builder;
import lombok.Data;
@@ -8,7 +10,6 @@ import lombok.Data;
@Builder
@Data
public class ShelfCreateRequest {
@Null(message = "Id should be null for creation.")
private Long id;
@@ -17,4 +18,7 @@ public class ShelfCreateRequest {
@NotBlank(message = "Shelf icon must not be empty.")
private String icon;
@NotNull(message = "Shelf icon type must not be null.")
private IconType iconType;
}
@@ -0,0 +1,20 @@
package com.adityachandel.booklore.model.dto.request;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SvgIconBatchRequest {
@NotEmpty(message = "Icons list cannot be empty")
@Valid
private List<SvgIconCreateRequest> icons;
}
@@ -0,0 +1,18 @@
package com.adityachandel.booklore.model.dto.request;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
public class SvgIconCreateRequest {
@NotBlank(message = "SVG name is required")
@Size(min = 1, max = 255, message = "SVG name must be between 1 and 255 characters")
@Pattern(regexp = "^[a-zA-Z0-9-]+$", message = "SVG name can only contain alphanumeric characters and hyphens")
private String svgName;
@NotBlank(message = "SVG data is required")
@Size(max = 1048576, message = "SVG data must not exceed 1MB")
private String svgData;
}
@@ -0,0 +1,30 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SvgIconBatchResponse {
private int totalRequested;
private int successCount;
private int failureCount;
private List<IconSaveResult> results;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class IconSaveResult {
private String iconName;
private boolean success;
private String errorMessage;
}
}
@@ -11,12 +11,14 @@ public enum UserSettingKey {
CBX_READER_SETTING("cbxReaderSetting", true),
SIDEBAR_LIBRARY_SORTING("sidebarLibrarySorting", true),
SIDEBAR_SHELF_SORTING("sidebarShelfSorting", true),
SIDEBAR_MAGIC_SHELF_SORTING("sidebarMagicShelfSorting", true),
ENTITY_VIEW_PREFERENCES("entityViewPreferences", true),
TABLE_COLUMN_PREFERENCE("tableColumnPreference", true),
DASHBOARD_CONFIG("dashboardConfig", true),
FILTER_MODE("filterMode", false),
FILTER_SORTING_MODE("filterSortingMode", false),
METADATA_CENTER_VIEW_MODE("metadataCenterViewMode", false);
METADATA_CENTER_VIEW_MODE("metadataCenterViewMode", false),
ENABLE_SERIES_VIEW("enableSeriesView", false);
private final String dbKey;
@@ -29,7 +29,7 @@ public class AuthorEntity {
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AuthorEntity that)) return false;
return getId() != null && Objects.equals(getId(), that.getId());
return id != null && Objects.equals(id, that.id);
}
@Override
@@ -0,0 +1,45 @@
package com.adityachandel.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import java.time.LocalDateTime;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "book_marks")
public class BookMarkEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private BookLoreUserEntity user;
@Column(name = "user_id", insertable = false, updatable = false)
private Long userId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "book_id", nullable = false)
private BookEntity book;
@Column(name = "book_id", insertable = false, updatable = false)
private Long bookId;
@Column(name = "cfi", nullable = false, length = 1000)
private String cfi;
@Column(name = "title")
private String title;
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
}
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.model.entity;
import com.adityachandel.booklore.util.BookUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
@@ -87,9 +88,6 @@ public class BookMetadataEntity {
@Column(name = "hardcover_review_count")
private Integer hardcoverReviewCount;
@Column(name = "personal_rating")
private Double personalRating;
@Column(name = "asin", length = 10)
private String asin;
@@ -170,10 +168,6 @@ public class BookMetadataEntity {
@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;
@@ -232,6 +226,15 @@ public class BookMetadataEntity {
@Column(name = "embedding_updated_at")
private Instant embeddingUpdatedAt;
@Column(name = "search_text", columnDefinition = "TEXT")
private String searchText;
@PrePersist
@PreUpdate
public void updateSearchText() {
this.searchText = BookUtils.buildSearchText(this);
}
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "book_id")
@@ -304,7 +307,6 @@ public class BookMetadataEntity {
this.hardcoverRatingLocked = lock;
this.hardcoverReviewCountLocked = lock;
this.comicvineIdLocked = lock;
this.personalRatingLocked = lock;
this.goodreadsIdLocked = lock;
this.hardcoverIdLocked = lock;
this.googleIdLocked = lock;
@@ -336,7 +338,6 @@ public class BookMetadataEntity {
&& Boolean.TRUE.equals(this.goodreadsReviewCountLocked)
&& Boolean.TRUE.equals(this.hardcoverRatingLocked)
&& Boolean.TRUE.equals(this.hardcoverReviewCountLocked)
&& Boolean.TRUE.equals(this.personalRatingLocked)
&& Boolean.TRUE.equals(this.goodreadsIdLocked)
&& Boolean.TRUE.equals(this.comicvineIdLocked)
&& Boolean.TRUE.equals(this.hardcoverIdLocked)
@@ -31,7 +31,7 @@ public class CategoryEntity {
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CategoryEntity that)) return false;
return getId() != null && Objects.equals(getId(), that.getId());
return id != null && Objects.equals(id, that.id);
}
@Override
@@ -33,4 +33,8 @@ public class KoboUserSettingsEntity {
@Column(name = "progress_mark_as_finished_threshold")
@Builder.Default
private Float progressMarkAsFinishedThreshold = 99f;
@Column(name = "auto_add_to_shelf")
@Builder.Default
private boolean autoAddToShelf = false;
}
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.model.entity;
import com.adityachandel.booklore.convertor.SortConverter;
import com.adityachandel.booklore.model.dto.Sort;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.IconType;
import com.adityachandel.booklore.model.enums.LibraryScanMode;
import jakarta.persistence.*;
import lombok.*;
@@ -40,6 +41,11 @@ public class LibraryEntity {
private String icon;
@Enumerated(EnumType.STRING)
@Column(name = "icon_type", nullable = false)
@Builder.Default
private IconType iconType = IconType.PRIME_NG;
@Column(name = "file_naming_pattern")
private String fileNamingPattern;
@@ -51,4 +57,11 @@ public class LibraryEntity {
@Enumerated(EnumType.STRING)
@Column(name = "default_book_format")
private BookFileType defaultBookFormat;
@PrePersist
public void ensureIconType() {
if (this.iconType == null) {
this.iconType = IconType.PRIME_NG;
}
}
}
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.model.entity;
import com.adityachandel.booklore.model.enums.IconType;
import jakarta.persistence.*;
import lombok.*;
@@ -29,6 +30,11 @@ public class MagicShelfEntity {
@Column(nullable = false)
private String icon;
@Enumerated(EnumType.STRING)
@Column(name = "icon_type", nullable = false)
@Builder.Default
private IconType iconType = IconType.PRIME_NG;
@Column(name = "filter_json", columnDefinition = "json", nullable = false)
private String filterJson;
@@ -48,4 +54,11 @@ public class MagicShelfEntity {
public void onUpdate() {
updatedAt = LocalDateTime.now();
}
@PrePersist
public void ensureIconType() {
if (this.iconType == null) {
this.iconType = IconType.PRIME_NG;
}
}
}
@@ -31,7 +31,7 @@ public class MoodEntity {
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MoodEntity that)) return false;
return getId() != null && Objects.equals(getId(), that.getId());
return id != null && Objects.equals(id, that.id);
}
@Override
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.model.entity;
import com.adityachandel.booklore.convertor.SortConverter;
import com.adityachandel.booklore.model.dto.Sort;
import com.adityachandel.booklore.model.enums.IconType;
import jakarta.persistence.*;
import lombok.*;
@@ -34,6 +35,11 @@ public class ShelfEntity {
private String icon;
@Enumerated(EnumType.STRING)
@Column(name = "icon_type", nullable = false)
@Builder.Default
private IconType iconType = IconType.PRIME_NG;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "book_shelf_mapping",
@@ -31,7 +31,7 @@ public class TagEntity {
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TagEntity that)) return false;
return getId() != null && Objects.equals(getId(), that.getId());
return id != null && Objects.equals(id, that.id);
}
@Override
@@ -93,4 +93,7 @@ public class UserBookProgressEntity {
@Column(name = "read_status_modified_time")
private Instant readStatusModifiedTime;
@Column(name = "personal_rating")
private Integer personalRating;
}
@@ -0,0 +1,7 @@
package com.adityachandel.booklore.model.enums;
public enum IconType {
PRIME_NG,
CUSTOM_SVG
}
@@ -0,0 +1,19 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.BookMarkEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional;
public interface BookMarkRepository extends JpaRepository<BookMarkEntity, Long> {
Optional<BookMarkEntity> findByIdAndUserId(Long id, Long userId);
@Query("SELECT b FROM BookMarkEntity b WHERE b.bookId = :bookId AND b.userId = :userId ORDER BY b.createdAt DESC")
List<BookMarkEntity> findByBookIdAndUserIdOrderByCreatedAtDesc(@Param("bookId") Long bookId, @Param("userId") Long userId);
boolean existsByCfiAndBookIdAndUserId(String cfi, Long bookId, Long userId);
}
@@ -20,7 +20,7 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
// ALL BOOKS - Two Query Pattern
// ============================================
@Query("SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
@Query("SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) ORDER BY b.addedOn DESC")
Page<Long> findBookIds(Pageable pageable);
@EntityGraph(attributePaths = {"metadata", "additionalFiles", "shelves"})
@@ -40,7 +40,7 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
// BOOKS BY LIBRARY IDs - Two Query Pattern
// ============================================
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false) ORDER BY b.addedOn DESC")
Page<Long> findBookIdsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
@EntityGraph(attributePaths = {"metadata", "additionalFiles", "shelves"})
@@ -60,7 +60,7 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
// BOOKS BY SHELF ID - Two Query Pattern
// ============================================
@Query("SELECT DISTINCT b.id FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false)")
@Query("SELECT DISTINCT b.id FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false) ORDER BY b.addedOn DESC")
Page<Long> findBookIdsByShelfId(@Param("shelfId") Long shelfId, Pageable pageable);
@EntityGraph(attributePaths = {"metadata", "additionalFiles", "shelves"})
@@ -74,13 +74,10 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
@Query("""
SELECT DISTINCT b.id FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
m.searchText LIKE CONCAT('%', :text, '%')
)
ORDER BY b.addedOn DESC
""")
Page<Long> findBookIdsByMetadataSearch(@Param("text") String text, Pageable pageable);
@@ -95,15 +92,12 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
@Query("""
SELECT DISTINCT b.id FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false)
AND b.library.id IN :libraryIds
AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
m.searchText LIKE CONCAT('%', :text, '%')
)
ORDER BY b.addedOn DESC
""")
Page<Long> findBookIdsByMetadataSearchAndLibraryIds(@Param("text") String text, @Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
@@ -120,4 +114,52 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
@Query(value = "SELECT b.id FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false) ORDER BY function('RAND')", nativeQuery = false)
List<Long> findRandomBookIdsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
}
// ============================================
// AUTHORS - Distinct Authors List
// ============================================
@Query("""
SELECT DISTINCT a FROM AuthorEntity a
JOIN a.bookMetadataEntityList m
JOIN m.book b
WHERE (b.deleted IS NULL OR b.deleted = false)
ORDER BY a.name
""")
List<com.adityachandel.booklore.model.entity.AuthorEntity> findDistinctAuthors();
@Query("""
SELECT DISTINCT a FROM AuthorEntity a
JOIN a.bookMetadataEntityList m
JOIN m.book b
WHERE (b.deleted IS NULL OR b.deleted = false)
AND b.library.id IN :libraryIds
ORDER BY a.name
""")
List<com.adityachandel.booklore.model.entity.AuthorEntity> findDistinctAuthorsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
// ============================================
// BOOKS BY AUTHOR - Two Query Pattern
// ============================================
@Query("""
SELECT DISTINCT b.id FROM BookEntity b
JOIN b.metadata m
JOIN m.authors a
WHERE a.name = :authorName
AND (b.deleted IS NULL OR b.deleted = false)
ORDER BY b.addedOn DESC
""")
Page<Long> findBookIdsByAuthorName(@Param("authorName") String authorName, Pageable pageable);
@Query("""
SELECT DISTINCT b.id FROM BookEntity b
JOIN b.metadata m
JOIN m.authors a
WHERE a.name = :authorName
AND b.library.id IN :libraryIds
AND (b.deleted IS NULL OR b.deleted = false)
ORDER BY b.addedOn DESC
""")
Page<Long> findBookIdsByAuthorNameAndLibraryIds(@Param("authorName") String authorName, @Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
}
@@ -72,26 +72,35 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
""")
List<BookEntity> findAllFullBooks();
@Query(value = """
SELECT DISTINCT b.* FROM book b
LEFT JOIN book_metadata m ON b.id = m.book_id
WHERE (b.deleted IS NULL OR b.deleted = false)
ORDER BY b.id
LIMIT :limit OFFSET :offset
""", nativeQuery = true)
List<BookEntity> findBooksForMigrationBatch(@Param("offset") int offset, @Param("limit") int limit);
@Query("""
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN FETCH b.metadata m
LEFT JOIN FETCH m.authors
WHERE b.id IN :bookIds
""")
List<BookEntity> findBooksWithMetadataAndAuthors(@Param("bookIds") List<Long> bookIds);
@Query(value = """
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
m.searchText LIKE CONCAT('%', :text, '%')
)
""",
countQuery = """
SELECT COUNT(DISTINCT b.id) FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
m.searchText LIKE CONCAT('%', :text, '%')
)
""")
Page<BookEntity> searchByMetadata(@Param("text") String text, Pageable pageable);
@@ -31,5 +31,8 @@ public interface BookdropFileRepository extends JpaRepository<BookdropFileEntity
@Query("SELECT f.id FROM BookdropFileEntity f WHERE f.id NOT IN :excludedIds")
List<Long> findAllExcludingIdsFlat(@Param("excludedIds") List<Long> excludedIds);
@Query("SELECT f.id FROM BookdropFileEntity f")
List<Long> findAllIds();
}
@@ -4,6 +4,7 @@ import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
@@ -12,4 +13,6 @@ public interface KoboUserSettingsRepository extends JpaRepository<KoboUserSettin
Optional<KoboUserSettingsEntity> findByUserId(Long userId);
Optional<KoboUserSettingsEntity> findByToken(String token);
List<KoboUserSettingsEntity> findByAutoAddToShelfTrueAndSyncEnabledTrue();
}
@@ -18,4 +18,6 @@ public interface ShelfRepository extends JpaRepository<ShelfEntity, Long> {
List<ShelfEntity> findByUserId(Long id);
Optional<ShelfEntity> findByUserIdAndName(Long id, String name);
List<ShelfEntity> findByUserIdInAndName(List<Long> userIds, String name);
}
@@ -17,10 +17,7 @@ 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.*;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
@@ -315,13 +312,13 @@ public class BookRuleEvaluatorService {
case READ_STATUS -> progressJoin.get("readStatus");
case DATE_FINISHED -> progressJoin.get("dateFinished");
case LAST_READ_TIME -> progressJoin.get("lastReadTime");
case PERSONAL_RATING -> progressJoin.get("personalRating");
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");
@@ -433,7 +430,7 @@ public class BookRuleEvaluatorService {
private List<String> toStringList(Object value) {
if (value == null) return Collections.emptyList();
if (value instanceof List) {
return ((List<?>) value).stream()
return ((Collection<?>) value).stream()
.map(Object::toString)
.collect(Collectors.toList());
}
@@ -0,0 +1,274 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.request.SvgIconCreateRequest;
import com.adityachandel.booklore.model.dto.response.SvgIconBatchResponse;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@Slf4j
@RequiredArgsConstructor
@Service
public class IconService {
private static final Pattern INVALID_FILENAME_CHARS_PATTERN = Pattern.compile("[^a-zA-Z0-9._-]");
private final AppProperties appProperties;
private final ConcurrentHashMap<String, String> svgCache = new ConcurrentHashMap<>();
private static final String ICONS_DIR = "icons";
private static final String SVG_DIR = "svg";
private static final String SVG_EXTENSION = ".svg";
private static final int MAX_CACHE_SIZE = 1000;
private static final String SVG_START_TAG = "<svg";
private static final String XML_DECLARATION = "<?xml";
private static final String SVG_END_TAG = "</svg>";
@PostConstruct
public void init() {
try {
Path iconsPath = getIconsSvgPath();
if (Files.exists(iconsPath)) {
loadIconsIntoCache();
log.info("Loaded {} SVG icons into cache", svgCache.size());
} else {
Files.createDirectories(iconsPath);
log.info("Created icons directory: {}", iconsPath);
}
} catch (IOException e) {
log.error("Failed to initialize IconService: {}", e.getMessage(), e);
}
}
private void loadIconsIntoCache() throws IOException {
Path iconsPath = getIconsSvgPath();
try (Stream<Path> paths = Files.list(iconsPath)) {
paths.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(SVG_EXTENSION))
.limit(MAX_CACHE_SIZE)
.forEach(path -> {
try {
String filename = path.getFileName().toString();
String content = Files.readString(path);
svgCache.put(filename, content);
} catch (IOException e) {
log.warn("Failed to load icon: {}", path.getFileName(), e);
}
});
}
}
public void saveSvgIcon(SvgIconCreateRequest request) {
validateSvgData(request.getSvgData());
String filename = normalizeFilename(request.getSvgName());
Path filePath = getIconsSvgPath().resolve(filename);
if (Files.exists(filePath)) {
log.warn("SVG icon already exists: {}", filename);
throw ApiError.ICON_ALREADY_EXISTS.createException(request.getSvgName());
}
try {
Files.writeString(filePath, request.getSvgData(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
updateCache(filename, request.getSvgData());
log.info("SVG icon saved successfully: {}", filename);
} catch (IOException e) {
log.error("Failed to save SVG icon: {}", e.getMessage(), e);
throw ApiError.FILE_READ_ERROR.createException("Failed to save SVG icon: " + e.getMessage());
}
}
public SvgIconBatchResponse saveBatchSvgIcons(List<SvgIconCreateRequest> requests) {
if (requests == null || requests.isEmpty()) {
throw ApiError.INVALID_INPUT.createException("Icons list cannot be empty");
}
List<SvgIconBatchResponse.IconSaveResult> results = new ArrayList<>();
int successCount = 0;
int failureCount = 0;
for (SvgIconCreateRequest request : requests) {
try {
saveSvgIcon(request);
results.add(SvgIconBatchResponse.IconSaveResult.builder()
.iconName(request.getSvgName())
.success(true)
.build());
successCount++;
} catch (Exception e) {
log.warn("Failed to save icon '{}': {}", request.getSvgName(), e.getMessage());
results.add(SvgIconBatchResponse.IconSaveResult.builder()
.iconName(request.getSvgName())
.success(false)
.errorMessage(e.getMessage())
.build());
failureCount++;
}
}
log.info("Batch save completed: {} successful, {} failed", successCount, failureCount);
return SvgIconBatchResponse.builder()
.totalRequested(requests.size())
.successCount(successCount)
.failureCount(failureCount)
.results(results)
.build();
}
public String getSvgIcon(String name) {
String filename = normalizeFilename(name);
String cachedSvg = svgCache.get(filename);
if (cachedSvg != null) {
return cachedSvg;
}
return loadAndCacheIcon(filename, name);
}
private String loadAndCacheIcon(String filename, String originalName) {
Path filePath = getIconsSvgPath().resolve(filename);
if (!Files.exists(filePath)) {
log.warn("SVG icon not found: {}", filename);
throw ApiError.FILE_NOT_FOUND.createException("SVG icon not found: " + originalName);
}
try {
String svgData = Files.readString(filePath);
updateCache(filename, svgData);
return svgData;
} catch (IOException e) {
log.error("Failed to read SVG icon: {}", e.getMessage(), e);
throw ApiError.FILE_READ_ERROR.createException("Failed to read SVG icon: " + e.getMessage());
}
}
public void deleteSvgIcon(String svgName) {
String filename = normalizeFilename(svgName);
Path filePath = getIconsSvgPath().resolve(filename);
try {
if (!Files.exists(filePath)) {
log.warn("SVG icon not found for deletion: {}", filename);
throw ApiError.FILE_NOT_FOUND.createException("SVG icon not found: " + svgName);
}
Files.delete(filePath);
svgCache.remove(filename);
log.info("SVG icon deleted successfully: {}", filename);
} catch (IOException e) {
log.error("Failed to delete SVG icon: {}", e.getMessage(), e);
throw ApiError.FILE_READ_ERROR.createException("Failed to delete SVG icon: " + e.getMessage());
}
}
public Page<String> getIconNames(int page, int size) {
validatePaginationParams(page, size);
Path iconsPath = getIconsSvgPath();
if (!Files.exists(iconsPath)) {
return new PageImpl<>(Collections.emptyList(), PageRequest.of(page, size), 0);
}
try (Stream<Path> paths = Files.list(iconsPath)) {
List<String> allIcons = paths
.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(SVG_EXTENSION))
.map(path -> path.getFileName().toString().replace(SVG_EXTENSION, ""))
.sorted()
.toList();
return createPage(allIcons, page, size);
} catch (IOException e) {
log.error("Failed to read icon names: {}", e.getMessage(), e);
throw ApiError.FILE_READ_ERROR.createException("Failed to read icon names: " + e.getMessage());
}
}
private Page<String> createPage(List<String> allIcons, int page, int size) {
int totalElements = allIcons.size();
int fromIndex = page * size;
int toIndex = Math.min(fromIndex + size, totalElements);
List<String> pageContent = fromIndex < totalElements
? allIcons.subList(fromIndex, toIndex)
: Collections.emptyList();
return new PageImpl<>(pageContent, PageRequest.of(page, size), totalElements);
}
private void updateCache(String filename, String content) {
if (!svgCache.containsKey(filename) && svgCache.size() >= MAX_CACHE_SIZE) {
String firstKey = svgCache.keys().nextElement();
svgCache.remove(firstKey);
}
svgCache.put(filename, content);
}
private Path getIconsSvgPath() {
return Paths.get(appProperties.getPathConfig(), ICONS_DIR, SVG_DIR);
}
private void validateSvgData(String svgData) {
if (svgData == null || svgData.isBlank()) {
throw ApiError.INVALID_INPUT.createException("SVG data cannot be empty");
}
String trimmed = svgData.trim();
if (!trimmed.startsWith(SVG_START_TAG) && !trimmed.startsWith(XML_DECLARATION)) {
throw ApiError.INVALID_INPUT.createException("Invalid SVG format: must start with <svg or <?xml");
}
if (!trimmed.contains(SVG_END_TAG)) {
throw ApiError.INVALID_INPUT.createException("Invalid SVG format: missing closing </svg> tag");
}
}
private void validatePaginationParams(int page, int size) {
if (page < 0) {
throw ApiError.INVALID_INPUT.createException("Page index must not be less than zero");
}
if (size < 1) {
throw ApiError.INVALID_INPUT.createException("Page size must not be less than one");
}
}
private String normalizeFilename(String filename) {
if (filename == null || filename.isBlank()) {
throw ApiError.INVALID_INPUT.createException("Filename cannot be empty");
}
String sanitized = INVALID_FILENAME_CHARS_PATTERN.matcher(filename.trim()).replaceAll("_");
return sanitized.endsWith(SVG_EXTENSION) ? sanitized : sanitized + SVG_EXTENSION;
}
ConcurrentHashMap<String, String> getSvgCache() {
return svgCache;
}
}
@@ -56,6 +56,7 @@ public class MagicShelfService {
}
existing.setName(dto.getName());
existing.setIcon(dto.getIcon());
existing.setIconType(dto.getIconType());
existing.setFilterJson(dto.getFilterJson());
existing.setPublic(dto.getIsPublic());
return toDto(magicShelfRepository.save(existing));
@@ -81,6 +82,7 @@ public class MagicShelfService {
dto.setId(entity.getId());
dto.setName(entity.getName());
dto.setIcon(entity.getIcon());
dto.setIconType(entity.getIconType());
dto.setFilterJson(entity.getFilterJson());
dto.setIsPublic(entity.isPublic());
return dto;
@@ -91,6 +93,7 @@ public class MagicShelfService {
entity.setId(dto.getId());
entity.setName(dto.getName());
entity.setIcon(dto.getIcon());
entity.setIconType(dto.getIconType());
entity.setFilterJson(dto.getFilterJson());
entity.setPublic(dto.getIsPublic());
entity.setUserId(userId);
@@ -40,6 +40,7 @@ public class ShelfService {
ShelfEntity shelfEntity = ShelfEntity.builder()
.icon(request.getIcon())
.name(request.getName())
.iconType(request.getIconType())
.user(fetchUserEntityById(userId))
.build();
return shelfMapper.toShelf(shelfRepository.save(shelfEntity));
@@ -49,6 +50,7 @@ public class ShelfService {
ShelfEntity shelfEntity = findShelfByIdOrThrow(id);
shelfEntity.setName(request.getName());
shelfEntity.setIcon(request.getIcon());
shelfEntity.setIconType(request.getIconType());
return shelfMapper.toShelf(shelfRepository.save(shelfEntity));
}
@@ -83,6 +83,7 @@ public class BookCreatorService {
.map(authorName -> authorRepository.findByName(authorName)
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
.forEach(authorEntity -> bookEntity.getMetadata().getAuthors().add(authorEntity));
bookEntity.getMetadata().updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
}
private String truncate(String input, int maxLength) {
@@ -0,0 +1,72 @@
package com.adityachandel.booklore.service.book;
import com.adityachandel.booklore.mapper.BookMarkMapper;
import com.adityachandel.booklore.model.dto.BookMark;
import com.adityachandel.booklore.model.dto.CreateBookMarkRequest;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.BookMarkEntity;
import com.adityachandel.booklore.repository.BookMarkRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import java.util.List;
@Service
@RequiredArgsConstructor
public class BookMarkService {
private final BookMarkRepository bookMarkRepository;
private final BookRepository bookRepository;
private final UserRepository userRepository;
private final BookMarkMapper mapper;
private final AuthenticationService authenticationService;
@Transactional(readOnly = true)
public List<BookMark> getBookmarksForBook(Long bookId) {
Long userId = authenticationService.getAuthenticatedUser().getId();
return bookMarkRepository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId)
.stream()
.map(mapper::toDto)
.toList();
}
@Transactional
public BookMark createBookmark(CreateBookMarkRequest request) {
Long userId = authenticationService.getAuthenticatedUser().getId();
// Check for existing bookmark
if (bookMarkRepository.existsByCfiAndBookIdAndUserId(request.getCfi(), request.getBookId(), userId)) {
throw new IllegalArgumentException("Bookmark already exists at this location");
}
BookLoreUserEntity currentUser = userRepository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException("User not found: " + userId));
BookEntity book = bookRepository.findById(request.getBookId())
.orElseThrow(() -> new EntityNotFoundException("Book not found: " + request.getBookId()));
BookMarkEntity entity = BookMarkEntity.builder()
.user(currentUser)
.book(book)
.cfi(request.getCfi())
.title(request.getTitle())
.build();
BookMarkEntity saved = bookMarkRepository.save(entity);
return mapper.toDto(saved);
}
@Transactional
public void deleteBookmark(Long bookmarkId) {
Long userId = authenticationService.getAuthenticatedUser().getId();
BookMarkEntity bookmark = bookMarkRepository.findByIdAndUserId(bookmarkId, userId)
.orElseThrow(() -> new EntityNotFoundException("Bookmark not found: " + bookmarkId));
bookMarkRepository.delete(bookmark);
}
}
@@ -100,6 +100,7 @@ public class BookService {
book.setLastReadTime(progress.getLastReadTime());
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
book.setDateFinished(progress.getDateFinished());
book.setPersonalRating(progress.getPersonalRating());
}
}
@@ -191,6 +192,7 @@ public class BookService {
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
book.setReadStatus(userProgress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(userProgress.getReadStatus()));
book.setDateFinished(userProgress.getDateFinished());
book.setPersonalRating(userProgress.getPersonalRating());
if (!withDescription) {
book.getMetadata().setDescription(null);
@@ -429,13 +431,7 @@ public class BookService {
.findByUserIdAndBookId(user.getId(), bookEntity.getId())
.orElse(null);
if (progress != null) {
setBookProgress(book, progress);
book.setLastReadTime(progress.getLastReadTime());
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
book.setDateFinished(progress.getDateFinished());
}
this.enrichBookWithProgress(book, progress);
return book;
})
.collect(Collectors.toList());
@@ -491,6 +487,65 @@ public class BookService {
return updatedBooks;
}
@Transactional
public List<Book> updatePersonalRating(List<Long> bookIds, Integer rating) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<BookEntity> books = bookRepository.findAllById(bookIds);
if (books.size() != bookIds.size()) {
throw ApiError.BOOK_NOT_FOUND.createException("One or more books not found");
}
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
for (BookEntity book : books) {
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), book.getId())
.orElse(new UserBookProgressEntity());
progress.setUser(userEntity);
progress.setBook(book);
progress.setPersonalRating(rating);
userBookProgressRepository.save(progress);
}
return books.stream()
.map(bookEntity -> {
Book book = bookMapper.toBook(bookEntity);
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), bookEntity.getId())
.orElse(null);
this.enrichBookWithProgress(book, progress);
return book;
})
.collect(Collectors.toList());
}
public List<Book> resetPersonalRating(List<Long> bookIds) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<Book> updatedBooks = new ArrayList<>();
Optional<BookLoreUserEntity> userEntity = userRepository.findById(user.getId());
for (Long bookId : bookIds) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
UserBookProgressEntity progress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), bookId)
.orElse(new UserBookProgressEntity());
progress.setBook(bookEntity);
progress.setUser(userEntity.orElseThrow());
progress.setPersonalRating(null);
userBookProgressRepository.save(progress);
updatedBooks.add(bookMapper.toBook(bookEntity));
}
return updatedBooks;
}
@Transactional
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
@@ -186,7 +186,12 @@ public class BookDropService {
AtomicInteger failedCount,
AtomicInteger totalFilesProcessed) {
List<Long> excludedIds = Optional.ofNullable(request.getExcludedIds()).orElse(List.of());
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds);
List<Long> allIds;
if (excludedIds.isEmpty()) {
allIds = bookdropFileRepository.findAllIds();
} else {
allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds);
}
log.info("SelectAll: Total files to finalize (after exclusions): {}, Excluded IDs: {}", allIds.size(), excludedIds);
processFileChunks(allIds, metadataById, defaultLibraryId, defaultPathId, results, failedCount, totalFilesProcessed);
@@ -507,7 +512,7 @@ public class BookDropService {
private void cleanupTempFile(Path tempPath) {
if (tempPath != null) {
try {
Files.delete(tempPath);
Files.deleteIfExists(tempPath);
} catch (Exception e) {
log.warn("Failed to cleanup temp file: {}", tempPath, e);
}
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.bookdrop;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
@@ -147,16 +148,19 @@ public class BookdropMonitoringService {
try (Stream<Path> pathStream = Files.walk(fullPath)) {
pathStream
.filter(Files::isRegularFile)
.filter(path -> !FileUtils.shouldIgnore(path))
.filter(path -> BookFileExtension.fromFileName(path.getFileName().toString()).isPresent())
.forEach(path -> eventHandler.enqueueFile(path, StandardWatchEventKinds.ENTRY_CREATE));
} catch (IOException e) {
log.error("Failed to scan new directory: {}", fullPath, e);
}
} else {
if (BookFileExtension.fromFileName(fullPath.getFileName().toString()).isPresent()) {
eventHandler.enqueueFile(fullPath, kind);
} else {
log.info("Ignored unsupported file type: {}", fullPath);
if (!FileUtils.shouldIgnore(fullPath)) {
if (BookFileExtension.fromFileName(fullPath.getFileName().toString()).isPresent()) {
eventHandler.enqueueFile(fullPath, kind);
} else {
log.info("Ignored unsupported file type: {}", fullPath);
}
}
}
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
@@ -185,6 +189,7 @@ public class BookdropMonitoringService {
private void scanExistingBookdropFiles() {
try (Stream<Path> files = Files.walk(bookdrop)) {
files.filter(Files::isRegularFile)
.filter(path -> !FileUtils.shouldIgnore(path))
.filter(path -> BookFileExtension.fromFileName(path.getFileName().toString()).isPresent())
.forEach(file -> {
log.info("Found existing supported file on startup: {}", file);
@@ -12,7 +12,11 @@ import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@@ -27,37 +31,85 @@ public class FileMoveHelper {
private final MonitoringRegistrationService monitoringRegistrationService;
private final AppSettingService appSettingService;
private static final int MAX_ATTEMPTS = 3;
private static final long RETRY_DELAY_MS = 100;
private static final Set<Class<? extends Exception>> RETRYABLE_EXCEPTIONS = Set.of(
NoSuchFileException.class,
AccessDeniedException.class,
FileSystemException.class,
DirectoryNotEmptyException.class
);
private static final Set<String> IGNORED_FILENAMES = Set.of(".DS_Store", "Thumbs.db");
public boolean waitForFileAccessible(Path path) {
for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
if (Files.exists(path) && Files.isReadable(path)) {
return true;
}
if (attempt < MAX_ATTEMPTS) {
log.debug("File not accessible on attempt {}/{}, waiting {}ms: {}",
attempt, MAX_ATTEMPTS, RETRY_DELAY_MS, path);
waitBeforeRetry();
}
}
return false;
}
public void moveFile(Path source, Path target) throws IOException {
if (!waitForFileAccessible(source)) {
throw new NoSuchFileException(source.toString(), null, "Source file not accessible after retries");
}
if (target.getParent() != null) {
Files.createDirectories(target.getParent());
}
log.info("Moving file from {} to {}", source, target);
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
executeWithRetry(() -> Files.move(source, target, StandardCopyOption.REPLACE_EXISTING));
}
public Path moveFileWithBackup(Path source, Path target) throws IOException {
public Path moveFileWithBackup(Path source) throws IOException {
if (!waitForFileAccessible(source)) {
throw new NoSuchFileException(source.toString(), null, "Source file not accessible after retries");
}
Path tempPath = source.resolveSibling(source.getFileName().toString() + ".tmp_move");
log.info("Moving file from {} to temporary location {}", source, tempPath);
Files.move(source, tempPath, StandardCopyOption.REPLACE_EXISTING);
executeWithRetry(() -> Files.move(source, tempPath, StandardCopyOption.REPLACE_EXISTING));
return tempPath;
}
public void commitMove(Path tempPath, Path target) throws IOException {
if (!waitForFileAccessible(tempPath)) {
throw new NoSuchFileException(tempPath.toString(), null, "Temporary file not accessible before commit");
}
if (target.getParent() != null) {
Files.createDirectories(target.getParent());
}
log.info("Committing move from temporary location {} to {}", tempPath, target);
Files.move(tempPath, target, StandardCopyOption.REPLACE_EXISTING);
executeWithRetry(() -> Files.move(tempPath, target, StandardCopyOption.REPLACE_EXISTING));
}
public void rollbackMove(Path tempPath, Path originalSource) {
if (Files.exists(tempPath)) {
if (!Files.exists(tempPath)) {
return;
}
for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
try {
log.info("Rolling back move from {} to {}", tempPath, originalSource);
Files.move(tempPath, originalSource, StandardCopyOption.REPLACE_EXISTING);
return;
} catch (IOException e) {
log.error("Failed to rollback file move from {} to {}", tempPath, originalSource, e);
if (attempt == MAX_ATTEMPTS) {
log.error("Failed to rollback file move from {} to {} after {} attempts. " +
"Orphaned temp file may need manual cleanup: {}",
tempPath, originalSource, MAX_ATTEMPTS, tempPath, e);
return;
}
log.warn("Rollback attempt {}/{} failed, retrying: {}", attempt, MAX_ATTEMPTS, e.getMessage());
waitBeforeRetry();
}
}
}
@@ -74,6 +126,7 @@ public class FileMoveHelper {
}
public void registerLibraryPaths(Long libraryId, Path libraryRoot) {
log.debug("Registering library paths for library {} with root {}", libraryId, libraryRoot);
monitoringRegistrationService.registerLibraryPaths(libraryId, libraryRoot);
}
@@ -107,9 +160,7 @@ public class FileMoveHelper {
}
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) {
Path dir = currentDir;
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
dir = dir.toAbsolutePath().normalize();
Path dir = currentDir.toAbsolutePath().normalize();
Set<Path> normalizedRoots = new HashSet<>();
for (Path root : libraryRoots) {
normalizedRoots.add(root.toAbsolutePath().normalize());
@@ -118,13 +169,7 @@ public class FileMoveHelper {
if (isLibraryRoot(dir, normalizedRoots)) {
break;
}
File[] files = dir.toFile().listFiles();
if (files == null) {
log.warn("Cannot read directory: {}. Stopping cleanup.", dir);
break;
}
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
deleteIgnoredFilesAndDirectory(files, dir);
if (deleteIfEffectivelyEmpty(dir, normalizedRoots)) {
dir = dir.getParent();
} else {
break;
@@ -132,6 +177,53 @@ public class FileMoveHelper {
}
}
private boolean deleteIfEffectivelyEmpty(Path dir, Set<Path> libraryRoots) {
if (isLibraryRoot(dir, libraryRoots)) {
return false;
}
File[] contents = dir.toFile().listFiles();
if (contents == null) {
log.warn("Cannot read directory: {}. Stopping cleanup.", dir);
return false;
}
boolean deletedAnySubdirectory = recursivelyDeleteEmptySubdirectories(contents, libraryRoots);
if (deletedAnySubdirectory) {
waitBeforeRetry();
}
File[] remainingContents = dir.toFile().listFiles();
if (remainingContents == null) {
log.warn("Cannot read directory after subdirectory cleanup: {}", dir);
return false;
}
if (isSafeToDelete(remainingContents)) {
deleteIgnoredFilesAndDirectory(remainingContents, dir);
return true;
}
return false;
}
private boolean recursivelyDeleteEmptySubdirectories(File[] contents, Set<Path> libraryRoots) {
boolean deletedAny = false;
for (File file : contents) {
if (isNonSymlinkDirectory(file)) {
if (deleteIfEffectivelyEmpty(file.toPath(), libraryRoots)) {
deletedAny = true;
}
}
}
return deletedAny;
}
private boolean isNonSymlinkDirectory(File file) {
return file.isDirectory() && !Files.isSymbolicLink(file.toPath());
}
private boolean isLibraryRoot(Path currentDir, Set<Path> normalizedRoots) {
for (Path root : normalizedRoots) {
try {
@@ -145,9 +237,11 @@ public class FileMoveHelper {
return false;
}
private boolean hasOnlyIgnoredFiles(File[] files, Set<String> ignoredFilenames) {
private boolean isSafeToDelete(File[] files) {
for (File file : files) {
if (!ignoredFilenames.contains(file.getName())) {
if (Files.isSymbolicLink(file.toPath())
|| file.isDirectory()
|| !IGNORED_FILENAMES.contains(file.getName())) {
return false;
}
}
@@ -164,10 +258,45 @@ public class FileMoveHelper {
}
}
try {
Files.delete(currentDir);
executeWithRetry(() -> Files.delete(currentDir));
log.info("Deleted empty directory: {}", currentDir);
} catch (IOException e) {
log.warn("Failed to delete directory: {}", currentDir, e);
}
}
@FunctionalInterface
private interface FileOperation {
void execute() throws IOException;
}
private void executeWithRetry(FileOperation operation) throws IOException {
for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
try {
operation.execute();
return;
} catch (IOException e) {
if (!isRetryableException(e) || attempt == MAX_ATTEMPTS) {
throw e;
}
log.warn("File operation failed (attempt {}/{}), retrying in {}ms: {}",
attempt, MAX_ATTEMPTS, RETRY_DELAY_MS, e.getMessage());
waitBeforeRetry();
}
}
}
private boolean isRetryableException(IOException e) {
return RETRYABLE_EXCEPTIONS.stream().anyMatch(type -> type.isInstance(e));
}
private void waitBeforeRetry() {
try {
Thread.sleep(RETRY_DELAY_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@@ -28,6 +28,8 @@ import java.util.stream.Collectors;
@Slf4j
public class FileMoveService {
private static final long EVENT_DRAIN_TIMEOUT_MS = 300;
private final BookRepository bookRepository;
private final LibraryRepository libraryRepository;
private final FileMoveHelper fileMoveHelper;
@@ -41,79 +43,100 @@ public class FileMoveService {
@Transactional
public void bulkMoveFiles(FileMoveRequest request) {
List<FileMoveRequest.Move> moves = request.getMoves();
Set<Long> targetLibraryIds = moves.stream().map(FileMoveRequest.Move::getTargetLibraryId).collect(Collectors.toSet());
Set<Long> sourceLibraryIds = new HashSet<>();
monitoringRegistrationService.unregisterLibraries(targetLibraryIds);
Set<Long> allAffectedLibraryIds = collectAllAffectedLibraryIds(moves);
Set<Path> libraryPaths = monitoringRegistrationService.getPathsForLibraries(allAffectedLibraryIds);
log.info("Unregistering {} libraries before bulk file move", allAffectedLibraryIds.size());
monitoringRegistrationService.unregisterLibraries(allAffectedLibraryIds);
monitoringRegistrationService.waitForEventsDrainedByPaths(libraryPaths, EVENT_DRAIN_TIMEOUT_MS);
for (FileMoveRequest.Move move : moves) {
Long bookId = move.getBookId();
Long targetLibraryId = move.getTargetLibraryId();
Long targetLibraryPathId = move.getTargetLibraryPathId();
Path tempPath = null;
Path currentFilePath = null;
try {
Optional<BookEntity> optionalBook = bookRepository.findById(bookId);
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(targetLibraryId);
if (optionalBook.isEmpty() || optionalLibrary.isEmpty()) {
continue;
}
BookEntity bookEntity = optionalBook.get();
LibraryEntity targetLibrary = optionalLibrary.get();
Optional<LibraryPathEntity> optionalLibraryPathEntity = targetLibrary.getLibraryPaths().stream().filter(l -> Objects.equals(l.getId(), targetLibraryPathId)).findFirst();
if (optionalLibraryPathEntity.isEmpty()) {
continue;
}
LibraryPathEntity libraryPathEntity = optionalLibraryPathEntity.get();
LibraryEntity sourceLibrary = bookEntity.getLibrary();
if (!sourceLibrary.getId().equals(targetLibrary.getId()) && !sourceLibraryIds.contains(sourceLibrary.getId())) {
monitoringRegistrationService.unregisterLibraries(Collections.singleton(sourceLibrary.getId()));
sourceLibraryIds.add(sourceLibrary.getId());
}
currentFilePath = bookEntity.getFullFilePath();
String pattern = fileMoveHelper.getFileNamingPattern(targetLibrary);
Path newFilePath = fileMoveHelper.generateNewFilePath(bookEntity, libraryPathEntity, pattern);
if (currentFilePath.equals(newFilePath)) {
continue;
}
tempPath = fileMoveHelper.moveFileWithBackup(currentFilePath, newFilePath);
String newFileName = newFilePath.getFileName().toString();
String newFileSubPath = fileMoveHelper.extractSubPath(newFilePath, libraryPathEntity);
bookRepository.updateFileAndLibrary(bookEntity.getId(), newFileSubPath, newFileName, targetLibrary.getId(), libraryPathEntity);
fileMoveHelper.commitMove(tempPath, newFilePath);
tempPath = null;
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize();
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot));
entityManager.clear();
BookEntity fresh = bookRepository.findById(bookId).orElseThrow();
notificationService.sendMessage(Topic.BOOK_UPDATE, bookMapper.toBookWithDescription(fresh, false));
} catch (Exception e) {
log.error("Error moving file for book ID {}: {}", bookId, e.getMessage(), e);
} finally {
if (tempPath != null && currentFilePath != null) {
fileMoveHelper.rollbackMove(tempPath, currentFilePath);
}
try {
for (FileMoveRequest.Move move : moves) {
processSingleMove(move);
}
} finally {
for (Long libraryId : allAffectedLibraryIds) {
libraryRepository.findById(libraryId)
.ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)));
}
}
}
for (Long libraryId : targetLibraryIds) {
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
optionalLibrary.ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)));
private Set<Long> collectAllAffectedLibraryIds(List<FileMoveRequest.Move> moves) {
Set<Long> libraryIds = new HashSet<>();
for (FileMoveRequest.Move move : moves) {
libraryIds.add(move.getTargetLibraryId());
bookRepository.findById(move.getBookId())
.ifPresent(book -> libraryIds.add(book.getLibrary().getId()));
}
for (Long libraryId : sourceLibraryIds) {
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(libraryId);
optionalLibrary.ifPresent(library -> monitoringRegistrationService.registerLibrary(libraryMapper.toLibrary(library)));
return libraryIds;
}
private void processSingleMove(FileMoveRequest.Move move) {
Long bookId = move.getBookId();
Long targetLibraryId = move.getTargetLibraryId();
Long targetLibraryPathId = move.getTargetLibraryPathId();
Path tempPath = null;
Path currentFilePath = null;
try {
Optional<BookEntity> optionalBook = bookRepository.findById(bookId);
Optional<LibraryEntity> optionalLibrary = libraryRepository.findById(targetLibraryId);
if (optionalBook.isEmpty()) {
log.warn("Book not found for move operation: bookId={}", bookId);
return;
}
if (optionalLibrary.isEmpty()) {
log.warn("Target library not found for move operation: libraryId={}", targetLibraryId);
return;
}
BookEntity bookEntity = optionalBook.get();
LibraryEntity targetLibrary = optionalLibrary.get();
Optional<LibraryPathEntity> optionalLibraryPathEntity = targetLibrary.getLibraryPaths().stream()
.filter(libraryPath -> Objects.equals(libraryPath.getId(), targetLibraryPathId))
.findFirst();
if (optionalLibraryPathEntity.isEmpty()) {
log.warn("Target library path not found for move operation: libraryId={}, pathId={}", targetLibraryId, targetLibraryPathId);
return;
}
LibraryPathEntity libraryPathEntity = optionalLibraryPathEntity.get();
currentFilePath = bookEntity.getFullFilePath();
String pattern = fileMoveHelper.getFileNamingPattern(targetLibrary);
Path newFilePath = fileMoveHelper.generateNewFilePath(bookEntity, libraryPathEntity, pattern);
if (currentFilePath.equals(newFilePath)) {
return;
}
tempPath = fileMoveHelper.moveFileWithBackup(currentFilePath);
String newFileName = newFilePath.getFileName().toString();
String newFileSubPath = fileMoveHelper.extractSubPath(newFilePath, libraryPathEntity);
bookRepository.updateFileAndLibrary(bookEntity.getId(), newFileSubPath, newFileName, targetLibrary.getId(), libraryPathEntity);
fileMoveHelper.commitMove(tempPath, newFilePath);
tempPath = null;
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize();
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot));
entityManager.clear();
BookEntity fresh = bookRepository.findById(bookId).orElseThrow();
notificationService.sendMessage(Topic.BOOK_UPDATE, bookMapper.toBookWithDescription(fresh, false));
} catch (Exception e) {
log.error("Error moving file for book ID {}: {}", bookId, e.getMessage(), e);
} finally {
if (tempPath != null && currentFilePath != null) {
fileMoveHelper.rollbackMove(tempPath, currentFilePath);
}
}
}
@@ -122,8 +145,10 @@ public class FileMoveService {
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize();
boolean isLibraryMonitoredWhenCalled = false;
try {
isLibraryMonitoredWhenCalled = monitoringRegistrationService.isLibraryMonitored(libraryId);
String pattern = fileMoveHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary());
Path currentFilePath = bookEntity.getFullFilePath();
Path expectedFilePath = fileMoveHelper.generateNewFilePath(bookEntity, bookEntity.getLibraryPath(), pattern);
@@ -134,7 +159,12 @@ public class FileMoveService {
log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath);
fileMoveHelper.unregisterLibrary(libraryId);
if (isLibraryMonitoredWhenCalled) {
log.debug("Unregistering library {} before moving a single file", libraryId);
Set<Path> libraryPaths = monitoringRegistrationService.getPathsForLibraries(Set.of(libraryId));
fileMoveHelper.unregisterLibrary(libraryId);
monitoringRegistrationService.waitForEventsDrainedByPaths(libraryPaths, EVENT_DRAIN_TIMEOUT_MS);
}
fileMoveHelper.moveFile(currentFilePath, expectedFilePath);
@@ -151,7 +181,10 @@ public class FileMoveService {
} catch (Exception e) {
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
} finally {
fileMoveHelper.registerLibraryPaths(libraryId, libraryRoot);
if (isLibraryMonitoredWhenCalled) {
log.debug("Registering library paths for library {} with root {}", libraryId, libraryRoot);
fileMoveHelper.registerLibraryPaths(libraryId, libraryRoot);
}
}
return FileMoveResult.builder().moved(false).build();
@@ -14,14 +14,13 @@ import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import io.documentnode.epub4j.domain.Resource;
import io.documentnode.epub4j.epub.EpubReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.time.Instant;
import java.util.List;
import java.util.Set;
@@ -63,34 +62,28 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
public boolean generateCover(BookEntity bookEntity) {
try {
File epubFile = new File(FileUtils.getBookFullPath(bookEntity));
io.documentnode.epub4j.domain.Book epub;
try (FileInputStream fis = new FileInputStream(epubFile)) {
epub = new EpubReader().readEpub(fis);
}
Resource coverImage = epub.getCoverImage();
byte[] coverData = epubMetadataExtractor.extractCover(epubFile);
if (coverImage == null) {
for (Resource res : epub.getResources().getAll()) {
String id = res.getId();
String href = res.getHref();
if ((id != null && id.toLowerCase().contains("cover")) ||
(href != null && href.toLowerCase().contains("cover"))) {
if (res.getMediaType() != null && res.getMediaType().getName().startsWith("image")) {
coverImage = res;
break;
}
}
}
}
if (coverImage == null) {
if (coverData == null) {
log.warn("No cover image found in EPUB '{}'", bookEntity.getFileName());
return false;
}
boolean saved = saveCoverImage(coverImage, bookEntity.getId());
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
bookMetadataRepository.save(bookEntity.getMetadata());
boolean saved;
try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) {
BufferedImage originalImage = ImageIO.read(bais);
if (originalImage == null) {
log.warn("Cover image found but could not be decoded (possibly SVG or unsupported format) in EPUB '{}'", bookEntity.getFileName());
return false;
}
saved = fileService.saveCoverImages(originalImage, bookEntity.getId());
originalImage.flush();
}
if (saved) {
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
bookMetadataRepository.save(bookEntity.getMetadata());
}
return saved;
} catch (Exception e) {
@@ -127,7 +120,6 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
metadata.setLanguage(truncate((lang == null || "UND".equalsIgnoreCase(lang)) ? "en" : lang, 1000));
metadata.setAsin(truncate(epubMetadata.getAsin(), 20));
metadata.setPersonalRating(epubMetadata.getPersonalRating());
metadata.setAmazonRating(epubMetadata.getAmazonRating());
metadata.setAmazonReviewCount(epubMetadata.getAmazonReviewCount());
metadata.setGoodreadsId(truncate(epubMetadata.getGoodreadsId(), 100));
@@ -148,15 +140,4 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
bookCreatorService.addCategoriesToBook(validSubjects, bookEntity);
}
}
private boolean saveCoverImage(Resource coverImage, long bookId) throws IOException {
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(coverImage.getData()));
try {
return fileService.saveCoverImages(originalImage, bookId);
} finally {
if (originalImage != null) {
originalImage.flush(); // Release resources after processing
}
}
}
}
@@ -139,9 +139,6 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
if (StringUtils.isNotBlank(extracted.getIsbn13())) {
bookEntity.getMetadata().setIsbn13(extracted.getIsbn13());
}
if (extracted.getPersonalRating() != null) {
bookEntity.getMetadata().setPersonalRating(extracted.getPersonalRating());
}
if (extracted.getCategories() != null) {
bookCreatorService.addCategoriesToBook(extracted.getCategories(), bookEntity);
}
@@ -291,11 +291,9 @@ public class CbxConversionService {
private boolean isImageFile(String fileName) {
String lowerName = fileName.toLowerCase();
boolean isImage = lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") ||
return 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) {
@@ -348,7 +346,7 @@ public class CbxConversionService {
List<EpubContentFileGroup> contentGroups = new ArrayList<>();
if (!imagePaths.isEmpty()) {
addImageToZipFromPath(zipOut, COVER_IMAGE_PATH, imagePaths.get(0));
addImageToZipFromPath(zipOut, COVER_IMAGE_PATH, imagePaths.getFirst());
}
for (int i = 0; i < imagePaths.size(); i++) {
@@ -461,7 +459,7 @@ public class CbxConversionService {
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());
model.put("firstPageId", contentGroups.isEmpty() ? "" : "page_" + contentGroups.getFirst().contentKey());
String contentOpf = processTemplate("xml/content.opf.ftl", model);
@@ -0,0 +1,97 @@
package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity;
import com.adityachandel.booklore.model.entity.ShelfEntity;
import com.adityachandel.booklore.model.enums.ShelfType;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.KoboUserSettingsRepository;
import com.adityachandel.booklore.repository.ShelfRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class KoboAutoShelfService {
private final KoboUserSettingsRepository koboUserSettingsRepository;
private final ShelfRepository shelfRepository;
private final BookRepository bookRepository;
private final KoboCompatibilityService koboCompatibilityService;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void autoAddBookToKoboShelves(Long bookId) {
if (bookId == null) {
log.warn("Book ID is null for auto-add to Kobo shelf");
return;
}
BookEntity book = bookRepository.findById(bookId).orElse(null);
if (!isBookEligible(book)) {
return;
}
List<KoboUserSettingsEntity> eligibleUsers = koboUserSettingsRepository.findByAutoAddToShelfTrueAndSyncEnabledTrue();
if (eligibleUsers.isEmpty()) {
log.debug("No Kobo auto-add enabled users for book {}", book.getId());
return;
}
List<Long> userIds = eligibleUsers.stream()
.map(KoboUserSettingsEntity::getUserId)
.toList();
List<ShelfEntity> shelves = shelfRepository.findByUserIdInAndName(userIds, ShelfType.KOBO.getName());
Map<Long, ShelfEntity> shelfByUser = shelves
.stream()
.collect(Collectors.toMap(s -> s.getUser().getId(), s -> s));
boolean modified = false;
for (KoboUserSettingsEntity setting : eligibleUsers) {
ShelfEntity shelf = shelfByUser.get(setting.getUserId());
if (shelf == null) {
log.debug("User {} has auto-add enabled but no Kobo shelf exists", setting.getUserId());
continue;
}
if (book.getShelves().contains(shelf)) {
log.debug("Book {} already on Kobo shelf for user {}", book.getId(), setting.getUserId());
continue;
}
book.getShelves().add(shelf);
modified = true;
log.info("Auto-added book {} to Kobo shelf for user {}", book.getId(), setting.getUserId());
}
if (modified) {
bookRepository.save(book);
}
}
private boolean isBookEligible(BookEntity book) {
if (book == null) {
log.warn("Book not found for Kobo auto-add");
return false;
}
if (!koboCompatibilityService.isBookSupportedForKobo(book)) {
log.debug("Book {} is not Kobo-compatible, skipping", book.getId());
return false;
}
return true;
}
}
@@ -201,8 +201,7 @@ public class KoboReadingStateService {
return true;
}
boolean withinSyncBufferWindow = now.isBefore(statusSentTime.plusSeconds(STATUS_SYNC_BUFFER_SECONDS));
return withinSyncBufferWindow;
return now.isBefore(statusSentTime.plusSeconds(STATUS_SYNC_BUFFER_SECONDS));
}
private ReadStatus deriveStatusFromProgress(double progressPercent) {
@@ -7,6 +7,7 @@ import com.adityachandel.booklore.model.dto.Shelf;
import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest;
import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity;
import com.adityachandel.booklore.model.entity.ShelfEntity;
import com.adityachandel.booklore.model.enums.IconType;
import com.adityachandel.booklore.model.enums.ShelfType;
import com.adityachandel.booklore.repository.KoboUserSettingsRepository;
import com.adityachandel.booklore.service.ShelfService;
@@ -56,34 +57,31 @@ public class KoboSettingsService {
}
@Transactional
public void setSyncEnabled(boolean enabled) {
public KoboSyncSettings updateSettings(KoboSyncSettings settings) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
KoboUserSettingsEntity entity = repository.findByUserId(user.getId()).orElseThrow(() -> new IllegalStateException("Kobo settings not found for user"));
Shelf userKoboShelf = shelfService.getUserKoboShelf();
if (!enabled) {
if (userKoboShelf != null) {
shelfService.deleteShelf(userKoboShelf.getId());
}
} else {
ensureKoboShelfExists(user.getId());
}
entity.setSyncEnabled(enabled);
repository.save(entity);
}
KoboUserSettingsEntity entity = repository.findByUserId(user.getId()).orElseGet(() -> initDefaultSettings(user.getId()));
@Transactional
public KoboSyncSettings updateProgressThresholds(Float readingThreshold, Float finishedThreshold) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
KoboUserSettingsEntity entity = repository.findByUserId(user.getId())
.orElseGet(() -> initDefaultSettings(user.getId()));
if (readingThreshold != null) {
entity.setProgressMarkAsReadingThreshold(readingThreshold);
if (settings.isSyncEnabled() != entity.isSyncEnabled()) {
Shelf userKoboShelf = shelfService.getUserKoboShelf();
if (!settings.isSyncEnabled()) {
if (userKoboShelf != null) {
shelfService.deleteShelf(userKoboShelf.getId());
}
} else {
ensureKoboShelfExists(user.getId());
}
entity.setSyncEnabled(settings.isSyncEnabled());
}
if (finishedThreshold != null) {
entity.setProgressMarkAsFinishedThreshold(finishedThreshold);
if (settings.getProgressMarkAsReadingThreshold() != null) {
entity.setProgressMarkAsReadingThreshold(settings.getProgressMarkAsReadingThreshold());
}
if (settings.getProgressMarkAsFinishedThreshold() != null) {
entity.setProgressMarkAsFinishedThreshold(settings.getProgressMarkAsFinishedThreshold());
}
entity.setAutoAddToShelf(settings.isAutoAddToShelf());
repository.save(entity);
return mapToDto(entity);
}
@@ -105,6 +103,7 @@ public class KoboSettingsService {
ShelfCreateRequest.builder()
.name(ShelfType.KOBO.getName())
.icon(ShelfType.KOBO.getIcon())
.iconType(IconType.PRIME_NG)
.build()
);
}
@@ -122,6 +121,7 @@ public class KoboSettingsService {
dto.setSyncEnabled(entity.isSyncEnabled());
dto.setProgressMarkAsReadingThreshold(entity.getProgressMarkAsReadingThreshold());
dto.setProgressMarkAsFinishedThreshold(entity.getProgressMarkAsFinishedThreshold());
dto.setAutoAddToShelf(entity.isAutoAddToShelf());
return dto;
}
}
@@ -8,6 +8,7 @@ import com.adityachandel.booklore.model.enums.LibraryScanMode;
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.kobo.KoboAutoShelfService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@@ -22,6 +23,7 @@ public class FileAsBookProcessor implements LibraryFileProcessor {
private final BookEventBroadcaster bookEventBroadcaster;
private final BookFileProcessorRegistry processorRegistry;
private final KoboAutoShelfService koboAutoShelfService;
@Override
public LibraryScanMode getScanMode() {
@@ -32,17 +34,22 @@ public class FileAsBookProcessor implements LibraryFileProcessor {
@Transactional
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
for (LibraryFile libraryFile : libraryFiles) {
log.info("Processing file: {}", libraryFile.getFileName());
processFileWithErrorHandling(libraryFile);
}
log.info("Finished processing library '{}'", libraryEntity.getName());
}
private void processFileWithErrorHandling(LibraryFile libraryFile) {
log.info("Processing file: {}", libraryFile.getFileName());
try {
FileProcessResult result = processLibraryFile(libraryFile);
if (result != null) {
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
log.debug("Processed file: {}", libraryFile.getFileName());
koboAutoShelfService.autoAddBookToKoboShelves(result.getBook().getId());
}
} catch (Exception e) {
log.error("Failed to process file '{}': {}", libraryFile.getFileName(), e.getMessage());
}
log.info("Finished processing library '{}'", libraryEntity.getName());
}
@Transactional
@@ -34,6 +34,7 @@ public class LibraryFileHelper {
try (Stream<Path> stream = Files.walk(libraryPath, FileVisitOption.FOLLOW_LINKS)) {
return stream.filter(Files::isRegularFile)
.filter(path -> !FileUtils.shouldIgnore(path))
.map(fullPath -> {
String fileName = fullPath.getFileName().toString();
Optional<BookFileExtension> bookExtension = BookFileExtension.fromFileName(fileName);
@@ -51,7 +52,6 @@ public class LibraryFileHelper {
.build();
})
.filter(Objects::nonNull)
.filter(file -> !file.getFileName().startsWith("."))
.toList();
}
}
@@ -71,6 +71,7 @@ public class LibraryService {
library.setName(request.getName());
library.setIcon(request.getIcon());
library.setIconType(request.getIconType());
library.setWatch(request.isWatch());
if (request.getScanMode() != null) {
library.setScanMode(request.getScanMode());
@@ -149,6 +150,7 @@ public class LibraryService {
.collect(Collectors.toList())
)
.icon(request.getIcon())
.iconType(request.getIconType())
.watch(request.isWatch())
.scanMode(request.getScanMode() != null ? request.getScanMode() : LibraryScanMode.FILE_AS_BOOK)
.defaultBookFormat(request.getDefaultBookFormat())
@@ -74,8 +74,6 @@ 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);
@@ -84,14 +82,14 @@ public class BookMetadataUpdater {
return;
}
if (metadata.areAllFieldsLocked()) {
// If all fields are locked we must allow unlocking, hasValueChanges will be false
if (metadata.areAllFieldsLocked() && hasValueChanges) {
log.warn("All fields are locked for book ID {}. Skipping update.", bookId);
return;
}
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
boolean writeToFile = settings.isSaveToOriginalFile();
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
BookFileType bookType = bookEntity.getBookType();
boolean hasValueChangesForFileWrite = MetadataChangeDetector.hasValueChangesForFileWrite(newMetadata, metadata, clearFlags);
@@ -103,6 +101,7 @@ public class BookMetadataUpdater {
updateTagsIfNeeded(newMetadata, metadata, clearFlags, mergeTags, replaceMode);
bookReviewUpdateService.updateBookReviews(newMetadata, metadata, clearFlags, mergeCategories);
updateThumbnailIfNeeded(bookId, newMetadata, metadata, updateThumbnail);
updateLocks(newMetadata, metadata);
bookRepository.save(bookEntity);
@@ -164,7 +163,6 @@ public class BookMetadataUpdater {
handleFieldUpdate(e.getGoogleIdLocked(), clear.isGoogleId(), m.getGoogleId(), v -> e.setGoogleId(nullIfBlank(v)), e::getGoogleId, replaceMode);
handleFieldUpdate(e.getPageCountLocked(), clear.isPageCount(), m.getPageCount(), e::setPageCount, e::getPageCount, replaceMode);
handleFieldUpdate(e.getLanguageLocked(), clear.isLanguage(), m.getLanguage(), v -> e.setLanguage(nullIfBlank(v)), e::getLanguage, replaceMode);
handleFieldUpdate(e.getPersonalRatingLocked(), clear.isPersonalRating(), m.getPersonalRating(), e::setPersonalRating, e::getPersonalRating, replaceMode);
handleFieldUpdate(e.getAmazonRatingLocked(), clear.isAmazonRating(), m.getAmazonRating(), e::setAmazonRating, e::getAmazonRating, replaceMode);
handleFieldUpdate(e.getAmazonReviewCountLocked(), clear.isAmazonReviewCount(), m.getAmazonReviewCount(), e::setAmazonReviewCount, e::getAmazonReviewCount, replaceMode);
handleFieldUpdate(e.getGoodreadsRatingLocked(), clear.isGoodreadsRating(), m.getGoodreadsRating(), e::setGoodreadsRating, e::getGoodreadsRating, replaceMode);
@@ -226,11 +224,14 @@ public class BookMetadataUpdater {
if (replaceAll) {
if (!merge) e.getAuthors().clear();
e.getAuthors().addAll(newAuthors);
e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
} else if (replaceMissing && e.getAuthors().isEmpty()) {
e.getAuthors().addAll(newAuthors);
e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
} else if (replaceMode == null) {
if (!merge) e.getAuthors().clear();
e.getAuthors().addAll(newAuthors);
e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
}
}
@@ -377,7 +378,6 @@ public class BookMetadataUpdater {
Pair.of(m.getGoogleIdLocked(), e::setGoogleIdLocked),
Pair.of(m.getPageCountLocked(), e::setPageCountLocked),
Pair.of(m.getLanguageLocked(), e::setLanguageLocked),
Pair.of(m.getPersonalRatingLocked(), e::setPersonalRatingLocked),
Pair.of(m.getAmazonRatingLocked(), e::setAmazonRatingLocked),
Pair.of(m.getAmazonReviewCountLocked(), e::setAmazonReviewCountLocked),
Pair.of(m.getGoodreadsRatingLocked(), e::setGoodreadsRatingLocked),
@@ -64,15 +64,14 @@ public class DuckDuckGoCoverService implements BookCoverProvider {
siteFilteredImages = siteFilteredImages.subList(0, 7);
}
String generalQuery = searchTerm;
String encodedGeneralQuery = URLEncoder.encode(generalQuery, StandardCharsets.UTF_8);
String encodedGeneralQuery = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8);
String generalUrl = SEARCH_BASE_URL + encodedGeneralQuery + SEARCH_PARAMS;
Document generalDoc = getDocument(generalUrl);
Matcher generalMatcher = tokenPattern.matcher(generalDoc.html());
List<CoverImage> generalBookImages = new ArrayList<>();
if (generalMatcher.find()) {
String generalSearchToken = generalMatcher.group(1);
generalBookImages = fetchImagesFromApi(generalQuery, generalSearchToken);
generalBookImages = fetchImagesFromApi(searchTerm, generalSearchToken);
generalBookImages.removeIf(dto -> dto.getWidth() < 350);
generalBookImages.removeIf(dto -> dto.getWidth() >= dto.getHeight());
Set<String> siteUrls = siteFilteredImages.stream().map(CoverImage::getUrl).collect(Collectors.toSet());
@@ -112,6 +112,7 @@ public class MetadataManagementService {
for (BookMetadataEntity metadata : booksWithOldAuthor) {
metadata.getAuthors().remove(oldAuthor);
metadata.getAuthors().addAll(targetAuthors);
metadata.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
}
bookMetadataRepository.saveAll(booksWithOldAuthor);
@@ -41,39 +41,41 @@ public class MetadataMatchService {
float score = 0f;
if (isPresent(metadata.getTitle())) score += weights.getTitle();
if (isPresent(metadata.getSubtitle())) score += weights.getSubtitle();
if (isPresent(metadata.getDescription())) score += weights.getDescription();
if (hasContent(metadata.getAuthors())) score += weights.getAuthors();
if (isPresent(metadata.getPublisher())) score += weights.getPublisher();
if (metadata.getPublishedDate() != null) score += weights.getPublishedDate();
if (isPresent(metadata.getSeriesName())) score += weights.getSeriesName();
if (metadata.getSeriesNumber() != null && metadata.getSeriesNumber() > 0) score += weights.getSeriesNumber();
if (metadata.getSeriesTotal() != null && metadata.getSeriesTotal() > 0) score += weights.getSeriesTotal();
if (isPresent(metadata.getIsbn13())) score += weights.getIsbn13();
if (isPresent(metadata.getIsbn10())) score += weights.getIsbn10();
if (isPresent(metadata.getLanguage())) score += weights.getLanguage();
if (metadata.getPageCount() != null && metadata.getPageCount() > 0) score += weights.getPageCount();
if (hasContent(metadata.getCategories())) score += weights.getCategories();
if (isPositive(metadata.getAmazonRating())) score += weights.getAmazonRating();
if (isPositive(metadata.getAmazonReviewCount())) score += weights.getAmazonReviewCount();
if (isPositive(metadata.getGoodreadsRating())) score += weights.getGoodreadsRating();
if (isPositive(metadata.getGoodreadsReviewCount())) score += weights.getGoodreadsReviewCount();
if (isPositive(metadata.getHardcoverRating())) score += weights.getHardcoverRating();
if (isPositive(metadata.getHardcoverReviewCount())) score += weights.getHardcoverReviewCount();
if (isPresent(metadata.getTitle(), metadata.getTitleLocked())) score += weights.getTitle();
if (isPresent(metadata.getSubtitle(), metadata.getSubtitleLocked())) score += weights.getSubtitle();
if (isPresent(metadata.getDescription(), metadata.getDescriptionLocked())) score += weights.getDescription();
if (hasContent(metadata.getAuthors(), metadata.getAuthorsLocked())) score += weights.getAuthors();
if (isPresent(metadata.getPublisher(), metadata.getPublisherLocked())) score += weights.getPublisher();
if (metadata.getPublishedDate() != null || Boolean.TRUE.equals(metadata.getPublishedDateLocked())) score += weights.getPublishedDate();
if (isPresent(metadata.getSeriesName(), metadata.getSeriesNameLocked())) score += weights.getSeriesName();
if ((metadata.getSeriesNumber() != null && metadata.getSeriesNumber() > 0) || Boolean.TRUE.equals(metadata.getSeriesNumberLocked())) score += weights.getSeriesNumber();
if ((metadata.getSeriesTotal() != null && metadata.getSeriesTotal() > 0) || Boolean.TRUE.equals(metadata.getSeriesTotalLocked())) score += weights.getSeriesTotal();
if (isPresent(metadata.getIsbn13(), metadata.getIsbn13Locked())) score += weights.getIsbn13();
if (isPresent(metadata.getIsbn10(), metadata.getIsbn10Locked())) score += weights.getIsbn10();
if (isPresent(metadata.getLanguage(), metadata.getLanguageLocked())) score += weights.getLanguage();
if ((metadata.getPageCount() != null && metadata.getPageCount() > 0) || Boolean.TRUE.equals(metadata.getPageCountLocked())) score += weights.getPageCount();
if (hasContent(metadata.getCategories(), metadata.getCategoriesLocked())) score += weights.getCategories();
if (isPositive(metadata.getAmazonRating(), metadata.getAmazonRatingLocked())) score += weights.getAmazonRating();
if (isPositive(metadata.getAmazonReviewCount(), metadata.getAmazonReviewCountLocked())) score += weights.getAmazonReviewCount();
if (isPositive(metadata.getGoodreadsRating(), metadata.getGoodreadsRatingLocked())) score += weights.getGoodreadsRating();
if (isPositive(metadata.getGoodreadsReviewCount(), metadata.getGoodreadsReviewCountLocked())) score += weights.getGoodreadsReviewCount();
if (isPositive(metadata.getHardcoverRating(), metadata.getHardcoverRatingLocked())) score += weights.getHardcoverRating();
if (isPositive(metadata.getHardcoverReviewCount(), metadata.getHardcoverReviewCountLocked())) score += weights.getHardcoverReviewCount();
return (score / totalWeight) * 100f;
}
private boolean isPresent(String value) {
return value != null && !value.isBlank();
private boolean isPresent(String value, Boolean locked) {
return (value != null && !value.isBlank()) || Boolean.TRUE.equals(locked);
}
private boolean hasContent(Iterable<?> iterable) {
return iterable != null && iterable.iterator().hasNext();
private boolean hasContent(Iterable<?> iterable, Boolean locked) {
return (iterable != null && iterable.iterator().hasNext()) || Boolean.TRUE.equals(locked);
}
private boolean isPositive(Number number) {
return number != null && number.doubleValue() > 0;
private boolean isPositive(Number number, Boolean locked) {
return (number != null && number.doubleValue() > 0) || Boolean.TRUE.equals(locked);
}
}
}
@@ -27,17 +27,28 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
@Slf4j
@Component
public class EpubMetadataExtractor implements FileMetadataExtractor {
private static final Pattern YEAR_ONLY_PATTERN = Pattern.compile("^\\d{4}$");
@Override
public byte[] extractCover(File epubFile) {
try (FileInputStream fis = new FileInputStream(epubFile)) {
Book epub = new EpubReader().readEpub(fis);
io.documentnode.epub4j.domain.Resource coverImage = epub.getCoverImage();
if (coverImage == null) {
String coverHref = findCoverImageHrefInOpf(epubFile);
if (coverHref != null) {
byte[] data = extractFileFromZip(epubFile, coverHref);
if (data != null) return data;
}
}
if (coverImage == null) {
for (io.documentnode.epub4j.domain.Resource res : epub.getResources().getAll()) {
String id = res.getId();
@@ -154,10 +165,6 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
}
}
if ("calibre:rating".equals(name) || "booklore:personal_rating".equals(prop)) {
safeParseDouble(content, builderMeta::personalRating);
}
switch (prop) {
case "booklore:asin" -> builderMeta.asin(content);
case "booklore:goodreads_id" -> builderMeta.goodreadsId(content);
@@ -169,6 +176,7 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
}
case "creator" -> authors.add(text);
case "subject" -> categories.add(text);
case "description" -> builderMeta.description(text);
case "publisher" -> builderMeta.publisher(text);
case "language" -> builderMeta.language(text);
case "identifier" -> {
@@ -262,6 +270,16 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
private LocalDate parseDate(String value) {
if (StringUtils.isBlank(value)) return null;
value = value.trim();
// Check for year-only format first (e.g., "2024") - common in EPUB metadata
if (YEAR_ONLY_PATTERN.matcher(value).matches()) {
int year = Integer.parseInt(value);
if (year >= 1 && year <= 9999) {
return LocalDate.of(year, 1, 1);
}
}
try {
return LocalDate.parse(value);
} catch (Exception ignored) {
@@ -272,12 +290,93 @@ public class EpubMetadataExtractor implements FileMetadataExtractor {
} catch (Exception ignored) {
}
try {
return LocalDate.parse(value.substring(0, 10));
} catch (Exception ignored) {
// Try parsing first 10 characters for ISO date format with extra content
if (value.length() >= 10) {
try {
return LocalDate.parse(value.substring(0, 10));
} catch (Exception ignored) {
}
}
log.warn("Failed to parse date from string: {}", value);
return null;
}
private String findCoverImageHrefInOpf(File epubFile) {
try (ZipFile zip = new ZipFile(epubFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder builder = dbf.newDocumentBuilder();
FileHeader containerHdr = zip.getFileHeader("META-INF/container.xml");
if (containerHdr == null) return null;
try (InputStream cis = zip.getInputStream(containerHdr)) {
Document containerDoc = builder.parse(cis);
NodeList roots = containerDoc.getElementsByTagName("rootfile");
if (roots.getLength() == 0) return null;
String opfPath = ((Element) roots.item(0)).getAttribute("full-path");
if (StringUtils.isBlank(opfPath)) return null;
FileHeader opfHdr = zip.getFileHeader(opfPath);
if (opfHdr == null) return null;
try (InputStream in = zip.getInputStream(opfHdr)) {
Document doc = builder.parse(in);
NodeList manifestItems = doc.getElementsByTagName("item");
for (int i = 0; i < manifestItems.getLength(); i++) {
Element item = (Element) manifestItems.item(i);
String properties = item.getAttribute("properties");
if (properties != null && properties.contains("cover-image")) {
String href = item.getAttribute("href");
return resolvePath(opfPath, href);
}
}
}
}
} catch (Exception e) {
log.debug("Failed to find cover image in OPF: {}", e.getMessage());
}
return null;
}
private String resolvePath(String opfPath, String href) {
if (href == null || href.isEmpty()) return null;
// If href is absolute within the zip (starts with /), return it without leading /
if (href.startsWith("/")) return href.substring(1);
int lastSlash = opfPath.lastIndexOf('/');
String basePath = (lastSlash == -1) ? "" : opfPath.substring(0, lastSlash + 1);
String combined = basePath + href;
// Normalize path components to handle ".." and "."
java.util.LinkedList<String> parts = new java.util.LinkedList<>();
for (String part : combined.split("/")) {
if ("..".equals(part)) {
if (!parts.isEmpty()) parts.removeLast();
} else if (!".".equals(part) && !part.isEmpty()) {
parts.add(part);
}
}
return String.join("/", parts);
}
private byte[] extractFileFromZip(File epubFile, String path) {
try (ZipFile zip = new ZipFile(epubFile)) {
FileHeader header = zip.getFileHeader(path);
if (header == null) return null;
try (InputStream is = zip.getInputStream(header)) {
return is.readAllBytes();
}
} catch (Exception e) {
log.warn("Failed to extract file {} from zip", path);
return null;
}
}
}
@@ -234,11 +234,6 @@ public class PdfMetadataExtractor implements FileMetadataExtractor {
private void extractCalibreMetadata(XPath xpath, Document doc, BookMetadata.BookMetadataBuilder builder) {
try {
String rating = xpath.evaluate("//calibre:rating/text()", doc);
if (StringUtils.isNotBlank(rating)) {
builder.personalRating(Double.valueOf(rating));
}
String series = xpath.evaluate("//calibre:series/rdf:value/text()", doc);
if (StringUtils.isNotBlank(series)) {
builder.seriesName(series);
@@ -38,10 +38,11 @@ public class AmazonBookParser implements BookParser {
private static final Pattern SERIES_FORMAT_PATTERN = Pattern.compile("Book \\d+ of \\d+");
private static final Pattern SERIES_FORMAT_WITH_DECIMAL_PATTERN = Pattern.compile("Book \\d+(\\.\\d+)? of \\d+");
private static final Pattern PARENTHESES_WITH_WHITESPACE_PATTERN = Pattern.compile("\\s*\\(.*?\\)");
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-zA-Z0-9]");
private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^\\p{L}\\p{M}0-9]");
private static final Pattern DP_SEPARATOR_PATTERN = Pattern.compile("/dp/");
// Pattern to extract country and date from strings like "Reviewed in ... on ..."
private static final Pattern REVIEWED_IN_ON_PATTERN = Pattern.compile("Reviewed in (.+?) on (.+)");
// Pattern to extract country and date from strings like "Reviewed in ... on ..." or Japanese format
private static final Pattern REVIEWED_IN_ON_PATTERN = Pattern.compile("(?i)(?:Reviewed in|Rezension aus|Beoordeeld in|Recensie uit|Commenté en|Recensito in|Revisado en)\\s+(.+?)\\s+(?:on|vom|op|le|il|el)\\s+(.+)");
private static final Pattern JAPANESE_REVIEW_DATE_PATTERN = Pattern.compile("(\\d{4}年\\d{1,2}月\\d{1,2}日).+");
private static final Map<String, LocaleInfo> DOMAIN_LOCALE_MAP = Map.ofEntries(
Map.entry("com", new LocaleInfo("en-US,en;q=0.9", Locale.US)),
@@ -58,7 +59,14 @@ public class AmazonBookParser implements BookParser {
Map.entry("com.mx", new LocaleInfo("en-US,en;q=0.9,es;q=0.8", new Locale.Builder().setLanguage("es").setRegion("MX").build())),
Map.entry("nl", new LocaleInfo("en-GB,en;q=0.9,nl;q=0.8", new Locale.Builder().setLanguage("nl").setRegion("NL").build())),
Map.entry("se", new LocaleInfo("en-GB,en;q=0.9,sv;q=0.8", new Locale.Builder().setLanguage("sv").setRegion("SE").build())),
Map.entry("pl", new LocaleInfo("en-GB,en;q=0.9,pl;q=0.8", new Locale.Builder().setLanguage("pl").setRegion("PL").build()))
Map.entry("pl", new LocaleInfo("en-GB,en;q=0.9,pl;q=0.8", new Locale.Builder().setLanguage("pl").setRegion("PL").build())),
Map.entry("ae", new LocaleInfo("en-US,en;q=0.9,ar;q=0.8", new Locale.Builder().setLanguage("en").setRegion("AE").build())),
Map.entry("sa", new LocaleInfo("en-US,en;q=0.9,ar;q=0.8", new Locale.Builder().setLanguage("en").setRegion("SA").build())),
Map.entry("cn", new LocaleInfo("zh-CN,zh;q=0.9", Locale.CHINA)),
Map.entry("sg", new LocaleInfo("en-GB,en;q=0.9", new Locale.Builder().setLanguage("en").setRegion("SG").build())),
Map.entry("tr", new LocaleInfo("en-GB,en;q=0.9,tr;q=0.8", new Locale.Builder().setLanguage("tr").setRegion("TR").build())),
Map.entry("eg", new LocaleInfo("en-US,en;q=0.9,ar;q=0.8", new Locale.Builder().setLanguage("en").setRegion("EG").build())),
Map.entry("com.be", new LocaleInfo("en-GB,en;q=0.9,fr;q=0.8,nl;q=0.8", new Locale.Builder().setLanguage("fr").setRegion("BE").build()))
);
private final AppSettingService appSettingService;
@@ -281,56 +289,104 @@ public class AmazonBookParser implements BookParser {
return url;
}
private String getTitle(Document doc) {
Element titleElement = doc.getElementById("productTitle");
if (titleElement != null) {
String fullTitle = titleElement.text();
return fullTitle.split(":", 2)[0].trim();
private String getTextBySelectors(Document doc, String... selectors) {
for (String selector : selectors) {
try {
Element element = doc.selectFirst(selector);
if (element != null && !element.text().isBlank()) {
return element.text().trim();
}
} catch (Exception e) {
log.debug("Failed to extract text with selector '{}': {}", selector, e.getMessage());
}
}
log.warn("Failed to parse title: Element not found.");
return null;
}
private String getTitle(Document doc) {
String title = getTextBySelectors(doc,
"#productTitle",
"#ebooksProductTitle",
"h1#title",
"span#productTitle"
);
if (title != null) {
return title.split(":", 2)[0].trim();
}
log.warn("Failed to parse title: No suitable element found.");
return null;
}
private String getSubtitle(Document doc) {
Element titleElement = doc.getElementById("productTitle");
if (titleElement != null) {
String fullTitle = titleElement.text();
String[] parts = fullTitle.split(":", 2);
String title = getTextBySelectors(doc,
"#productTitle",
"#ebooksProductTitle",
"h1#title",
"span#productTitle"
);
if (title != null) {
String[] parts = title.split(":", 2);
if (parts.length > 1) {
return parts[1].trim();
}
}
log.warn("Failed to parse subtitle: Element not found.");
log.warn("Failed to parse subtitle: No suitable element found.");
return null;
}
private Set<String> getAuthors(Document doc) {
Set<String> authors = new HashSet<>();
try {
Element bylineDiv = doc.select("#bylineInfo_feature_div").first();
// Primary strategy: #bylineInfo_feature_div .author a
Element bylineDiv = doc.selectFirst("#bylineInfo_feature_div");
if (bylineDiv != null) {
return bylineDiv
.select(".author a")
.stream()
.map(Element::text)
.collect(Collectors.toSet());
authors.addAll(bylineDiv.select(".author a").stream().map(Element::text).collect(Collectors.toSet()));
}
// Fallback: #bylineInfo .author a
if (authors.isEmpty()) {
Element bylineInfo = doc.selectFirst("#bylineInfo");
if (bylineInfo != null) {
authors.addAll(bylineInfo.select(".author a").stream().map(Element::text).collect(Collectors.toSet()));
}
}
// Fallback: simple .author a check (broadest)
if (authors.isEmpty()) {
authors.addAll(doc.select(".author a").stream().map(Element::text).collect(Collectors.toSet()));
}
if (authors.isEmpty()) {
log.warn("Failed to parse authors: No author elements found.");
}
log.warn("Failed to parse authors: Byline element not found.");
} catch (Exception e) {
log.warn("Failed to parse authors: {}", e.getMessage());
}
return Set.of();
return authors;
}
private String getDescription(Document doc) {
try {
// Primary: data-a-expander-name
Elements descriptionElements = doc.select("[data-a-expander-name=book_description_expander] .a-expander-content");
if (!descriptionElements.isEmpty()) {
String html = descriptionElements.getFirst().html();
html = html.replace("\n", "<br>");
return html;
}
return null;
// Fallback: #bookDescription_feature_div noscript (often contains the clean HTML)
Element noscriptDesc = doc.selectFirst("#bookDescription_feature_div noscript");
if (noscriptDesc != null) {
return noscriptDesc.html(); // usually clean HTML inside noscript
}
// Fallback: div.product-description
Element simpleDesc = doc.selectFirst("div.product-description");
if (simpleDesc != null) {
return simpleDesc.html();
}
} catch (Exception e) {
log.warn("Failed to parse description: {}", e.getMessage());
}
@@ -338,29 +394,41 @@ public class AmazonBookParser implements BookParser {
}
private String getIsbn10(Document doc) {
// Strategy 1: RPI attribute
try {
Element isbn10Element = doc.select("#rpi-attribute-book_details-isbn10 .rpi-attribute-value span").first();
if (isbn10Element != null) {
String rawIsbn = isbn10Element.text();
return ParserUtils.cleanIsbn(rawIsbn);
return ParserUtils.cleanIsbn(isbn10Element.text());
}
log.warn("Failed to parse isbn10: Element not found.");
} catch (Exception e) {
log.warn("Failed to parse isbn10: {}", e.getMessage());
log.debug("RPI ISBN-10 extraction failed: {}", e.getMessage());
}
// Strategy 2: Detail bullets
try {
return extractFromDetailBullets(doc, "ISBN-10");
} catch (Exception e) {
log.warn("DetailBullets ISBN-10 extraction failed: {}", e.getMessage());
}
return null;
}
private String getIsbn13(Document doc) {
// Strategy 1: RPI attribute
try {
Element isbn13Element = doc.select("#rpi-attribute-book_details-isbn13 .rpi-attribute-value span").first();
if (isbn13Element != null) {
String rawIsbn = isbn13Element.text();
return ParserUtils.cleanIsbn(rawIsbn);
return ParserUtils.cleanIsbn(isbn13Element.text());
}
log.warn("Failed to parse isbn13: Element not found.");
} catch (Exception e) {
log.warn("Failed to parse isbn13: {}", e.getMessage());
log.debug("RPI ISBN-13 extraction failed: {}", e.getMessage());
}
// Strategy 2: Detail bullets
try {
return extractFromDetailBullets(doc, "ISBN-13");
} catch (Exception e) {
log.warn("DetailBullets ISBN-13 extraction failed: {}", e.getMessage());
}
return null;
}
@@ -372,16 +440,29 @@ public class AmazonBookParser implements BookParser {
Elements listItems = featureElement.select("li");
for (Element listItem : listItems) {
Element boldText = listItem.selectFirst("span.a-text-bold");
if (boldText != null && boldText.text().contains("Publisher")) {
Element publisherSpan = boldText.nextElementSibling();
if (publisherSpan != null) {
String fullPublisher = publisherSpan.text().trim();
return PARENTHESES_WITH_WHITESPACE_PATTERN.matcher(fullPublisher.split(";")[0].trim()).replaceAll("").trim();
if (boldText != null) {
String header = boldText.text().toLowerCase();
// Check against known localized "Publisher" labels
if (header.contains("publisher") ||
header.contains("herausgeber") ||
header.contains("éditeur") ||
header.contains("editoriale") ||
header.contains("editorial") ||
header.contains("uitgever") ||
header.contains("wydawca") ||
header.contains("出版社") || // Japanese
header.contains("editora")) {
Element publisherSpan = boldText.nextElementSibling();
if (publisherSpan != null) {
String fullPublisher = publisherSpan.text().trim();
return PARENTHESES_WITH_WHITESPACE_PATTERN.matcher(fullPublisher.split(";")[0].trim()).replaceAll("").trim();
}
}
}
}
} else {
log.warn("Failed to parse publisher: Element 'detailBullets_feature_div' not found.");
log.debug("Failed to parse publisher: Element 'detailBullets_feature_div' not found.");
}
} catch (Exception e) {
log.warn("Failed to parse publisher: {}", e.getMessage());
@@ -390,19 +471,63 @@ public class AmazonBookParser implements BookParser {
}
private LocalDate getPublicationDate(Document doc) {
// Strategy 1: RPI attribute
try {
Element publicationDateElement = doc.select("#rpi-attribute-book_details-publication_date .rpi-attribute-value span").first();
if (publicationDateElement != null) {
String dateText = publicationDateElement.text();
LocalDate parsedDate = parseAmazonDate(dateText);
if (parsedDate == null) {
log.warn("Failed to parse publication date: '{}', returning null", dateText);
}
return parsedDate;
if (parsedDate != null) return parsedDate;
}
log.warn("Failed to parse publishedDate: Element not found.");
} catch (Exception e) {
log.warn("Failed to parse publishedDate: {}", e.getMessage());
log.debug("RPI Publication Date extraction failed: {}", e.getMessage());
}
// Strategy 2: Detail bullets (look for specific date patterns in values)
try {
Element featureElement = doc.getElementById("detailBullets_feature_div");
if (featureElement != null) {
Elements listItems = featureElement.select("li");
for (Element listItem : listItems) {
// We look for any value that parses as a date, as the label varies wildly ("Publication date", "Seitenzahl"?? no, "Erscheinungsdatum", etc.)
// But usually it's associated with "Publisher" line sometimes: "Publisher: XYZ (Jan 1, 2020)"
Element boldText = listItem.selectFirst("span.a-text-bold");
Element valueSpan = boldText != null ? boldText.nextElementSibling() : null;
if (valueSpan != null) {
// Sometimes date is inside the value span, e.g. "January 1, 2020"
LocalDate d = parseAmazonDate(valueSpan.text());
if (d != null) return d;
// Sometimes it's in parentheses after publisher: "Publisher: Name (January 1, 2020)"
Matcher matcher = Pattern.compile("\\((.*?)\\)").matcher(valueSpan.text());
while (matcher.find()) {
LocalDate pd = parseAmazonDate(matcher.group(1));
if (pd != null) return pd;
}
}
}
}
} catch (Exception e) {
log.warn("DetailBullets Publication Date extraction failed: {}", e.getMessage());
}
return null;
}
private String extractFromDetailBullets(Document doc, String keyPart) {
Element featureElement = doc.getElementById("detailBullets_feature_div");
if (featureElement != null) {
Elements listItems = featureElement.select("li");
for (Element listItem : listItems) {
Element boldText = listItem.selectFirst("span.a-text-bold");
if (boldText != null && boldText.text().contains(keyPart)) {
Element valueSpan = boldText.nextElementSibling();
if (valueSpan != null) {
return ParserUtils.cleanIsbn(valueSpan.text());
}
}
}
}
return null;
}
@@ -568,6 +693,13 @@ public class AmazonBookParser implements BookParser {
country = country.substring(4).trim();
}
datePart = matcher.group(2).trim();
} else {
// Try Japanese format
Matcher japaneseMatcher = JAPANESE_REVIEW_DATE_PATTERN.matcher(fullDateText);
if (japaneseMatcher.find()) {
datePart = japaneseMatcher.group(1);
country = "日本";
}
}
LocalDate localDate = parseReviewDate(datePart, localeInfo);
@@ -735,7 +867,11 @@ public class AmazonBookParser implements BookParser {
"MMM. d, yyyy",
"d MMM yyyy",
"d MMM. yyyy",
"d. MMM yyyy"
"d. MMM yyyy",
// Japanese date patterns
"yyyy/M/d",
"yyyy/MM/dd",
"yyyy年M月d日"
};
for (String pattern : patterns) {
@@ -198,51 +198,47 @@ public class CbxMetadataWriter implements MetadataWriter {
if (rarAvailable) {
tempDir = Files.createTempDirectory("cbx_rar_");
try {
// Extract entire RAR into a temp directory
try (Archive archive = new Archive(file)) {
for (FileHeader fh : archive.getFileHeaders()) {
String name = fh.getFileName();
if (name == null || name.isBlank()) continue;
if (!isSafeEntryName(name)) {
log.warn("Skipping unsafe RAR entry name: {}", name);
continue;
}
Path out = tempDir.resolve(name).normalize();
if (!out.startsWith(tempDir)) {
log.warn("Skipping traversal entry outside tempDir: {}", name);
continue;
}
if (fh.isDirectory()) {
Files.createDirectories(out);
} else {
Files.createDirectories(out.getParent());
try (OutputStream os = Files.newOutputStream(out, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
archive.extractFile(fh, os);
}
// Extract entire RAR into a temp directory
try (Archive archive = new Archive(file)) {
for (FileHeader fh : archive.getFileHeaders()) {
String name = fh.getFileName();
if (name == null || name.isBlank()) continue;
if (!isSafeEntryName(name)) {
log.warn("Skipping unsafe RAR entry name: {}", name);
continue;
}
Path out = tempDir.resolve(name).normalize();
if (!out.startsWith(tempDir)) {
log.warn("Skipping traversal entry outside tempDir: {}", name);
continue;
}
if (fh.isDirectory()) {
Files.createDirectories(out);
} else {
Files.createDirectories(out.getParent());
try (OutputStream os = Files.newOutputStream(out, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
archive.extractFile(fh, os);
}
}
}
}
// Write/replace ComicInfo.xml in extracted tree root
Path comicInfo = tempDir.resolve("ComicInfo.xml");
Files.write(comicInfo, xmlBytes);
// Write/replace ComicInfo.xml in extracted tree root
Path comicInfo = tempDir.resolve("ComicInfo.xml");
Files.write(comicInfo, xmlBytes);
// Rebuild RAR in-place (replace original file)
Path targetRar = file.toPath().toAbsolutePath().normalize();
String rarExec = isSafeExecutable(rarBin) ? rarBin : "rar"; // prefer validated path, then PATH lookup
ProcessBuilder pb = new ProcessBuilder(rarExec, "a", "-idq", "-ep1", "-ma5", targetRar.toString(), ".");
pb.directory(tempDir.toFile());
Process p = pb.start();
int code = p.waitFor();
if (code == 0) {
writeSucceeded = true;
return;
} else {
log.warn("RAR creation failed with exit code {}. Falling back to CBZ conversion for {}", code, file.getName());
}
} finally {
// tempDir cleanup will be handled in outer finally block
// Rebuild RAR in-place (replace original file)
Path targetRar = file.toPath().toAbsolutePath().normalize();
String rarExec = isSafeExecutable(rarBin) ? rarBin : "rar"; // prefer validated path, then PATH lookup
ProcessBuilder pb = new ProcessBuilder(rarExec, "a", "-idq", "-ep1", "-ma5", targetRar.toString(), ".");
pb.directory(tempDir.toFile());
Process p = pb.start();
int code = p.waitFor();
if (code == 0) {
writeSucceeded = true;
return;
} else {
log.warn("RAR creation failed with exit code {}. Falling back to CBZ conversion for {}", code, file.getName());
}
} else {
log.warn("`rar` binary not found. Falling back to CBZ conversion for {}", file.getName());
@@ -114,11 +114,6 @@ public class EpubMetadataWriter implements MetadataWriter {
replaceMetaElement(metadataElement, opfDoc, "calibre:series_index", formatted, hasChanges);
});
helper.copyPersonalRating(clear != null && clear.isPersonalRating(), val -> {
String formatted = val != null ? String.format("%.1f", val) : null;
replaceMetaElement(metadataElement, opfDoc, "calibre:rating", formatted, hasChanges);
});
List<String> schemes = List.of("AMAZON", "GOOGLE", "GOODREADS", "HARDCOVER", "ISBN");
for (String scheme : schemes) {
@@ -112,13 +112,6 @@ public class MetadataCopyHelper {
}
}
public void copyPersonalRating(boolean clear, Consumer<Double> consumer) {
if (!isLocked(metadata.getPersonalRatingLocked())) {
if (clear) consumer.accept(null);
else if (metadata.getPersonalRating() != null) consumer.accept(metadata.getPersonalRating());
}
}
public void copyGoodreadsId(boolean clear, Consumer<String> consumer) {
if (!isLocked(metadata.getGoodreadsIdLocked())) {
if (clear) consumer.accept(null);
@@ -200,11 +200,6 @@ public class PdfMetadataWriter implements MetadataWriter {
calibreDescription.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:calibreSI", "http://calibre-ebook.com/xmp-namespace-series-index");
calibreDescription.setAttributeNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:about", "");
helper.copyPersonalRating(clear != null && clear.isPersonalRating(), rating -> {
String value = (rating != null) ? String.valueOf((int) Math.round(rating)) : "";
calibreDescription.appendChild(createSimpleElement(doc, "calibre:rating", value));
});
helper.copySeriesName(clear != null && clear.isSeriesName(), series -> {
Element seriesElem = doc.createElementNS("http://calibre-ebook.com/xmp-namespace", "calibre:series");
seriesElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:calibreSI", "http://calibre-ebook.com/xmp-namespace-series-index");
@@ -3,16 +3,20 @@ package com.adityachandel.booklore.service.migration;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.repository.AppMigrationRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.util.BookUtils;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
@@ -23,6 +27,7 @@ import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
@@ -39,6 +44,49 @@ public class AppMigrationService {
private AppProperties appProperties;
private FileService fileService;
@Transactional
public void populateSearchTextOnce() {
if (migrationRepository.existsById("populateSearchText")) return;
int batchSize = 1000;
int processedCount = 0;
int offset = 0;
while (true) {
List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(offset, batchSize);
if (bookBatch.isEmpty()) break;
List<Long> bookIds = bookBatch.stream().map(BookEntity::getId).toList();
List<BookEntity> books = bookRepository.findBooksWithMetadataAndAuthors(bookIds);
for (BookEntity book : books) {
BookMetadataEntity m = book.getMetadata();
if (m != null) {
try {
m.setSearchText(BookUtils.buildSearchText(m));
} catch (Exception ex) {
log.warn("Failed to build search text for book {}: {}", book.getId(), ex.getMessage());
}
}
}
bookRepository.saveAll(books);
processedCount += books.size();
offset += batchSize;
log.info("Migration progress: {} books processed", processedCount);
if (bookBatch.size() < batchSize) break;
}
log.info("Migration 'populateSearchText' completed. Total books processed: {}", processedCount);
migrationRepository.save(new AppMigrationEntity(
"populateSearchText",
LocalDateTime.now(),
"Populate search_text column for all books"
));
}
@Transactional
public void populateMissingFileSizesOnce() {
if (migrationRepository.existsById("populateFileSizes")) {
@@ -194,4 +242,51 @@ public class AppMigrationService {
log.info("Completed migration: populateCoversAndResizeThumbnails in {} ms", elapsedMs);
}
@Transactional
public void moveIconsToDataFolder() {
if (migrationRepository.existsById("moveIconsToDataFolder")) return;
long start = System.nanoTime();
log.info("Starting migration: moveIconsToDataFolder");
try {
String targetFolder = fileService.getIconsSvgFolder();
Path targetDir = Paths.get(targetFolder);
Files.createDirectories(targetDir);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:static/images/icons/svg/*.svg");
int copiedCount = 0;
for (Resource resource : resources) {
String filename = resource.getFilename();
if (filename == null) continue;
Path targetFile = targetDir.resolve(filename);
try (var inputStream = resource.getInputStream()) {
Files.copy(inputStream, targetFile, StandardCopyOption.REPLACE_EXISTING);
copiedCount++;
log.debug("Copied icon: {} to {}", filename, targetFile);
} catch (IOException e) {
log.error("Failed to copy icon: {}", filename, e);
}
}
log.info("Copied {} SVG icons from resources to data folder", copiedCount);
migrationRepository.save(new AppMigrationEntity(
"moveIconsToDataFolder",
LocalDateTime.now(),
"Move SVG icons from resources/static/images/icons/svg to data/icons/svg"
));
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
log.info("Completed migration: moveIconsToDataFolder in {} ms", elapsedMs);
} catch (IOException e) {
log.error("Error during migration moveIconsToDataFolder", e);
throw new UncheckedIOException(e);
}
}
}
@@ -17,5 +17,7 @@ public class AppMigrationStartup {
appMigrationService.populateMetadataScoresOnce();
appMigrationService.populateFileHashesOnce();
appMigrationService.populateCoversAndResizeThumbnails();
appMigrationService.populateSearchTextOnce();
appMigrationService.moveIconsToDataFolder();
}
}
@@ -8,7 +8,9 @@ import org.springframework.stereotype.Service;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Slf4j
@Service
@@ -21,6 +23,10 @@ public class MonitoringRegistrationService {
return monitoringService.isPathMonitored(path);
}
public boolean isLibraryMonitored(Long libraryId) {
return monitoringService.isLibraryMonitored(libraryId);
}
public void unregisterSpecificPath(Path path) {
monitoringService.unregisterPath(path);
}
@@ -42,6 +48,7 @@ public class MonitoringRegistrationService {
return;
}
try {
log.debug("Registering library paths for libraryId {} at {}", libraryId, libraryRoot);
monitoringService.registerPath(libraryRoot, libraryId);
try (var stream = Files.walk(libraryRoot)) {
stream.filter(Files::isDirectory)
@@ -66,4 +73,22 @@ public class MonitoringRegistrationService {
}
libraryIds.forEach(this::unregisterLibrary);
}
public Set<Path> getPathsForLibraries(Collection<Long> libraryIds) {
if (libraryIds == null || libraryIds.isEmpty()) {
return Set.of();
}
return monitoringService.getPathsForLibraries(new HashSet<>(libraryIds));
}
public boolean waitForEventsDrainedByPaths(Set<Path> paths, long timeoutMs) {
return monitoringService.waitForEventsDrainedByPaths(paths, timeoutMs);
}
public boolean waitForEventsDrained(Collection<Long> libraryIds, long timeoutMs) {
if (libraryIds == null || libraryIds.isEmpty()) {
return true;
}
return monitoringService.waitForEventsDrained(new HashSet<>(libraryIds), timeoutMs);
}
}
@@ -32,7 +32,6 @@ public class MonitoringService {
private final Map<Path, WatchKey> registeredWatchKeys = new ConcurrentHashMap<>();
private final Map<Path, Long> pathToLibraryIdMap = new ConcurrentHashMap<>();
private final Map<Long, Boolean> libraryWatchStatusMap = new ConcurrentHashMap<>();
private final Map<Long, List<Path>> libraryIdToPaths = new ConcurrentHashMap<>();
public MonitoringService(LibraryFileEventProcessor libraryFileEventProcessor, WatchService watchService, MonitoringTask monitoringTask) {
this.libraryFileEventProcessor = libraryFileEventProcessor;
@@ -67,7 +66,6 @@ public class MonitoringService {
libraryWatchStatusMap.put(library.getId(), library.isWatch());
if (!library.isWatch()) return;
List<Path> registeredPaths = new ArrayList<>();
int[] registeredCount = {0};
library.getPaths().forEach(libraryPath -> {
@@ -77,7 +75,6 @@ public class MonitoringService {
pathStream.filter(Files::isDirectory).forEach(path -> {
if (registerPath(path, library.getId())) {
registeredCount[0]++;
registeredPaths.add(path);
}
});
} catch (IOException e) {
@@ -86,7 +83,6 @@ public class MonitoringService {
}
});
libraryIdToPaths.put(library.getId(), registeredPaths);
log.info("Registered {} folders for library '{}'", registeredCount[0], library.getName());
}
@@ -101,7 +97,6 @@ public class MonitoringService {
}
libraryWatchStatusMap.put(libraryId, false);
libraryIdToPaths.remove(libraryId);
log.debug("Unregistered library {} from monitoring", libraryId);
}
@@ -241,4 +236,55 @@ public class MonitoringService {
public boolean isPathMonitored(Path path) {
return monitoredPaths.contains(path.toAbsolutePath().normalize());
}
public boolean isLibraryMonitored(Long libraryId) {
return libraryWatchStatusMap.getOrDefault(libraryId, false);
}
public Set<Path> getPathsForLibraries(Set<Long> libraryIds) {
return pathToLibraryIdMap.entrySet().stream()
.filter(entry -> libraryIds.contains(entry.getValue()))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
public boolean waitForEventsDrained(Set<Long> libraryIds, long timeoutMs) {
if (libraryIds == null || libraryIds.isEmpty()) {
return true;
}
Set<Path> libraryPaths = getPathsForLibraries(libraryIds);
return waitForEventsDrainedByPaths(libraryPaths, timeoutMs);
}
public boolean waitForEventsDrainedByPaths(Set<Path> libraryPaths, long timeoutMs) {
if (libraryPaths == null || libraryPaths.isEmpty()) {
return true;
}
final long pollIntervalMs = 50;
long deadline = System.currentTimeMillis() + timeoutMs;
while (System.currentTimeMillis() < deadline) {
boolean hasPendingEvents = eventQueue.stream()
.anyMatch(event -> {
Path watchedFolder = event.getWatchedFolder();
return libraryPaths.stream().anyMatch(watchedFolder::startsWith);
});
if (!hasPendingEvents) {
log.debug("Event queue drained for paths: {}", libraryPaths.size());
return true;
}
try {
Thread.sleep(pollIntervalMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
log.warn("Timeout waiting for event queue to drain for {} paths", libraryPaths.size());
return false;
}
}
@@ -11,6 +11,7 @@ import com.adityachandel.booklore.repository.BookOpdsRepository;
import com.adityachandel.booklore.repository.ShelfRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.library.LibraryService;
import com.adityachandel.booklore.util.BookUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
@@ -78,19 +79,19 @@ public class OpdsBookService {
if (libraryId != null) {
validateLibraryAccess(libraryId, userLibraryIds, isAdmin);
Page<Book> books = query != null && !query.isBlank()
? searchByMetadataInLibrariesPageInternal(query, Set.of(libraryId), page, size)
? searchByMetadataInLibrariesPageInternal(BookUtils.normalizeForSearch(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)
? searchByMetadataPageInternal(BookUtils.normalizeForSearch(query), page, size)
: getAllBooksPageInternal(page, size);
}
Page<Book> books = query != null && !query.isBlank()
? searchByMetadataInLibrariesPageInternal(query, userLibraryIds, page, size)
? searchByMetadataInLibrariesPageInternal(BookUtils.normalizeForSearch(query), userLibraryIds, page, size)
: getBooksByLibraryIdsPageInternal(userLibraryIds, page, size);
return applyBookFilters(books, userId);
}
@@ -157,6 +158,68 @@ public class OpdsBookService {
return books.stream().map(bookMapper::toBook).toList();
}
public List<String> getDistinctAuthors(Long userId) {
if (userId == null) {
return List.of();
}
BookLoreUserEntity entity = userRepository.findById(userId)
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
List<com.adityachandel.booklore.model.entity.AuthorEntity> authors;
if (user.getPermissions().isAdmin()) {
authors = bookOpdsRepository.findDistinctAuthors();
} else {
Set<Long> libraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
authors = bookOpdsRepository.findDistinctAuthorsByLibraryIds(libraryIds);
}
return authors.stream()
.map(com.adityachandel.booklore.model.entity.AuthorEntity::getName)
.filter(Objects::nonNull)
.distinct()
.sorted()
.toList();
}
public Page<Book> getBooksByAuthorName(Long userId, String authorName, int page, int size) {
if (userId == null) {
throw ApiError.FORBIDDEN.createException("Authentication required");
}
BookLoreUserEntity entity = userRepository.findById(userId)
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
if (user.getPermissions().isAdmin()) {
Page<Long> idPage = bookOpdsRepository.findBookIdsByAuthorName(authorName, pageable);
if (idPage.isEmpty()) {
return new PageImpl<>(List.of(), pageable, 0);
}
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(idPage.getContent());
return createPageFromEntities(books, idPage, pageable);
}
Set<Long> libraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
Page<Long> idPage = bookOpdsRepository.findBookIdsByAuthorNameAndLibraryIds(authorName, libraryIds, pageable);
if (idPage.isEmpty()) {
return new PageImpl<>(List.of(), pageable, 0);
}
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds);
Page<Book> booksPage = createPageFromEntities(books, idPage, pageable);
return applyBookFilters(booksPage, userId);
}
private Page<Book> getAllBooksPageInternal(int page, int size) {
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
@@ -90,6 +90,16 @@ public class OpdsFeedService {
</entry>
""".formatted(now()));
feed.append("""
<entry>
<title>Authors</title>
<id>urn:booklore:navigation:authors</id>
<updated>%s</updated>
<link rel="subsection" href="/api/v1/opds/authors" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
<content type="text">Browse books by author</content>
</entry>
""".formatted(now()));
feed.append("""
<entry>
<title>Surprise Me</title>
@@ -223,11 +233,49 @@ public class OpdsFeedService {
return feed.toString();
}
public String generateAuthorsNavigation(HttpServletRequest request) {
Long userId = getUserId();
List<String> authors = opdsBookService.getDistinctAuthors(userId);
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:authors</id>
<title>Authors</title>
<updated>%s</updated>
<link rel="self" href="/api/v1/opds/authors" 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()));
for (String author : authors) {
feed.append("""
<entry>
<title>%s</title>
<id>urn:booklore:author:%s</id>
<updated>%s</updated>
<link rel="subsection" href="%s" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
<content type="text">Books by %s</content>
</entry>
""".formatted(
escapeXml(author),
escapeXml(author),
now(),
escapeXml("/api/v1/opds/catalog?author=" + java.net.URLEncoder.encode(author, java.nio.charset.StandardCharsets.UTF_8)),
escapeXml(author)
));
}
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");
String author = request.getParameter("author");
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);
@@ -236,12 +284,14 @@ public class OpdsFeedService {
if (magicShelfId != null) {
booksPage = magicShelfBookService.getBooksByMagicShelfId(userId, magicShelfId, page - 1, size);
} else if (author != null && !author.isBlank()) {
booksPage = opdsBookService.getBooksByAuthorName(userId, author, 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);
String feedTitle = determineFeedTitle(libraryId, shelfId, magicShelfId, author);
String feedId = determineFeedId(libraryId, shelfId, magicShelfId, author);
var feed = new StringBuilder("""
<?xml version="1.0" encoding="UTF-8"?>
@@ -427,6 +477,15 @@ public class OpdsFeedService {
if (meta.getIsbn10() != null) {
feed.append(" <dc:identifier>urn:isbn:").append(escapeXml(meta.getIsbn10())).append("</dc:identifier>\n");
}
// Series metadata
if (meta.getSeriesName() != null) {
feed.append(" <meta property=\"belongs-to-collection\" id=\"series\">")
.append(escapeXml(meta.getSeriesName())).append("</meta>\n");
if (meta.getSeriesNumber() != null) {
feed.append(" <meta property=\"group-position\" refines=\"#series\">")
.append(meta.getSeriesNumber()).append("</meta>\n");
}
}
}
private void appendLinks(StringBuilder feed, Book book) {
@@ -443,7 +502,7 @@ public class OpdsFeedService {
}
}
private String determineFeedTitle(Long libraryId, Long shelfId, Long magicShelfId) {
private String determineFeedTitle(Long libraryId, Long shelfId, Long magicShelfId, String author) {
if (magicShelfId != null) {
return magicShelfBookService.getMagicShelfName(magicShelfId);
}
@@ -453,10 +512,13 @@ public class OpdsFeedService {
if (libraryId != null) {
return opdsBookService.getLibraryName(libraryId);
}
if (author != null && !author.isBlank()) {
return "Books by " + author;
}
return "Booklore Catalog";
}
private String determineFeedId(Long libraryId, Long shelfId, Long magicShelfId) {
private String determineFeedId(Long libraryId, Long shelfId, Long magicShelfId, String author) {
if (magicShelfId != null) {
return "urn:booklore:magic-shelf:" + magicShelfId;
}
@@ -466,6 +528,9 @@ public class OpdsFeedService {
if (libraryId != null) {
return "urn:booklore:library:" + libraryId;
}
if (author != null && !author.isBlank()) {
return "urn:booklore:author:" + author;
}
return "urn:booklore:catalog";
}
@@ -28,8 +28,10 @@ public class DefaultUserSettingsProvider {
defaultSettings.put(UserSettingKey.NEW_PDF_READER_SETTING, this::buildDefaultNewPdfReaderSetting);
defaultSettings.put(UserSettingKey.SIDEBAR_LIBRARY_SORTING, this::buildDefaultSidebarLibrarySorting);
defaultSettings.put(UserSettingKey.SIDEBAR_SHELF_SORTING, this::buildDefaultSidebarShelfSorting);
defaultSettings.put(UserSettingKey.SIDEBAR_MAGIC_SHELF_SORTING, this::buildDefaultSidebarMagicShelfSorting);
defaultSettings.put(UserSettingKey.ENTITY_VIEW_PREFERENCES, this::buildDefaultEntityViewPreferences);
defaultSettings.put(UserSettingKey.TABLE_COLUMN_PREFERENCE, () -> null);
defaultSettings.put(UserSettingKey.FILTER_MODE, () -> "and");
defaultSettings.put(UserSettingKey.FILTER_SORTING_MODE, () -> "count");
defaultSettings.put(UserSettingKey.METADATA_CENTER_VIEW_MODE, () -> "route");
}
@@ -98,6 +100,10 @@ public class DefaultUserSettingsProvider {
return SidebarSortOption.builder().field("id").order("asc").build();
}
private SidebarSortOption buildDefaultSidebarMagicShelfSorting() {
return SidebarSortOption.builder().field("id").order("asc").build();
}
private BookLoreUser.UserSettings.EntityViewPreferences buildDefaultEntityViewPreferences() {
return BookLoreUser.UserSettings.EntityViewPreferences.builder()
.global(BookLoreUser.UserSettings.GlobalPreferences.builder()
@@ -25,7 +25,6 @@ import java.util.regex.Pattern;
@AllArgsConstructor
public class UserProvisioningService {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private final AppProperties appProperties;
private final UserRepository userRepository;
private final LibraryRepository libraryRepository;
@@ -146,7 +145,9 @@ public class UserProvisioningService {
if (groupsContent.length() >= 2 && groupsContent.charAt(0) == '[' && groupsContent.charAt(groupsContent.length() - 1) == ']') {
groupsContent = groupsContent.substring(1, groupsContent.length() - 1);
}
List<String> groupsList = Arrays.asList(WHITESPACE_PATTERN.split(groupsContent));
String delimiter = appProperties.getRemoteAuth().getGroupsDelimiter();
Pattern groupsPattern = Pattern.compile(delimiter);
List<String> groupsList = Arrays.asList(groupsPattern.split(groupsContent));
isAdmin = groupsList.contains(appProperties.getRemoteAuth().getAdminGroup());
log.debug("Remote-Auth: user {} will be admin: {}", username, isAdmin);
}
@@ -1,5 +1,7 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.AuthorEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import lombok.experimental.UtilityClass;
import java.util.regex.Pattern;
@@ -8,9 +10,49 @@ import java.util.regex.Pattern;
public class BookUtils {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private static final Pattern SPECIAL_CHARACTERS_PATTERN = Pattern.compile("[.,\\-\\[\\]{}()!@#$%^&*_=+|~`<>?/\";:]");
private static final Pattern SPECIAL_CHARACTERS_PATTERN = Pattern.compile("[!@$%^&*_=|~`<>?/\"]");
private static final Pattern PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN = Pattern.compile("\\s?\\(.*?\\)");
public static String buildSearchText(BookMetadataEntity e) {
if (e == null) return null;
StringBuilder sb = new StringBuilder();
if (e.getTitle() != null) sb.append(e.getTitle()).append(" ");
if (e.getSubtitle() != null) sb.append(e.getSubtitle()).append(" ");
if (e.getSeriesName() != null) sb.append(e.getSeriesName()).append(" ");
try {
if (e.getAuthors() != null) {
for (AuthorEntity author : e.getAuthors()) {
if (author != null && author.getName() != null) {
sb.append(author.getName()).append(" ");
}
}
}
} catch (Exception ex) {
// LazyInitializationException or similar - authors won't be included in search text
}
return normalizeForSearch(sb.toString().trim());
}
public static String normalizeForSearch(String term) {
if (term == null) {
return null;
}
String s = java.text.Normalizer.normalize(term, java.text.Normalizer.Form.NFD);
s = s.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
s = s.replace("ø", "o").replace("Ø", "O")
.replace("ł", "l").replace("Ł", "L")
.replace("æ", "ae").replace("Æ", "AE")
.replace("œ", "oe").replace("Œ", "OE")
.replace("ß", "ss");
// Use cleanSearchTerm instead of cleanAndTruncateSearchTerm
s = cleanSearchTerm(s);
return s.toLowerCase();
}
public static String cleanFileName(String fileName) {
String name = fileName;
if (name == null) {
@@ -25,13 +67,18 @@ public class BookUtils {
return name;
}
public static String cleanAndTruncateSearchTerm(String term) {
public static String cleanSearchTerm(String term) {
if (term == null) {
return "";
}
String s = term;
s = SPECIAL_CHARACTERS_PATTERN.matcher(s).replaceAll("").trim();
s = WHITESPACE_PATTERN.matcher(s).replaceAll(" ");
return s;
}
public static String cleanAndTruncateSearchTerm(String term) {
String s = cleanSearchTerm(term);
if (s.length() > 60) {
String[] words = WHITESPACE_PATTERN.split(s);
if (words.length > 1) {
@@ -42,6 +42,8 @@ public class FileService {
// @formatter:off
private static final String IMAGES_DIR = "images";
private static final String BACKGROUNDS_DIR = "backgrounds";
private static final String ICONS_DIR = "icons";
private static final String SVG_DIR = "svg";
private static final String THUMBNAIL_FILENAME = "thumbnail.jpg";
private static final String COVER_FILENAME = "cover.jpg";
private static final String JPEG_MIME_TYPE = "image/jpeg";
@@ -401,6 +403,10 @@ public class FileService {
return new ClassPathResource("static/images/background.jpg");
}
public String getIconsSvgFolder() {
return Paths.get(appProperties.getPathConfig(), ICONS_DIR, SVG_DIR).toString();
}
// ========================================
// UTILITY METHODS
// ========================================
@@ -59,4 +59,16 @@ public class FileUtils {
.forEach(File::delete);
}
}
public boolean shouldIgnore(Path path) {
if (!path.getFileName().toString().isEmpty() && path.getFileName().toString().charAt(0) == '.') {
return true;
}
for (Path part : path) {
if (".caltrash".equals(part.toString())) {
return true;
}
}
return false;
}
}
@@ -38,7 +38,6 @@ public class MetadataChangeDetector {
compare(changes, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked()), newMeta.getGoogleIdLocked(), existingMeta.getGoogleIdLocked());
compare(changes, "pageCount", clear.isPageCount(), newMeta.getPageCount(), existingMeta.getPageCount(), () -> !isTrue(existingMeta.getPageCountLocked()), newMeta.getPageCountLocked(), existingMeta.getPageCountLocked());
compare(changes, "language", clear.isLanguage(), newMeta.getLanguage(), existingMeta.getLanguage(), () -> !isTrue(existingMeta.getLanguageLocked()), newMeta.getLanguageLocked(), existingMeta.getLanguageLocked());
compare(changes, "personalRating", clear.isPersonalRating(), newMeta.getPersonalRating(), existingMeta.getPersonalRating(), () -> !isTrue(existingMeta.getPersonalRatingLocked()), newMeta.getPersonalRatingLocked(), existingMeta.getPersonalRatingLocked());
compare(changes, "amazonRating", clear.isAmazonRating(), newMeta.getAmazonRating(), existingMeta.getAmazonRating(), () -> !isTrue(existingMeta.getAmazonRatingLocked()), newMeta.getAmazonRatingLocked(), existingMeta.getAmazonRatingLocked());
compare(changes, "amazonReviewCount", clear.isAmazonReviewCount(), newMeta.getAmazonReviewCount(), existingMeta.getAmazonReviewCount(), () -> !isTrue(existingMeta.getAmazonReviewCountLocked()), newMeta.getAmazonReviewCountLocked(), existingMeta.getAmazonReviewCountLocked());
compare(changes, "goodreadsRating", clear.isGoodreadsRating(), newMeta.getGoodreadsRating(), existingMeta.getGoodreadsRating(), () -> !isTrue(existingMeta.getGoodreadsRatingLocked()), newMeta.getGoodreadsRatingLocked(), existingMeta.getGoodreadsRatingLocked());
@@ -79,7 +78,6 @@ public class MetadataChangeDetector {
compareValue(diffs, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked()));
compareValue(diffs, "pageCount", clear.isPageCount(), newMeta.getPageCount(), existingMeta.getPageCount(), () -> !isTrue(existingMeta.getPageCountLocked()));
compareValue(diffs, "language", clear.isLanguage(), newMeta.getLanguage(), existingMeta.getLanguage(), () -> !isTrue(existingMeta.getLanguageLocked()));
compareValue(diffs, "personalRating", clear.isPersonalRating(), newMeta.getPersonalRating(), existingMeta.getPersonalRating(), () -> !isTrue(existingMeta.getPersonalRatingLocked()));
compareValue(diffs, "amazonRating", clear.isAmazonRating(), newMeta.getAmazonRating(), existingMeta.getAmazonRating(), () -> !isTrue(existingMeta.getAmazonRatingLocked()));
compareValue(diffs, "amazonReviewCount", clear.isAmazonReviewCount(), newMeta.getAmazonReviewCount(), existingMeta.getAmazonReviewCount(), () -> !isTrue(existingMeta.getAmazonReviewCountLocked()));
compareValue(diffs, "goodreadsRating", clear.isGoodreadsRating(), newMeta.getGoodreadsRating(), existingMeta.getGoodreadsRating(), () -> !isTrue(existingMeta.getGoodreadsRatingLocked()));
@@ -111,7 +109,6 @@ public class MetadataChangeDetector {
compareValue(diffs, "hardcoverId", clear.isHardcoverId(), newMeta.getHardcoverId(), existingMeta.getHardcoverId(), () -> !isTrue(existingMeta.getHardcoverIdLocked()));
compareValue(diffs, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked()));
compareValue(diffs, "language", clear.isLanguage(), newMeta.getLanguage(), existingMeta.getLanguage(), () -> !isTrue(existingMeta.getLanguageLocked()));
compareValue(diffs, "personalRating", clear.isPersonalRating(), newMeta.getPersonalRating(), existingMeta.getPersonalRating(), () -> !isTrue(existingMeta.getPersonalRatingLocked()));
compareValue(diffs, "authors", clear.isAuthors(), newMeta.getAuthors(), toNameSet(existingMeta.getAuthors()), () -> !isTrue(existingMeta.getAuthorsLocked()));
compareValue(diffs, "categories", clear.isCategories(), newMeta.getCategories(), toNameSet(existingMeta.getCategories()), () -> !isTrue(existingMeta.getCategoriesLocked()));
return !diffs.isEmpty();

Some files were not shown because too many files have changed in this diff Show More