Merge pull request #2223 from booklore-app/develop
Merge develop into master for release
This commit is contained in:
@@ -34,8 +34,8 @@
|
||||
|
||||
- [ ] **Code adheres to project style guidelines and conventions**
|
||||
- [ ] **Branch synchronized with latest `develop` branch** _(please resolve any merge conflicts)_
|
||||
- [ ] **🚨 CRITICAL: Automated unit/integration tests added/updated to cover changes** _(MANDATORY for ALL backend changes - this is non-negotiable)_
|
||||
- [ ] **🚨 CRITICAL: All tests pass locally** _(run `./gradlew test` for backend - NO EXCEPTIONS)_
|
||||
- [ ] **🚨 CRITICAL: Automated unit tests added/updated to cover changes** _(MANDATORY for ALL Spring Boot backend and Angular frontend changes - this is non-negotiable)_
|
||||
- [ ] **🚨 CRITICAL: All tests pass locally** _(run `./gradlew test` for Spring Boot backend, and `ng test` for Angular frontend - NO EXCEPTIONS)_
|
||||
- [ ] **🚨 CRITICAL: Manual testing completed in local development environment** _(verify your changes work AND no existing functionality is broken - test related features thoroughly)_
|
||||
- [ ] **Flyway migration versioning follows correct sequence** _(if database schema was modified)_
|
||||
- [ ] **Documentation PR submitted to [booklore-docs](https://github.com/booklore-app/booklore-docs)** _(required for features or enhancements that introduce user-facing or visual changes)_
|
||||
|
||||
@@ -17,34 +17,23 @@ jobs:
|
||||
name: Flyway Migration Check
|
||||
uses: ./.github/workflows/migrations-check.yml
|
||||
with:
|
||||
base_ref: 'origin/develop'
|
||||
base_ref: 'develop'
|
||||
head_ref: 'HEAD'
|
||||
|
||||
build-and-push:
|
||||
backend-tests:
|
||||
name: Backend Tests
|
||||
needs: [ migration-check ]
|
||||
if: needs.migration-check.result == 'success' || needs.migration-check.result == 'skipped'
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
checks: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# ----------------------------------------
|
||||
# Environment setup
|
||||
# ----------------------------------------
|
||||
- name: Set Up QEMU for Multi-Arch Builds
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set Up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Set Up JDK 21
|
||||
uses: actions/setup-java@v5
|
||||
@@ -53,9 +42,6 @@ jobs:
|
||||
distribution: 'temurin'
|
||||
cache: gradle
|
||||
|
||||
# ----------------------------------------
|
||||
# Backend tests
|
||||
# ----------------------------------------
|
||||
- name: Execute Backend Tests
|
||||
id: backend_tests
|
||||
working-directory: ./booklore-api
|
||||
@@ -75,7 +61,7 @@ jobs:
|
||||
uses: actions/upload-artifact@v6
|
||||
if: always()
|
||||
with:
|
||||
name: test-reports
|
||||
name: backend-test-reports
|
||||
path: |
|
||||
booklore-api/build/reports/tests/
|
||||
booklore-api/build/test-results/
|
||||
@@ -87,6 +73,86 @@ jobs:
|
||||
echo "❌ Backend tests failed"
|
||||
exit 1
|
||||
|
||||
frontend-tests:
|
||||
name: Frontend Tests
|
||||
needs: [ migration-check ]
|
||||
if: needs.migration-check.result == 'success' || needs.migration-check.result == 'skipped'
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
checks: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set Up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: booklore-ui/package-lock.json
|
||||
|
||||
- name: Install Frontend Dependencies
|
||||
working-directory: ./booklore-ui
|
||||
run: npm ci --force
|
||||
|
||||
- name: Execute Frontend Tests
|
||||
id: frontend_tests
|
||||
working-directory: ./booklore-ui
|
||||
run: |
|
||||
echo "Running frontend tests..."
|
||||
npx ng test
|
||||
continue-on-error: true
|
||||
|
||||
- name: Publish Frontend Test Results
|
||||
uses: EnricoMi/publish-unit-test-result-action@v2
|
||||
if: always()
|
||||
with:
|
||||
files: booklore-ui/test-results/vitest-results.xml
|
||||
check_name: Frontend Test Results
|
||||
|
||||
- name: Upload Frontend Test Reports
|
||||
uses: actions/upload-artifact@v6
|
||||
if: always()
|
||||
with:
|
||||
name: frontend-test-reports
|
||||
path: |
|
||||
booklore-ui/test-results/vitest-results.xml
|
||||
retention-days: 30
|
||||
|
||||
- name: Validate Frontend Test Results
|
||||
if: steps.frontend_tests.outcome == 'failure'
|
||||
run: |
|
||||
echo "❌ Frontend tests failed"
|
||||
exit 1
|
||||
|
||||
build-and-push:
|
||||
name: Build and Push Container
|
||||
needs: [ backend-tests, frontend-tests ]
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# ----------------------------------------
|
||||
# Environment setup
|
||||
# ----------------------------------------
|
||||
- name: Set Up QEMU for Multi-Arch Builds
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set Up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
# ----------------------------------------
|
||||
# Image tagging
|
||||
# ----------------------------------------
|
||||
|
||||
@@ -69,6 +69,21 @@ jobs:
|
||||
distribution: 'temurin'
|
||||
cache: 'gradle'
|
||||
|
||||
- name: Set Up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: booklore-ui/package-lock.json
|
||||
|
||||
- name: Install Frontend Dependencies
|
||||
working-directory: ./booklore-ui
|
||||
run: npm ci --force
|
||||
|
||||
- name: Execute Frontend Tests
|
||||
working-directory: ./booklore-ui
|
||||
run: npm run test:ci
|
||||
|
||||
- name: Retrieve Latest Master Version Tag
|
||||
id: get_version
|
||||
run: |
|
||||
@@ -166,4 +181,3 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh release edit ${{ env.new_tag }} --draft=true
|
||||
|
||||
|
||||
@@ -42,5 +42,6 @@ out/
|
||||
local/
|
||||
|
||||
### Dev config, books, and data ###
|
||||
booklore-ui/test-results/
|
||||
booklore-api/src/main/resources/application-local.yaml
|
||||
/shared/
|
||||
@@ -197,6 +197,24 @@ curl http://localhost:8080/actuator/health
|
||||
|
||||
Always run tests before submitting a pull request to ensure your changes don't break existing functionality.
|
||||
|
||||
### Frontend Tests (Angular + Vitest)
|
||||
|
||||
Booklore uses [Vitest](https://vitest.dev/) for fast, modern frontend testing in the Angular app.
|
||||
|
||||
```bash
|
||||
cd booklore-ui
|
||||
|
||||
# Run all frontend tests
|
||||
ng test
|
||||
|
||||
# Run tests with coverage report
|
||||
ng test --coverage
|
||||
```
|
||||
|
||||
- The coverage report will be generated in the `coverage/` directory.
|
||||
- You can open `coverage/index.html` in your browser to view detailed coverage metrics.
|
||||
- All new features and bug fixes should include relevant unit tests.
|
||||
|
||||
### Backend Tests
|
||||
|
||||
```bash
|
||||
|
||||
@@ -354,7 +354,7 @@ services:
|
||||
|
||||
Found an issue?
|
||||
|
||||
[](https://github.com/booklore-app/booklore/issues)
|
||||
[](https://github.com/booklore-app/booklore/issues/new?template=bug_report.yml)
|
||||
|
||||
</td>
|
||||
<td align="center">
|
||||
@@ -363,7 +363,7 @@ Found an issue?
|
||||
|
||||
Have an idea?
|
||||
|
||||
[](https://github.com/booklore-app/booklore/issues/new?template=feature_request.md)
|
||||
[](https://github.com/booklore-app/booklore/issues/new?template=feature_request.yml)
|
||||
|
||||
</td>
|
||||
<td align="center">
|
||||
|
||||
@@ -37,6 +37,9 @@ dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-mail'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
|
||||
|
||||
// --- Reactive Streams ---
|
||||
implementation 'io.projectreactor:reactor-core'
|
||||
|
||||
// --- Database & Migration ---
|
||||
implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.6'
|
||||
implementation 'org.flywaydb:flyway-mysql:11.19.0'
|
||||
@@ -55,8 +58,13 @@ dependencies {
|
||||
implementation 'org.apache.pdfbox:pdfbox-io:3.0.6'
|
||||
implementation 'org.apache.pdfbox:xmpbox:3.0.6'
|
||||
implementation 'org.apache.pdfbox:jbig2-imageio:3.0.4'
|
||||
implementation 'com.github.jai-imageio:jai-imageio-core:1.4.0'
|
||||
implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.4.0'
|
||||
|
||||
// --- TwelveMonkeys ImageIO ---
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.13.0'
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-tiff:3.13.0'
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-webp:3.13.0'
|
||||
implementation 'com.twelvemonkeys.imageio:imageio-bmp:3.13.0'
|
||||
|
||||
implementation 'io.documentnode:epub4j-core:4.2.2'
|
||||
|
||||
// --- UNRAR Support ---
|
||||
|
||||
+18
-5
@@ -1,11 +1,9 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.config.security.filter.CoverJwtFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.DualJwtAuthenticationFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.KoboAuthFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.KoreaderAuthFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.*;
|
||||
import com.adityachandel.booklore.config.security.service.OpdsUserDetailsService;
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
@@ -133,6 +131,21 @@ public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
@Order(5)
|
||||
public SecurityFilterChain customFontSecurityChain(HttpSecurity http, CustomFontJwtFilter customFontJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/custom-fonts/*/file")
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(customFontJwtFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(6)
|
||||
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
|
||||
List<String> publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS));
|
||||
if (appProperties.getSwagger().isEnabled()) {
|
||||
@@ -143,6 +156,7 @@ public class SecurityConfig {
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll()
|
||||
.requestMatchers(publicEndpoints.toArray(new String[0])).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
@@ -152,7 +166,6 @@ public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
|
||||
// Configure the shared AuthenticationManagerBuilder with the UserDetailsService and PasswordEncoder
|
||||
AuthenticationManagerBuilder auth = http.getSharedObject(AuthenticationManagerBuilder.class);
|
||||
auth.userDetailsService(opdsUserDetailsService).passwordEncoder(passwordEncoder());
|
||||
return auth.build();
|
||||
|
||||
+5
@@ -50,6 +50,11 @@ public class SecurityUtil {
|
||||
return user != null && user.getPermissions().isCanManageIcons();
|
||||
}
|
||||
|
||||
public boolean canManageFonts() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanManageFonts();
|
||||
}
|
||||
|
||||
public boolean canSyncKoReader() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanSyncKoReader();
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
|
||||
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
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 jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
|
||||
@AllArgsConstructor
|
||||
public abstract class AbstractQueryParameterJwtFilter extends OncePerRequestFilter {
|
||||
|
||||
protected final JwtUtils jwtUtils;
|
||||
protected final UserRepository userRepository;
|
||||
protected final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
protected final AppSettingService appSettingService;
|
||||
protected final DynamicOidcJwtProcessor dynamicOidcJwtProcessor;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
// Extract token from query parameter (not from Authorization header)
|
||||
String token = request.getParameter("token");
|
||||
if (token == null || token.isEmpty()) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateLocalUser(token, request);
|
||||
} else if (appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
authenticateOidcUser(token, request);
|
||||
} else {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
|
||||
return;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
protected void authenticateLocalUser(String token, HttpServletRequest request) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
|
||||
protected void authenticateOidcUser(String token, HttpServletRequest request) throws Exception {
|
||||
var processor = dynamicOidcJwtProcessor.getProcessor();
|
||||
var claimsSet = processor.process(token, null);
|
||||
|
||||
if (claimsSet.getExpirationTime() == null ||
|
||||
claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) {
|
||||
throw new RuntimeException("OIDC token expired or invalid");
|
||||
}
|
||||
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping();
|
||||
String username = claimsSet.getStringClaim(claimMapping.getUsername());
|
||||
BookLoreUserEntity entity = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
+9
-74
@@ -2,92 +2,27 @@ package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
|
||||
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
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 jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
public class CoverJwtFilter extends OncePerRequestFilter {
|
||||
public class CoverJwtFilter extends AbstractQueryParameterJwtFilter {
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
private final AppSettingService appSettingService;
|
||||
private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor;
|
||||
public CoverJwtFilter(
|
||||
JwtUtils jwtUtils,
|
||||
UserRepository userRepository,
|
||||
BookLoreUserTransformer bookLoreUserTransformer,
|
||||
AppSettingService appSettingService,
|
||||
DynamicOidcJwtProcessor dynamicOidcJwtProcessor) {
|
||||
super(jwtUtils, userRepository, bookLoreUserTransformer, appSettingService, dynamicOidcJwtProcessor);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return !path.startsWith("/api/v1/media/");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
|
||||
String token = request.getParameter("token");
|
||||
if (token == null || token.isEmpty()) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateLocalUser(token, request);
|
||||
} else if (appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
authenticateOidcUser(token, request);
|
||||
} else {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
|
||||
return;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private void authenticateLocalUser(String token, HttpServletRequest request) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
BookLoreUserEntity entity = userRepository.findById(userId).orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
|
||||
private void authenticateOidcUser(String token, HttpServletRequest request) throws Exception {
|
||||
var processor = dynamicOidcJwtProcessor.getProcessor();
|
||||
var claimsSet = processor.process(token, null);
|
||||
|
||||
if (claimsSet.getExpirationTime() == null || claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) {
|
||||
throw new RuntimeException("OIDC token expired or invalid");
|
||||
}
|
||||
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping();
|
||||
String username = claimsSet.getStringClaim(claimMapping.getUsername());
|
||||
BookLoreUserEntity entity = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CustomFontJwtFilter extends AbstractQueryParameterJwtFilter {
|
||||
|
||||
public CustomFontJwtFilter(
|
||||
JwtUtils jwtUtils,
|
||||
UserRepository userRepository,
|
||||
BookLoreUserTransformer bookLoreUserTransformer,
|
||||
AppSettingService appSettingService,
|
||||
DynamicOidcJwtProcessor dynamicOidcJwtProcessor) {
|
||||
super(jwtUtils, userRepository, bookLoreUserTransformer, appSettingService, dynamicOidcJwtProcessor);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
// Only filter requests to custom font file endpoints (e.g., /api/v1/custom-fonts/123/file)
|
||||
return !(path.startsWith("/api/v1/custom-fonts/") && path.endsWith("/file"));
|
||||
}
|
||||
}
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.UploadResponse;
|
||||
import com.adityachandel.booklore.model.dto.UrlRequest;
|
||||
import com.adityachandel.booklore.service.file.BackgroundUploadService;
|
||||
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;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Tag(name = "Background Upload", description = "Endpoints for uploading and managing background images")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/background")
|
||||
@RequiredArgsConstructor
|
||||
public class BackgroundUploadController {
|
||||
|
||||
private final BackgroundUploadService backgroundUploadService;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@Operation(summary = "Upload background image file", description = "Upload a new background image file for the authenticated user.")
|
||||
@ApiResponse(responseCode = "200", description = "Background image uploaded successfully")
|
||||
@PostMapping("/upload")
|
||||
public ResponseEntity<UploadResponse> uploadFile(@Parameter(description = "Background image file") @RequestParam("file") MultipartFile file) {
|
||||
try {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
UploadResponse response = backgroundUploadService.uploadBackgroundFile(file, authenticatedUser.getId());
|
||||
return ResponseEntity.ok(response);
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "Upload background image from URL", description = "Upload a new background image from a URL for the authenticated user.")
|
||||
@ApiResponse(responseCode = "200", description = "Background image uploaded successfully")
|
||||
@PostMapping("/url")
|
||||
public ResponseEntity<UploadResponse> uploadUrl(
|
||||
@Parameter(description = "URL request containing the image URL") @RequestBody UrlRequest request) {
|
||||
try {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
UploadResponse response = backgroundUploadService.uploadBackgroundFromUrl(request.getUrl(), authenticatedUser.getId());
|
||||
return ResponseEntity.ok(response);
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "Reset background to default", description = "Reset the background image to the default for the authenticated user.")
|
||||
@ApiResponse(responseCode = "200", description = "Background reset to default successfully")
|
||||
@DeleteMapping
|
||||
public ResponseEntity<Void> resetToDefault() {
|
||||
try {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
backgroundUploadService.resetToDefault(authenticatedUser.getId());
|
||||
return ResponseEntity.ok().build();
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.internalServerError().build();
|
||||
}
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
|
||||
import com.adityachandel.booklore.model.dto.CoverImage;
|
||||
import com.adityachandel.booklore.model.dto.request.BulkBookIdsRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.CoverFetchRequest;
|
||||
import com.adityachandel.booklore.service.metadata.BookCoverService;
|
||||
import com.adityachandel.booklore.service.metadata.DuckDuckGoCoverService;
|
||||
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.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 org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/books")
|
||||
@AllArgsConstructor
|
||||
@Tag(name = "Book Metadata", description = "Endpoints for managing book metadata, covers, and metadata operations")
|
||||
public class BookCoverController {
|
||||
|
||||
private final BookCoverService bookCoverService;
|
||||
private final DuckDuckGoCoverService duckDuckGoCoverService;
|
||||
|
||||
@Operation(summary = "Upload cover image from file", description = "Upload a cover image for a book from a file. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "200", description = "Cover image uploaded successfully")
|
||||
@PostMapping("/{bookId}/metadata/cover/upload")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public void uploadCoverFromFile(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file) {
|
||||
bookCoverService.updateCoverFromFile(bookId, file);
|
||||
}
|
||||
|
||||
@Operation(summary = "Upload cover image from URL", description = "Upload a cover image for a book from a URL. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "200", description = "Cover image uploaded successfully")
|
||||
@PostMapping("/{bookId}/metadata/cover/from-url")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public void uploadCoverFromUrl(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "URL body") @RequestBody Map<String, String> body) {
|
||||
bookCoverService.updateCoverFromUrl(bookId, body.get("url"));
|
||||
}
|
||||
|
||||
@Operation(summary = "Regenerate all covers", description = "Regenerate covers for all books. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Covers regenerated successfully")
|
||||
@PostMapping("/regenerate-covers")
|
||||
@PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()")
|
||||
public void regenerateCovers() {
|
||||
bookCoverService.regenerateCovers();
|
||||
}
|
||||
|
||||
@Operation(summary = "Regenerate cover for a book", description = "Regenerate cover for a specific book. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Cover regenerated successfully")
|
||||
@PostMapping("/{bookId}/regenerate-cover")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public void regenerateCovers(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
bookCoverService.regenerateCover(bookId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Generate custom cover for a book", description = "Generate a custom cover for a specific book based on its metadata. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Custom cover generated successfully")
|
||||
@PostMapping("/{bookId}/generate-custom-cover")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public void generateCustomCover(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
bookCoverService.generateCustomCover(bookId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Regenerate covers for selected books", description = "Regenerate covers for a list of books. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Cover regeneration started successfully")
|
||||
@PostMapping("/bulk-regenerate-covers")
|
||||
@PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()")
|
||||
public void regenerateCoversForBooks(@Parameter(description = "List of book IDs") @Validated @RequestBody BulkBookIdsRequest request) {
|
||||
bookCoverService.regenerateCoversForBooks(request.getBookIds());
|
||||
}
|
||||
|
||||
@Operation(summary = "Upload cover image for multiple books", description = "Upload a cover image to apply to multiple books. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Cover upload started successfully")
|
||||
@PostMapping("/bulk-upload-cover")
|
||||
@PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()")
|
||||
public void bulkUploadCover(
|
||||
@Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file,
|
||||
@Parameter(description = "Comma-separated book IDs") @RequestParam("bookIds") @jakarta.validation.constraints.NotEmpty java.util.Set<Long> bookIds) {
|
||||
bookCoverService.updateCoverFromFileForBooks(bookIds, file);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get cover images for a book", description = "Fetch cover images for a book.")
|
||||
@ApiResponse(responseCode = "200", description = "Cover images returned successfully")
|
||||
@PostMapping("/{bookId}/metadata/covers")
|
||||
public ResponseEntity<List<CoverImage>> getImages(@Parameter(description = "Cover fetch request") @RequestBody CoverFetchRequest request) {
|
||||
return ResponseEntity.ok(duckDuckGoCoverService.getCovers(request));
|
||||
}
|
||||
}
|
||||
-32
@@ -91,36 +91,4 @@ public class BookMediaController {
|
||||
.body(file)
|
||||
: ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Get background image", description = "Retrieve the current background image for the authenticated user.")
|
||||
@ApiResponse(responseCode = "200", description = "Background image returned successfully")
|
||||
@GetMapping("/background")
|
||||
public ResponseEntity<Resource> getBackgroundImage() {
|
||||
try {
|
||||
Resource file = bookService.getBackgroundImage();
|
||||
if (file == null || !file.exists()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
String filename = file.getFilename();
|
||||
MediaType mediaType = filename != null && filename.endsWith(".png")
|
||||
? MediaType.IMAGE_PNG
|
||||
: MediaType.IMAGE_JPEG;
|
||||
|
||||
if (filename == null) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
String fallbackFilename = NON_ASCII_PATTERN.matcher(filename).replaceAll("_");
|
||||
String contentDisposition = String.format("inline; filename=\"%s\"; filename*=UTF-8''%s",
|
||||
fallbackFilename, encodedFilename);
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
|
||||
.contentType(mediaType)
|
||||
.body(file);
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.internalServerError().build();
|
||||
}
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.CustomFontDto;
|
||||
import com.adityachandel.booklore.model.enums.FontFormat;
|
||||
import com.adityachandel.booklore.service.customfont.CustomFontService;
|
||||
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;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "Custom Fonts", description = "Endpoints for managing custom fonts for EPUB reader")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/custom-fonts")
|
||||
@RequiredArgsConstructor
|
||||
public class CustomFontController {
|
||||
|
||||
private final CustomFontService customFontService;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@Operation(summary = "Upload a custom font", description = "Upload a custom font file (.ttf, .otf, .woff, .woff2) for the authenticated user")
|
||||
@ApiResponse(responseCode = "200", description = "Font uploaded successfully")
|
||||
@ApiResponse(responseCode = "400", description = "Invalid file or quota exceeded")
|
||||
@PostMapping("/upload")
|
||||
@PreAuthorize("@securityUtil.canManageFonts() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<CustomFontDto> uploadFont(
|
||||
@Parameter(description = "Font file (.ttf, .otf, .woff, .woff2)") @RequestParam("file") MultipartFile file,
|
||||
@Parameter(description = "Font display name") @RequestParam(value = "fontName", required = false) String fontName) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
CustomFontDto fontDto = customFontService.uploadFont(file, fontName, user.getId());
|
||||
return ResponseEntity.ok(fontDto);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get all user's custom fonts", description = "Retrieve all custom fonts for the authenticated user")
|
||||
@ApiResponse(responseCode = "200", description = "Fonts retrieved successfully")
|
||||
@GetMapping
|
||||
@PreAuthorize("@securityUtil.canManageFonts() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<CustomFontDto>> getUserFonts() {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
List<CustomFontDto> fonts = customFontService.getUserFonts(user.getId());
|
||||
return ResponseEntity.ok(fonts);
|
||||
}
|
||||
|
||||
@Operation(summary = "Delete a custom font", description = "Delete a custom font file and database record")
|
||||
@ApiResponse(responseCode = "200", description = "Font deleted successfully")
|
||||
@ApiResponse(responseCode = "404", description = "Font not found or access denied")
|
||||
@DeleteMapping("/{fontId}")
|
||||
@PreAuthorize("@securityUtil.canManageFonts() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Void> deleteFont(@PathVariable Long fontId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
customFontService.deleteFont(fontId, user.getId());
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Get font file", description = "Retrieve the font file for use in the browser")
|
||||
@ApiResponse(responseCode = "200", description = "Font file retrieved successfully")
|
||||
@ApiResponse(responseCode = "404", description = "Font not found or access denied")
|
||||
@GetMapping("/{fontId}/file")
|
||||
@PreAuthorize("@securityUtil.canManageFonts() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Resource> getFontFile(@PathVariable Long fontId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Resource resource = customFontService.getFontFile(fontId, user.getId());
|
||||
FontFormat format = customFontService.getFontFormat(fontId, user.getId());
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(format.getMimeType()))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline")
|
||||
.body(resource);
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.HardcoverSyncSettings;
|
||||
import com.adityachandel.booklore.service.hardcover.HardcoverSyncSettingsService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/hardcover-sync-settings")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "Hardcover Sync Settings", description = "Endpoints for managing Hardcover progress sync settings")
|
||||
public class HardcoverSyncSettingsController {
|
||||
|
||||
private final HardcoverSyncSettingsService hardcoverSyncSettingsService;
|
||||
|
||||
@Operation(summary = "Get Hardcover sync settings", description = "Retrieve the current user's Hardcover sync settings.")
|
||||
@ApiResponse(responseCode = "200", description = "Settings returned successfully")
|
||||
@GetMapping
|
||||
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.canSyncKoReader() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<HardcoverSyncSettings> getSettings() {
|
||||
HardcoverSyncSettings settings = hardcoverSyncSettingsService.getCurrentUserSettings();
|
||||
return ResponseEntity.ok(settings);
|
||||
}
|
||||
|
||||
@Operation(summary = "Update Hardcover sync settings", description = "Update the current user's Hardcover sync settings.")
|
||||
@ApiResponse(responseCode = "200", description = "Settings updated successfully")
|
||||
@PutMapping
|
||||
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.canSyncKoReader() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<HardcoverSyncSettings> updateSettings(@RequestBody HardcoverSyncSettings settings) {
|
||||
HardcoverSyncSettings updated = hardcoverSyncSettingsService.updateCurrentUserSettings(settings);
|
||||
return ResponseEntity.ok(updated);
|
||||
}
|
||||
}
|
||||
+15
-8
@@ -41,8 +41,7 @@ public class LibraryController {
|
||||
})
|
||||
@GetMapping("/{libraryId}")
|
||||
@CheckLibraryAccess(libraryIdParam = "libraryId")
|
||||
public ResponseEntity<Library> getLibrary(
|
||||
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
|
||||
public ResponseEntity<Library> getLibrary(@Parameter(description = "ID of the library") @PathVariable long libraryId) {
|
||||
return ResponseEntity.ok(libraryService.getLibrary(libraryId));
|
||||
}
|
||||
|
||||
@@ -50,8 +49,7 @@ public class LibraryController {
|
||||
@ApiResponse(responseCode = "200", description = "Library created successfully")
|
||||
@PostMapping
|
||||
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Library> createLibrary(
|
||||
@Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) {
|
||||
public ResponseEntity<Library> createLibrary(@Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) {
|
||||
return ResponseEntity.ok(libraryService.createLibrary(request));
|
||||
}
|
||||
|
||||
@@ -71,8 +69,7 @@ public class LibraryController {
|
||||
@DeleteMapping("/{libraryId}")
|
||||
@CheckLibraryAccess(libraryIdParam = "libraryId")
|
||||
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<?> deleteLibrary(
|
||||
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
|
||||
public ResponseEntity<?> deleteLibrary(@Parameter(description = "ID of the library") @PathVariable long libraryId) {
|
||||
libraryService.deleteLibrary(libraryId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
@@ -91,8 +88,7 @@ public class LibraryController {
|
||||
@ApiResponse(responseCode = "200", description = "Books returned successfully")
|
||||
@GetMapping("/{libraryId}/book")
|
||||
@CheckLibraryAccess(libraryIdParam = "libraryId")
|
||||
public ResponseEntity<List<Book>> getBooks(
|
||||
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
|
||||
public ResponseEntity<List<Book>> getBooks(@Parameter(description = "ID of the library") @PathVariable long libraryId) {
|
||||
List<Book> books = libraryService.getBooks(libraryId);
|
||||
return ResponseEntity.ok(books);
|
||||
}
|
||||
@@ -119,4 +115,15 @@ public class LibraryController {
|
||||
Library updated = libraryService.setFileNamingPattern(libraryId, pattern);
|
||||
return ResponseEntity.ok(updated);
|
||||
}
|
||||
|
||||
@Operation(summary = "Scan library paths", description = "Scan the provided library paths and return a count of processable files. Requires admin or manipulation permission.")
|
||||
@ApiResponse(responseCode = "200", description = "Processable files count returned successfully")
|
||||
@PostMapping("/scan")
|
||||
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Integer> scanLibraryPaths(
|
||||
@Parameter(description = "Library creation request with paths to scan")
|
||||
@Validated @RequestBody CreateLibraryRequest request) {
|
||||
int processableFilesCount = libraryService.scanLibraryPaths(request);
|
||||
return ResponseEntity.ok(processableFilesCount);
|
||||
}
|
||||
}
|
||||
+16
-100
@@ -6,25 +6,27 @@ import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateContext;
|
||||
import com.adityachandel.booklore.model.MetadataUpdateWrapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.CoverImage;
|
||||
import com.adityachandel.booklore.model.dto.request.*;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.enums.MetadataReplaceMode;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.metadata.*;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataService;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataUpdater;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataManagementService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
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.AllArgsConstructor;
|
||||
import org.springframework.http.MediaType;
|
||||
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 org.springframework.web.multipart.MultipartFile;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/books")
|
||||
@@ -36,19 +38,18 @@ public class MetadataController {
|
||||
private final BookMetadataUpdater bookMetadataUpdater;
|
||||
private final BookMetadataMapper bookMetadataMapper;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
private final DuckDuckGoCoverService duckDuckGoCoverService;
|
||||
private final BookRepository bookRepository;
|
||||
private final MetadataManagementService metadataManagementService;
|
||||
|
||||
@Operation(summary = "Get prospective metadata for a book", description = "Fetch prospective metadata for a book by its ID. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "200", description = "Prospective metadata returned successfully")
|
||||
@PostMapping("/{bookId}/metadata/prospective")
|
||||
@PostMapping(value = "/{bookId}/metadata/prospective", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<List<BookMetadata>> getMetadataList(
|
||||
public Flux<BookMetadata> getMetadataList(
|
||||
@Parameter(description = "Fetch metadata request") @RequestBody(required = false) FetchMetadataRequest fetchMetadataRequest,
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return ResponseEntity.ok(bookMetadataService.getProspectiveMetadataListForBookId(bookId, fetchMetadataRequest));
|
||||
return bookMetadataService.getProspectiveMetadataListForBookId(bookId, fetchMetadataRequest);
|
||||
}
|
||||
|
||||
@Operation(summary = "Update book metadata", description = "Update metadata for a book. Requires metadata edit permission or admin.")
|
||||
@@ -84,8 +85,7 @@ public class MetadataController {
|
||||
@ApiResponse(responseCode = "204", description = "Bulk metadata updated successfully")
|
||||
@PutMapping("/bulk-edit-metadata")
|
||||
@PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Void> bulkEditMetadata(
|
||||
@Parameter(description = "Bulk metadata update request") @RequestBody BulkMetadataUpdateRequest bulkMetadataUpdateRequest) {
|
||||
public ResponseEntity<Void> bulkEditMetadata(@Parameter(description = "Bulk metadata update request") @RequestBody BulkMetadataUpdateRequest bulkMetadataUpdateRequest) {
|
||||
boolean mergeCategories = bulkMetadataUpdateRequest.isMergeCategories();
|
||||
boolean mergeMoods = bulkMetadataUpdateRequest.isMergeMoods();
|
||||
boolean mergeTags = bulkMetadataUpdateRequest.isMergeTags();
|
||||
@@ -93,36 +93,11 @@ public class MetadataController {
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Upload cover image from file", description = "Upload a cover image for a book from a file. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "200", description = "Cover image uploaded successfully")
|
||||
@PostMapping("/{bookId}/metadata/cover/upload")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<BookMetadata> uploadCoverFromFile(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file) {
|
||||
BookMetadata updated = bookMetadataService.updateCoverImageFromFile(bookId, file);
|
||||
return ResponseEntity.ok(updated);
|
||||
}
|
||||
|
||||
@Operation(summary = "Upload cover image from URL", description = "Upload a cover image for a book from a URL. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "200", description = "Cover image uploaded successfully")
|
||||
@PostMapping("/{bookId}/metadata/cover/from-url")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<BookMetadata> uploadCoverFromUrl(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "URL body") @RequestBody Map<String, String> body) {
|
||||
BookMetadata updated = bookMetadataService.updateCoverImageFromUrl(bookId, body.get("url"));
|
||||
return ResponseEntity.ok(updated);
|
||||
}
|
||||
|
||||
@Operation(summary = "Toggle all metadata locks", description = "Toggle all metadata locks for books. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "200", description = "Metadata locks toggled successfully")
|
||||
@PutMapping("/metadata/toggle-all-lock")
|
||||
@PreAuthorize("@securityUtil.canBulkLockUnlockMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<BookMetadata>> toggleAllMetadata(
|
||||
@Parameter(description = "Toggle all lock request") @RequestBody ToggleAllLockRequest request) {
|
||||
public ResponseEntity<List<BookMetadata>> toggleAllMetadata(@Parameter(description = "Toggle all lock request") @RequestBody ToggleAllLockRequest request) {
|
||||
return ResponseEntity.ok(bookMetadataService.toggleAllLock(request));
|
||||
}
|
||||
|
||||
@@ -130,61 +105,11 @@ public class MetadataController {
|
||||
@ApiResponse(responseCode = "200", description = "Field locks toggled successfully")
|
||||
@PutMapping("/metadata/toggle-field-locks")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<BookMetadata>> toggleFieldLocks(
|
||||
@Parameter(description = "Toggle field locks request") @RequestBody ToggleFieldLocksRequest request) {
|
||||
public ResponseEntity<List<BookMetadata>> toggleFieldLocks(@Parameter(description = "Toggle field locks request") @RequestBody ToggleFieldLocksRequest request) {
|
||||
bookMetadataService.toggleFieldLocks(request.getBookIds(), request.getFieldActions());
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Regenerate all covers", description = "Regenerate covers for all books. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Covers regenerated successfully")
|
||||
@PostMapping("/regenerate-covers")
|
||||
@PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()")
|
||||
public void regenerateCovers() {
|
||||
bookMetadataService.regenerateCovers();
|
||||
}
|
||||
|
||||
@Operation(summary = "Regenerate cover for a book", description = "Regenerate cover for a specific book. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Cover regenerated successfully")
|
||||
@PostMapping("/{bookId}/regenerate-cover")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public void regenerateCovers(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
bookMetadataService.regenerateCover(bookId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Generate custom cover for a book", description = "Generate a custom cover for a specific book based on its metadata. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Custom cover generated successfully")
|
||||
@PostMapping("/{bookId}/generate-custom-cover")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public void generateCustomCover(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
bookMetadataService.generateCustomCover(bookId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Regenerate covers for selected books", description = "Regenerate covers for a list of books. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Cover regeneration started successfully")
|
||||
@PostMapping("/bulk-regenerate-covers")
|
||||
@PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Void> regenerateCoversForBooks(
|
||||
@Parameter(description = "List of book IDs") @Validated @RequestBody BulkBookIdsRequest request) {
|
||||
bookMetadataService.regenerateCoversForBooks(request.getBookIds());
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Upload cover image for multiple books", description = "Upload a cover image to apply to multiple books. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Cover upload started successfully")
|
||||
@PostMapping("/bulk-upload-cover")
|
||||
@PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Void> bulkUploadCover(
|
||||
@Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file,
|
||||
@Parameter(description = "Comma-separated book IDs") @RequestParam("bookIds") @jakarta.validation.constraints.NotEmpty java.util.Set<Long> bookIds) {
|
||||
bookMetadataService.updateCoverImageFromFileForBooks(bookIds, file);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Recalculate metadata match scores", description = "Recalculate match scores for all metadata. Requires admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Match scores recalculated successfully")
|
||||
@PostMapping("/metadata/recalculate-match-scores")
|
||||
@@ -194,20 +119,11 @@ public class MetadataController {
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Get cover images for a book", description = "Fetch cover images for a book.")
|
||||
@ApiResponse(responseCode = "200", description = "Cover images returned successfully")
|
||||
@PostMapping("/{bookId}/metadata/covers")
|
||||
public ResponseEntity<List<CoverImage>> getImages(
|
||||
@Parameter(description = "Cover fetch request") @RequestBody CoverFetchRequest request) {
|
||||
return ResponseEntity.ok(duckDuckGoCoverService.getCovers(request));
|
||||
}
|
||||
|
||||
@Operation(summary = "Consolidate metadata", description = "Merge metadata values. Requires metadata edit permission or admin.")
|
||||
@ApiResponse(responseCode = "204", description = "Metadata consolidated successfully")
|
||||
@PostMapping("/metadata/manage/consolidate")
|
||||
@PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Void> mergeMetadata(
|
||||
@Parameter(description = "Merge metadata request") @Validated @RequestBody MergeMetadataRequest request) {
|
||||
public ResponseEntity<Void> mergeMetadata(@Parameter(description = "Merge metadata request") @Validated @RequestBody MergeMetadataRequest request) {
|
||||
metadataManagementService.consolidateMetadata(request.getMetadataType(), request.getTargetValues(), request.getValuesToMerge());
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
@@ -216,9 +132,9 @@ public class MetadataController {
|
||||
@ApiResponse(responseCode = "204", description = "Metadata deleted successfully")
|
||||
@PostMapping("/metadata/manage/delete")
|
||||
@PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Void> deleteMetadata(
|
||||
@Parameter(description = "Delete metadata request") @Validated @RequestBody DeleteMetadataRequest request) {
|
||||
public ResponseEntity<Void> deleteMetadata(@Parameter(description = "Delete metadata request") @Validated @RequestBody DeleteMetadataRequest request) {
|
||||
metadataManagementService.deleteMetadata(request.getMetadataType(), request.getValuesToDelete());
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
@@ -93,6 +93,27 @@ public class GlobalExceptionHandler {
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ResponseEntity<ErrorResponse> handleIllegalArgumentException(IllegalArgumentException ex) {
|
||||
log.warn("Illegal argument: {}", ex.getMessage());
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalStateException.class)
|
||||
public ResponseEntity<ErrorResponse> handleIllegalStateException(IllegalStateException ex) {
|
||||
log.error("Illegal state: {}", ex.getMessage(), ex);
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.value(), ex.getMessage());
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnsupportedOperationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleUnsupportedOperationException(UnsupportedOperationException ex) {
|
||||
log.error("Unsupported operation: {}", ex.getMessage(), ex);
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_IMPLEMENTED.value(), ex.getMessage());
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_IMPLEMENTED);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.mapper;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.CustomFontDto;
|
||||
import com.adityachandel.booklore.model.entity.CustomFontEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface CustomFontMapper {
|
||||
|
||||
CustomFontDto toDto(CustomFontEntity entity);
|
||||
}
|
||||
@@ -44,6 +44,7 @@ public class BookLoreUser {
|
||||
private boolean canAccessTaskManager;
|
||||
private boolean canManageGlobalPreferences;
|
||||
private boolean canManageIcons;
|
||||
private boolean canManageFonts;
|
||||
private boolean isDemoUser;
|
||||
private boolean canBulkAutoFetchMetadata;
|
||||
private boolean canBulkCustomFetchMetadata;
|
||||
|
||||
@@ -46,6 +46,7 @@ public class BookMetadata {
|
||||
private Double lubimyczytacRating;
|
||||
private String googleId;
|
||||
private String lubimyczytacId;
|
||||
private String externalUrl;
|
||||
private Instant coverUpdatedOn;
|
||||
private Set<String> authors;
|
||||
private Set<String> categories;
|
||||
@@ -84,6 +85,7 @@ public class BookMetadata {
|
||||
private Boolean doubanReviewCountLocked;
|
||||
private Boolean lubimyczytacIdLocked;
|
||||
private Boolean lubimyczytacRatingLocked;
|
||||
private Boolean externalUrlLocked;
|
||||
private Boolean coverLocked;
|
||||
private Boolean authorsLocked;
|
||||
private Boolean categoriesLocked;
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.FontFormat;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CustomFontDto {
|
||||
private Long id;
|
||||
private String fontName;
|
||||
private String originalFileName;
|
||||
private FontFormat format;
|
||||
private Long fileSize;
|
||||
private LocalDateTime uploadedAt;
|
||||
}
|
||||
+1
@@ -14,4 +14,5 @@ public class EpubViewerPreferences {
|
||||
private Integer fontSize;
|
||||
private Float letterSpacing;
|
||||
private Float lineHeight;
|
||||
private Long customFontId;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class HardcoverSyncSettings {
|
||||
private String hardcoverApiKey;
|
||||
private boolean hardcoverSyncEnabled;
|
||||
}
|
||||
@@ -27,6 +27,10 @@ public enum RuleField {
|
||||
PAGE_COUNT,
|
||||
@JsonProperty("language")
|
||||
LANGUAGE,
|
||||
@JsonProperty("isbn13")
|
||||
ISBN13,
|
||||
@JsonProperty("isbn10")
|
||||
ISBN10,
|
||||
@JsonProperty("amazonRating")
|
||||
AMAZON_RATING,
|
||||
@JsonProperty("amazonReviewCount")
|
||||
@@ -56,6 +60,8 @@ public enum RuleField {
|
||||
@JsonProperty("moods")
|
||||
MOODS,
|
||||
@JsonProperty("tags")
|
||||
TAGS
|
||||
TAGS,
|
||||
@JsonProperty("genre")
|
||||
GENRE
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ public class UserCreateRequest {
|
||||
private boolean permissionAccessTaskManager;
|
||||
private boolean permissionManageGlobalPreferences;
|
||||
private boolean permissionManageIcons;
|
||||
private boolean permissionManageFonts;
|
||||
private boolean permissionBulkAutoFetchMetadata;
|
||||
private boolean permissionBulkCustomFetchMetadata;
|
||||
private boolean permissionBulkEditMetadata;
|
||||
|
||||
+1
@@ -28,6 +28,7 @@ public class KoboBookMetadata {
|
||||
private String language = "en";
|
||||
|
||||
private String isbn;
|
||||
@Builder.Default
|
||||
private String genre = "00000000-0000-0000-0000-000000000001";
|
||||
private String slug;
|
||||
private String coverImageId;
|
||||
|
||||
+4
@@ -51,12 +51,14 @@ public class MetadataRefreshOptions {
|
||||
private FieldProvider comicvineId;
|
||||
private FieldProvider hardcoverId;
|
||||
private FieldProvider googleId;
|
||||
private FieldProvider lubimyczytacId;
|
||||
private FieldProvider amazonRating;
|
||||
private FieldProvider amazonReviewCount;
|
||||
private FieldProvider goodreadsRating;
|
||||
private FieldProvider goodreadsReviewCount;
|
||||
private FieldProvider hardcoverRating;
|
||||
private FieldProvider hardcoverReviewCount;
|
||||
private FieldProvider lubimyczytacRating;
|
||||
private FieldProvider moods;
|
||||
private FieldProvider tags;
|
||||
}
|
||||
@@ -99,12 +101,14 @@ public class MetadataRefreshOptions {
|
||||
private boolean comicvineId;
|
||||
private boolean hardcoverId;
|
||||
private boolean googleId;
|
||||
private boolean lubimyczytacId;
|
||||
private boolean amazonRating;
|
||||
private boolean amazonReviewCount;
|
||||
private boolean goodreadsRating;
|
||||
private boolean goodreadsReviewCount;
|
||||
private boolean hardcoverRating;
|
||||
private boolean hardcoverReviewCount;
|
||||
private boolean lubimyczytacRating;
|
||||
private boolean moods;
|
||||
private boolean tags;
|
||||
}
|
||||
|
||||
+1
@@ -30,6 +30,7 @@ public class UserUpdateRequest {
|
||||
private boolean canAccessTaskManager;
|
||||
private boolean canManageGlobalPreferences;
|
||||
private boolean canManageIcons;
|
||||
private boolean canManageFonts;
|
||||
private boolean canBulkAutoFetchMetadata;
|
||||
private boolean canBulkCustomFetchMetadata;
|
||||
private boolean canBulkEditMetadata;
|
||||
|
||||
+41
@@ -5,6 +5,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -32,6 +34,30 @@ public class Comic {
|
||||
@JsonProperty("resource_type")
|
||||
private String resourceType;
|
||||
|
||||
@JsonProperty("person_credits")
|
||||
private List<PersonCredit> personCredits;
|
||||
|
||||
@JsonProperty("start_year")
|
||||
private String startYear;
|
||||
|
||||
@JsonProperty("count_of_issues")
|
||||
private Integer countOfIssues;
|
||||
|
||||
@JsonProperty("site_detail_url")
|
||||
private String siteDetailUrl;
|
||||
|
||||
private Publisher publisher;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Publisher {
|
||||
private int id;
|
||||
private String name;
|
||||
@JsonProperty("api_detail_url")
|
||||
private String apiDetailUrl;
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -79,5 +105,20 @@ public class Comic {
|
||||
|
||||
@JsonProperty("site_detail_url")
|
||||
private String siteDetailUrl;
|
||||
|
||||
@JsonProperty("start_year")
|
||||
private String startYear;
|
||||
|
||||
@JsonProperty("count_of_issues")
|
||||
private Integer countOfIssues;
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class PersonCredit {
|
||||
private long id;
|
||||
private String name;
|
||||
private String role;
|
||||
}
|
||||
}
|
||||
+19
-7
@@ -22,14 +22,26 @@ public class ComicvineIssueResponse {
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class IssueResults {
|
||||
@JsonProperty("person_credits")
|
||||
private List<PersonCredit> personCredits;
|
||||
}
|
||||
private List<Comic.PersonCredit> personCredits;
|
||||
|
||||
private String description;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class PersonCredit {
|
||||
private long id;
|
||||
private String name;
|
||||
private String role;
|
||||
|
||||
@JsonProperty("issue_number")
|
||||
private String issueNumber;
|
||||
|
||||
@JsonProperty("cover_date")
|
||||
private String coverDate;
|
||||
|
||||
private Comic.Image image;
|
||||
|
||||
private Comic.Volume volume;
|
||||
|
||||
@JsonProperty("api_detail_url")
|
||||
private String apiDetailUrl;
|
||||
|
||||
@JsonProperty("site_detail_url")
|
||||
private String siteDetailUrl;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -20,7 +20,7 @@ public enum AppSettingKey {
|
||||
LIBRARY_METADATA_REFRESH_OPTIONS ("library_metadata_refresh_options", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
|
||||
METADATA_PROVIDER_SETTINGS ("metadata_provider_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
|
||||
METADATA_MATCH_WEIGHTS ("metadata_match_weights", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
|
||||
METADATA_PERSISTENCE_SETTINGS ("metadata_persistence_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
|
||||
METADATA_PERSISTENCE_SETTINGS ("metadata_persistence_settings_v2", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
|
||||
METADATA_PUBLIC_REVIEWS_SETTINGS ("metadata_public_reviews_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
|
||||
UPLOAD_FILE_PATTERN ("upload_file_pattern", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
|
||||
MOVE_FILE_PATTERN ("move_file_pattern", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)),
|
||||
|
||||
+24
-1
@@ -10,7 +10,30 @@ import lombok.NoArgsConstructor;
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MetadataPersistenceSettings {
|
||||
private boolean saveToOriginalFile;
|
||||
private SaveToOriginalFile saveToOriginalFile;
|
||||
private boolean convertCbrCb7ToCbz;
|
||||
private boolean moveFilesToLibraryPattern;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class SaveToOriginalFile {
|
||||
private FormatSettings epub;
|
||||
private FormatSettings pdf;
|
||||
private FormatSettings cbx;
|
||||
|
||||
public boolean isAnyFormatEnabled() {
|
||||
return (epub != null && epub.isEnabled()) || (pdf != null && pdf.isEnabled() || (cbx != null && cbx.isEnabled()));
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class FormatSettings {
|
||||
private boolean enabled;
|
||||
private int maxFileSizeInMb;
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -18,7 +18,9 @@ public enum UserSettingKey {
|
||||
FILTER_MODE("filterMode", false),
|
||||
FILTER_SORTING_MODE("filterSortingMode", false),
|
||||
METADATA_CENTER_VIEW_MODE("metadataCenterViewMode", false),
|
||||
ENABLE_SERIES_VIEW("enableSeriesView", false);
|
||||
ENABLE_SERIES_VIEW("enableSeriesView", false),
|
||||
HARDCOVER_API_KEY("hardcoverApiKey", false),
|
||||
HARDCOVER_SYNC_ENABLED("hardcoverSyncEnabled", false);
|
||||
|
||||
|
||||
private final String dbKey;
|
||||
@@ -42,4 +44,4 @@ public enum UserSettingKey {
|
||||
}
|
||||
throw new IllegalArgumentException("Unknown setting key: " + dbKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.FontFormat;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "custom_font")
|
||||
public class CustomFontEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private BookLoreUserEntity user;
|
||||
|
||||
@Column(name = "font_name", nullable = false)
|
||||
private String fontName;
|
||||
|
||||
@Column(name = "file_name", nullable = false, unique = true)
|
||||
private String fileName;
|
||||
|
||||
@Column(name = "original_file_name", nullable = false)
|
||||
private String originalFileName;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "format", nullable = false)
|
||||
private FontFormat format;
|
||||
|
||||
@Column(name = "file_size", nullable = false)
|
||||
private Long fileSize;
|
||||
|
||||
@Column(name = "uploaded_at", nullable = false)
|
||||
private LocalDateTime uploadedAt;
|
||||
}
|
||||
+3
@@ -44,4 +44,7 @@ public class EpubViewerPreferencesEntity {
|
||||
|
||||
@Column(name = "spread")
|
||||
private String spread;
|
||||
|
||||
@Column(name = "custom_font_id")
|
||||
private Long customFontId;
|
||||
}
|
||||
+4
@@ -87,6 +87,10 @@ public class UserPermissionsEntity {
|
||||
@Builder.Default
|
||||
private boolean permissionManageIcons = false;
|
||||
|
||||
@Column(name = "permission_manage_fonts", nullable = false)
|
||||
@Builder.Default
|
||||
private boolean permissionManageFonts = false;
|
||||
|
||||
@Column(name = "permission_demo_user", nullable = false)
|
||||
@Builder.Default
|
||||
private boolean permissionDemoUser = false;
|
||||
|
||||
+29
-1
@@ -1,5 +1,33 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@Getter
|
||||
public enum BookFileType {
|
||||
PDF, EPUB, CBX, FB2
|
||||
|
||||
PDF(Set.of("pdf")),
|
||||
EPUB(Set.of("epub")),
|
||||
CBX(Set.of("cbz", "cbr", "cb7")),
|
||||
FB2(Set.of("fb2"));
|
||||
|
||||
private final Set<String> extensions;
|
||||
|
||||
BookFileType(Set<String> extensions) {
|
||||
this.extensions = extensions;
|
||||
}
|
||||
|
||||
public boolean supports(String extension) {
|
||||
return extensions.contains(extension.toLowerCase());
|
||||
}
|
||||
|
||||
public static Optional<BookFileType> fromExtension(String extension) {
|
||||
String ext = extension.toLowerCase();
|
||||
return Arrays.stream(values())
|
||||
.filter(type -> type.supports(ext))
|
||||
.findFirst();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public enum FontFormat {
|
||||
TTF("font/ttf", ".ttf"),
|
||||
OTF("font/otf", ".otf"),
|
||||
WOFF("font/woff", ".woff"),
|
||||
WOFF2("font/woff2", ".woff2");
|
||||
|
||||
private final String mimeType;
|
||||
private final String extension;
|
||||
|
||||
FontFormat(String mimeType, String extension) {
|
||||
this.mimeType = mimeType;
|
||||
this.extension = extension;
|
||||
}
|
||||
|
||||
public static FontFormat fromExtension(String extension) {
|
||||
String normalizedExt = extension.toLowerCase();
|
||||
if (!normalizedExt.startsWith(".")) {
|
||||
normalizedExt = "." + normalizedExt;
|
||||
}
|
||||
for (FontFormat format : values()) {
|
||||
if (format.extension.equals(normalizedExt)) {
|
||||
return format;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unsupported font format: " + extension);
|
||||
}
|
||||
|
||||
public static FontFormat fromMimeType(String mimeType) {
|
||||
for (FontFormat format : values()) {
|
||||
if (format.mimeType.equals(mimeType)) {
|
||||
return format;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unsupported MIME type: " + mimeType);
|
||||
}
|
||||
|
||||
public static boolean isSupportedExtension(String extension) {
|
||||
String normalizedExt = extension.toLowerCase();
|
||||
if (!normalizedExt.startsWith(".")) {
|
||||
normalizedExt = "." + normalizedExt;
|
||||
}
|
||||
for (FontFormat format : values()) {
|
||||
if (format.extension.equals(normalizedExt)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -18,5 +18,6 @@ public enum PermissionType {
|
||||
ACCESS_TASK_MANAGER,
|
||||
MANAGE_GLOBAL_PREFERENCES,
|
||||
MANAGE_ICONS,
|
||||
MANAGE_FONTS,
|
||||
DEMO_USER
|
||||
}
|
||||
|
||||
@@ -146,6 +146,14 @@ public enum UserPermission {
|
||||
UserPermissionsEntity::isPermissionManageIcons,
|
||||
UserPermissionsEntity::setPermissionManageIcons
|
||||
),
|
||||
CAN_MANAGE_FONTS(
|
||||
"Manage fonts",
|
||||
BookLoreUser.UserPermissions::isCanManageFonts,
|
||||
BookLoreUser.UserPermissions::setCanManageFonts,
|
||||
UserUpdateRequest.Permissions::isCanManageFonts,
|
||||
UserPermissionsEntity::isPermissionManageFonts,
|
||||
UserPermissionsEntity::setPermissionManageFonts
|
||||
),
|
||||
CAN_BULK_AUTO_FETCH_METADATA(
|
||||
"Bulk auto fetch metadata",
|
||||
BookLoreUser.UserPermissions::isCanBulkAutoFetchMetadata,
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.repository;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.projection.BookCoverUpdateProjection;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.*;
|
||||
@@ -143,4 +144,7 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
|
||||
@Query("SELECT COUNT(b) FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
long countByLibraryId(@Param("libraryId") Long libraryId);
|
||||
|
||||
@Query("SELECT b.id as id, m.coverUpdatedOn as coverUpdatedOn FROM BookEntity b LEFT JOIN b.metadata m WHERE b.id IN :bookIds")
|
||||
List<BookCoverUpdateProjection> findCoverUpdateInfoByIds(@Param("bookIds") Collection<Long> bookIds);
|
||||
}
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.CustomFontEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface CustomFontRepository extends JpaRepository<CustomFontEntity, Long> {
|
||||
|
||||
List<CustomFontEntity> findByUserId(Long userId);
|
||||
|
||||
int countByUserId(Long userId);
|
||||
|
||||
Optional<CustomFontEntity> findByIdAndUserId(Long id, Long userId);
|
||||
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.UserSettingEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserSettingRepository extends JpaRepository<UserSettingEntity, Long> {
|
||||
long countBySettingKeyAndSettingValue(String settingKey, String settingValue);
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.repository.projection;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public interface BookCoverUpdateProjection {
|
||||
Long getId();
|
||||
Instant getCoverUpdatedOn();
|
||||
}
|
||||
|
||||
+5
-1
@@ -324,6 +324,8 @@ public class BookRuleEvaluatorService {
|
||||
case SERIES_NAME -> root.get("metadata").get("seriesName");
|
||||
case SERIES_NUMBER -> root.get("metadata").get("seriesNumber");
|
||||
case SERIES_TOTAL -> root.get("metadata").get("seriesTotal");
|
||||
case ISBN13 -> root.get("metadata").get("isbn13");
|
||||
case ISBN10 -> root.get("metadata").get("isbn10");
|
||||
case AMAZON_RATING -> root.get("metadata").get("amazonRating");
|
||||
case AMAZON_REVIEW_COUNT -> root.get("metadata").get("amazonReviewCount");
|
||||
case GOODREADS_RATING -> root.get("metadata").get("goodreadsRating");
|
||||
@@ -338,7 +340,8 @@ public class BookRuleEvaluatorService {
|
||||
|
||||
private boolean isArrayField(RuleField field) {
|
||||
return field == RuleField.AUTHORS || field == RuleField.CATEGORIES ||
|
||||
field == RuleField.MOODS || field == RuleField.TAGS;
|
||||
field == RuleField.MOODS || field == RuleField.TAGS ||
|
||||
field == RuleField.GENRE;
|
||||
}
|
||||
|
||||
private Join<?, ?> createArrayFieldJoin(RuleField field, Root<BookEntity> root) {
|
||||
@@ -356,6 +359,7 @@ public class BookRuleEvaluatorService {
|
||||
case CATEGORIES -> metadataJoin.join("categories", JoinType.INNER);
|
||||
case MOODS -> metadataJoin.join("moods", JoinType.INNER);
|
||||
case TAGS -> metadataJoin.join("tags", JoinType.INNER);
|
||||
case GENRE -> metadataJoin.join("categories", JoinType.INNER);
|
||||
default -> throw new IllegalArgumentException("Not an array field: " + field);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.adityachandel.booklore.model.dto.InstallationPing;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataProviderSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPublicReviewsSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
@@ -42,6 +43,7 @@ public class TelemetryService {
|
||||
private final EmailRecipientV2Repository emailRecipientV2Repository;
|
||||
private final AppSettingService appSettingService;
|
||||
private final KoboUserSettingsRepository koboUserSettingsRepository;
|
||||
private final UserSettingRepository userSettingRepository;
|
||||
private final KoreaderUserRepository koreaderUserRepository;
|
||||
private final OpdsUserV2Repository opdsUserV2Repository;
|
||||
private final InstallationService installationService;
|
||||
@@ -104,7 +106,7 @@ public class TelemetryService {
|
||||
.metadataStatistics(BookloreTelemetry.MetadataStatistics.builder()
|
||||
.enabledMetadataProviders(enabledMetadataProviders)
|
||||
.enabledReviewMetadataProviders(enabledReviewMetadataProviders)
|
||||
.saveMetadataToFile(settings.getMetadataPersistenceSettings().isSaveToOriginalFile())
|
||||
.saveMetadataToFile(settings.getMetadataPersistenceSettings().getSaveToOriginalFile().isAnyFormatEnabled())
|
||||
.moveFileViaPattern(settings.getMetadataPersistenceSettings().isMoveFilesToLibraryPattern())
|
||||
.autoBookSearchEnabled(settings.isAutoBookSearch())
|
||||
.similarBookRecommendationsEnabled(settings.isSimilarBookRecommendation())
|
||||
@@ -121,7 +123,8 @@ public class TelemetryService {
|
||||
.koboStatistics(BookloreTelemetry.KoboStatistics.builder()
|
||||
.convertToKepubEnabled(settings.getKoboSettings().isConvertToKepub())
|
||||
.totalKoboUsers((int) koboUserSettingsRepository.count())
|
||||
.totalHardcoverSyncEnabled((int) koboUserSettingsRepository.countByHardcoverSyncEnabledTrue())
|
||||
.totalHardcoverSyncEnabled((int) userSettingRepository.countBySettingKeyAndSettingValue(
|
||||
UserSettingKey.HARDCOVER_SYNC_ENABLED.getDbKey(), "true"))
|
||||
.totalAutoAddToShelf((int) koboUserSettingsRepository.countByAutoAddToShelfTrue())
|
||||
.build())
|
||||
.bookStatistics(bookStatistics)
|
||||
|
||||
+27
-3
@@ -9,6 +9,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
@@ -16,6 +17,7 @@ import java.util.Set;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class SettingPersistenceHelper {
|
||||
|
||||
public final AppSettingsRepository appSettingsRepository;
|
||||
@@ -52,14 +54,15 @@ public class SettingPersistenceHelper {
|
||||
try {
|
||||
return deserializer.deserialize(json);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException("Failed to parse " + key, e);
|
||||
log.error("Failed to parse JSON for setting key '{}'. Using default value. Error: {}", key, e.getMessage());
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
if (defaultValue != null && persistDefault) {
|
||||
try {
|
||||
saveDefaultSetting(key, objectMapper.writeValueAsString(defaultValue));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException("Failed to persist default for " + key, e);
|
||||
log.error("Failed to persist default value for setting key '{}'. Error: {}", key, e.getMessage());
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
@@ -218,8 +221,29 @@ public class SettingPersistenceHelper {
|
||||
}
|
||||
|
||||
public MetadataPersistenceSettings getDefaultMetadataPersistenceSettings() {
|
||||
MetadataPersistenceSettings.FormatSettings epubSettings = MetadataPersistenceSettings.FormatSettings.builder()
|
||||
.enabled(false)
|
||||
.maxFileSizeInMb(250)
|
||||
.build();
|
||||
|
||||
MetadataPersistenceSettings.FormatSettings pdfSettings = MetadataPersistenceSettings.FormatSettings.builder()
|
||||
.enabled(false)
|
||||
.maxFileSizeInMb(250)
|
||||
.build();
|
||||
|
||||
MetadataPersistenceSettings.FormatSettings cbxSettings = MetadataPersistenceSettings.FormatSettings.builder()
|
||||
.enabled(false)
|
||||
.maxFileSizeInMb(250)
|
||||
.build();
|
||||
|
||||
MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = MetadataPersistenceSettings.SaveToOriginalFile.builder()
|
||||
.epub(epubSettings)
|
||||
.pdf(pdfSettings)
|
||||
.cbx(cbxSettings)
|
||||
.build();
|
||||
|
||||
return MetadataPersistenceSettings.builder()
|
||||
.saveToOriginalFile(false)
|
||||
.saveToOriginalFile(saveToOriginalFile)
|
||||
.convertCbrCb7ToCbz(false)
|
||||
.moveFilesToLibraryPattern(false)
|
||||
.build();
|
||||
|
||||
@@ -293,16 +293,6 @@ public class BookService {
|
||||
return getBookCover(bookEntity.getId());
|
||||
}
|
||||
|
||||
public Resource getBackgroundImage() {
|
||||
try {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
return fileService.getBackgroundResource(user.getId());
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to get background image: {}", e.getMessage(), e);
|
||||
return fileService.getBackgroundResource(null);
|
||||
}
|
||||
}
|
||||
|
||||
public ResponseEntity<Resource> downloadBook(Long bookId) {
|
||||
return bookDownloadService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
package com.adityachandel.booklore.service.customfont;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.mapper.CustomFontMapper;
|
||||
import com.adityachandel.booklore.model.dto.CustomFontDto;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.CustomFontEntity;
|
||||
import com.adityachandel.booklore.model.enums.FontFormat;
|
||||
import com.adityachandel.booklore.repository.CustomFontRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CustomFontService {
|
||||
|
||||
private final CustomFontRepository customFontRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final CustomFontMapper customFontMapper;
|
||||
private final AppProperties appProperties;
|
||||
|
||||
private static final int MAX_FONTS_PER_USER = 10;
|
||||
private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024;
|
||||
private static final String CUSTOM_FONTS_DIR = "custom-fonts";
|
||||
private static final int MAX_FONT_NAME_LENGTH = 100;
|
||||
|
||||
@Transactional
|
||||
public CustomFontDto uploadFont(MultipartFile file, String fontName, Long userId) {
|
||||
Path fontPath = null;
|
||||
CustomFontEntity savedEntity = null;
|
||||
|
||||
try {
|
||||
validateFontUpload(file, userId);
|
||||
|
||||
BookLoreUserEntity user = userRepository.findById(userId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("User not found"));
|
||||
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
if (originalFilename == null || originalFilename.isEmpty()) {
|
||||
throw new IllegalArgumentException("Invalid file name");
|
||||
}
|
||||
|
||||
String extension = getFileExtension(originalFilename);
|
||||
FontFormat format = FontFormat.fromExtension(extension);
|
||||
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
|
||||
String fileName = String.format("user_%d_font_%s%s", userId, uuid, format.getExtension());
|
||||
|
||||
Path fontDir = getFontDirectory(userId);
|
||||
Files.createDirectories(fontDir);
|
||||
fontPath = fontDir.resolve(fileName);
|
||||
|
||||
validatePath(fontPath, fontDir);
|
||||
|
||||
file.transferTo(fontPath.toFile());
|
||||
|
||||
validateFontMagicBytes(fontPath, format);
|
||||
|
||||
String sanitizedFontName = sanitizeFontName(fontName, originalFilename);
|
||||
|
||||
CustomFontEntity entity = CustomFontEntity.builder()
|
||||
.user(user)
|
||||
.fontName(sanitizedFontName)
|
||||
.fileName(fileName)
|
||||
.originalFileName(originalFilename)
|
||||
.format(format)
|
||||
.fileSize(file.getSize())
|
||||
.uploadedAt(LocalDateTime.now())
|
||||
.build();
|
||||
|
||||
savedEntity = customFontRepository.save(entity);
|
||||
log.info("Font uploaded successfully for user {}: {} ({})", userId, sanitizedFontName, fileName);
|
||||
|
||||
return customFontMapper.toDto(savedEntity);
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to upload font for user {}: {}", userId, e.getMessage(), e);
|
||||
throw new APIException("Failed to upload font. Please try again or contact support if the problem persists.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
} finally {
|
||||
if (fontPath != null && savedEntity == null) {
|
||||
try {
|
||||
Files.deleteIfExists(fontPath);
|
||||
log.debug("Cleaned up orphaned font file after upload failure: {}", fontPath);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to cleanup orphaned font file: {}", fontPath, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<CustomFontDto> getUserFonts(Long userId) {
|
||||
List<CustomFontEntity> fonts = customFontRepository.findByUserId(userId);
|
||||
return fonts.stream()
|
||||
.map(customFontMapper::toDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteFont(Long fontId, Long userId) {
|
||||
CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Font not found or access denied"));
|
||||
|
||||
IOException fileDeleteException = null;
|
||||
|
||||
try {
|
||||
Path fontDir = getFontDirectory(userId);
|
||||
Path fontPath = fontDir.resolve(font.getFileName());
|
||||
|
||||
validatePath(fontPath, fontDir);
|
||||
|
||||
Files.deleteIfExists(fontPath);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to delete font file for user {}: {}", userId, e.getMessage(), e);
|
||||
fileDeleteException = e;
|
||||
}
|
||||
|
||||
try {
|
||||
customFontRepository.delete(font);
|
||||
log.info("Font deleted successfully for user {}: {} ({})", userId, font.getFontName(), font.getFileName());
|
||||
} catch (Exception dbException) {
|
||||
log.error("Failed to delete font from database for user {}: {}", userId, dbException.getMessage(), dbException);
|
||||
|
||||
if (fileDeleteException != null) {
|
||||
log.error("Additionally, file deletion also failed for font: {}", font.getFileName(), fileDeleteException);
|
||||
}
|
||||
|
||||
throw new APIException("Failed to delete font. Please try again or contact support if the problem persists.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
if (fileDeleteException != null) {
|
||||
log.warn("Font deleted from database but failed to delete file for user {}: {}", userId, font.getFileName(), fileDeleteException);
|
||||
}
|
||||
}
|
||||
|
||||
public Resource getFontFile(Long fontId, Long userId) {
|
||||
CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Font not found or access denied"));
|
||||
|
||||
Path fontDir = getFontDirectory(userId);
|
||||
Path fontPath = fontDir.resolve(font.getFileName());
|
||||
|
||||
try {
|
||||
validatePath(fontPath, fontDir);
|
||||
} catch (IOException e) {
|
||||
log.error("Invalid font path for user {}: {}", userId, fontPath, e);
|
||||
throw new IllegalArgumentException("Invalid font file path");
|
||||
}
|
||||
|
||||
File fontFile = fontPath.toFile();
|
||||
|
||||
if (!fontFile.exists()) {
|
||||
throw new IllegalArgumentException("Font file not found on disk");
|
||||
}
|
||||
|
||||
return new FileSystemResource(fontFile);
|
||||
}
|
||||
|
||||
public FontFormat getFontFormat(Long fontId, Long userId) {
|
||||
CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Font not found or access denied"));
|
||||
return font.getFormat();
|
||||
}
|
||||
|
||||
private void validateFontUpload(MultipartFile file, Long userId) {
|
||||
if (file.isEmpty()) {
|
||||
throw new IllegalArgumentException("File is empty");
|
||||
}
|
||||
|
||||
if (file.getSize() > MAX_FILE_SIZE_BYTES) {
|
||||
throw new IllegalArgumentException("File size exceeds maximum limit of 5MB");
|
||||
}
|
||||
|
||||
int currentFontCount = customFontRepository.countByUserId(userId);
|
||||
if (currentFontCount >= MAX_FONTS_PER_USER) {
|
||||
throw new IllegalArgumentException(String.format("Font limit exceeded. Maximum %d fonts per user allowed", MAX_FONTS_PER_USER));
|
||||
}
|
||||
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
if (originalFilename == null || originalFilename.isEmpty()) {
|
||||
throw new IllegalArgumentException("Invalid file name");
|
||||
}
|
||||
|
||||
String extension = getFileExtension(originalFilename);
|
||||
if (!FontFormat.isSupportedExtension(extension)) {
|
||||
throw new IllegalArgumentException("Unsupported font format. Allowed formats: .ttf, .otf, .woff, .woff2");
|
||||
}
|
||||
|
||||
String contentType = file.getContentType();
|
||||
if (contentType != null && !isSupportedMimeType(contentType)) {
|
||||
log.warn("Potentially invalid MIME type for font: {}", contentType);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isSupportedMimeType(String mimeType) {
|
||||
return mimeType.equals("font/ttf") ||
|
||||
mimeType.equals("font/otf") ||
|
||||
mimeType.equals("font/woff") ||
|
||||
mimeType.equals("font/woff2") ||
|
||||
mimeType.equals("application/x-font-ttf") ||
|
||||
mimeType.equals("application/x-font-opentype") ||
|
||||
mimeType.equals("application/font-woff") ||
|
||||
mimeType.equals("application/font-woff2") ||
|
||||
mimeType.equals("application/octet-stream");
|
||||
}
|
||||
|
||||
private String getFileExtension(String filename) {
|
||||
int lastDotIndex = filename.lastIndexOf('.');
|
||||
if (lastDotIndex == -1 || lastDotIndex == filename.length() - 1) {
|
||||
throw new IllegalArgumentException("File has no extension");
|
||||
}
|
||||
return filename.substring(lastDotIndex);
|
||||
}
|
||||
|
||||
private Path getFontDirectory(Long userId) {
|
||||
return Paths.get(appProperties.getPathConfig(), CUSTOM_FONTS_DIR, String.valueOf(userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that the resolved path stays within the expected parent directory
|
||||
* to prevent directory traversal attacks.
|
||||
*/
|
||||
private void validatePath(Path resolvedPath, Path expectedParent) throws IOException {
|
||||
Path normalizedPath = resolvedPath.toAbsolutePath().normalize();
|
||||
Path normalizedParent = expectedParent.toAbsolutePath().normalize();
|
||||
|
||||
if (!normalizedPath.startsWith(normalizedParent)) {
|
||||
log.error("Path traversal attempt detected: {} does not start with {}", normalizedPath, normalizedParent);
|
||||
throw new IOException("Invalid file path: path traversal detected");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates font file format by checking magic bytes.
|
||||
* Prevents malicious files from being uploaded with font extensions.
|
||||
*/
|
||||
private void validateFontMagicBytes(Path fontPath, FontFormat expectedFormat) throws IOException {
|
||||
byte[] header = new byte[4];
|
||||
|
||||
try (var inputStream = Files.newInputStream(fontPath)) {
|
||||
int bytesRead = inputStream.read(header);
|
||||
|
||||
if (bytesRead < 4) {
|
||||
throw new IllegalArgumentException("Invalid font file: file too small");
|
||||
}
|
||||
}
|
||||
|
||||
boolean isValid = false;
|
||||
String detectedFormat = "Unknown";
|
||||
|
||||
// Check TTF signature: 0x00 0x01 0x00 0x00 or "true" (0x74 0x72 0x75 0x65)
|
||||
if ((header[0] == 0x00 && header[1] == 0x01 && header[2] == 0x00 && header[3] == 0x00) ||
|
||||
(header[0] == 0x74 && header[1] == 0x72 && header[2] == 0x75 && header[3] == 0x65)) {
|
||||
isValid = (expectedFormat == FontFormat.TTF);
|
||||
detectedFormat = "TTF";
|
||||
}
|
||||
// Check OTF signature: "OTTO" (0x4F 0x54 0x54 0x4F)
|
||||
else if (header[0] == 0x4F && header[1] == 0x54 && header[2] == 0x54 && header[3] == 0x4F) {
|
||||
isValid = (expectedFormat == FontFormat.OTF);
|
||||
detectedFormat = "OTF";
|
||||
}
|
||||
// Check WOFF signature: "wOFF" (0x77 0x4F 0x46 0x46)
|
||||
else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x46) {
|
||||
isValid = (expectedFormat == FontFormat.WOFF);
|
||||
detectedFormat = "WOFF";
|
||||
}
|
||||
// Check WOFF2 signature: "wOF2" (0x77 0x4F 0x46 0x32)
|
||||
else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x32) {
|
||||
isValid = (expectedFormat == FontFormat.WOFF2);
|
||||
detectedFormat = "WOFF2";
|
||||
}
|
||||
|
||||
if (!isValid) {
|
||||
log.error("Font file magic bytes validation failed. Expected: {}, Detected: {}", expectedFormat, detectedFormat);
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Invalid font file format. File appears to be %s but extension indicates %s",
|
||||
detectedFormat, expectedFormat)
|
||||
);
|
||||
}
|
||||
|
||||
log.debug("Font file magic bytes validated successfully: {}", detectedFormat);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes font name to prevent XSS and ensure data integrity.
|
||||
*/
|
||||
private String sanitizeFontName(String fontName, String fallbackName) {
|
||||
if (fontName == null || fontName.trim().isEmpty()) {
|
||||
fontName = fallbackName;
|
||||
}
|
||||
|
||||
String sanitized = fontName.trim();
|
||||
|
||||
sanitized = sanitized.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", "");
|
||||
|
||||
sanitized = sanitized.replaceAll("<[^>]*>", "");
|
||||
sanitized = sanitized.replaceAll("[<>\"'`]", "");
|
||||
|
||||
sanitized = sanitized.replaceAll("\\s+", " ");
|
||||
|
||||
sanitized = sanitized.trim();
|
||||
|
||||
if (sanitized.isEmpty()) {
|
||||
sanitized = fallbackName;
|
||||
}
|
||||
|
||||
if (sanitized.length() > MAX_FONT_NAME_LENGTH) {
|
||||
sanitized = sanitized.substring(0, MAX_FONT_NAME_LENGTH).trim();
|
||||
}
|
||||
|
||||
return sanitized;
|
||||
}
|
||||
}
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
package com.adityachandel.booklore.service.file;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.UploadResponse;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Objects;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BackgroundUploadService {
|
||||
|
||||
private final FileService fileService;
|
||||
|
||||
private static final String JPEG_MIME_TYPE = "image/jpeg";
|
||||
private static final String PNG_MIME_TYPE = "image/png";
|
||||
private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024; // 5MB
|
||||
|
||||
public UploadResponse uploadBackgroundFile(MultipartFile file, Long userId) {
|
||||
try {
|
||||
validateBackgroundFile(file);
|
||||
|
||||
String originalFilename = Objects.requireNonNull(file.getOriginalFilename());
|
||||
String extension = getFileExtension(originalFilename);
|
||||
String filename = "1." + extension;
|
||||
|
||||
BufferedImage originalImage;
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
originalImage = ImageIO.read(inputStream);
|
||||
}
|
||||
if (originalImage == null) {
|
||||
throw new IllegalArgumentException("Invalid image file");
|
||||
}
|
||||
|
||||
deleteExistingBackgroundFiles(userId);
|
||||
fileService.saveBackgroundImage(originalImage, filename, userId);
|
||||
originalImage.flush(); // Release resources after saving
|
||||
|
||||
String fileUrl = FileService.getBackgroundUrl(filename, userId);
|
||||
return new UploadResponse(fileUrl);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to upload background file: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("Failed to upload file: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public UploadResponse uploadBackgroundFromUrl(String imageUrl, Long userId) {
|
||||
try {
|
||||
URL url = new URI(imageUrl).toURL();
|
||||
String originalFilename = Paths.get(url.getPath()).getFileName().toString();
|
||||
String extension = getFileExtension(originalFilename);
|
||||
String filename = "1." + extension;
|
||||
|
||||
BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl);
|
||||
deleteExistingBackgroundFiles(userId);
|
||||
|
||||
fileService.saveBackgroundImage(originalImage, filename, userId);
|
||||
originalImage.flush(); // Release resources after saving
|
||||
|
||||
String fileUrl = FileService.getBackgroundUrl(filename, userId);
|
||||
return new UploadResponse(fileUrl);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to upload background from URL: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("Invalid or inaccessible URL: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void resetToDefault(Long userId) {
|
||||
try {
|
||||
deleteExistingBackgroundFiles(userId);
|
||||
log.info("Reset background to default successfully for user: {}", userId);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to reset background to default: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("Failed to reset background: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteExistingBackgroundFiles(Long userId) {
|
||||
try {
|
||||
fileService.deleteBackgroundFile("1.jpg", userId);
|
||||
fileService.deleteBackgroundFile("1.jpeg", userId);
|
||||
fileService.deleteBackgroundFile("1.png", userId);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to delete existing background files: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void validateBackgroundFile(MultipartFile file) {
|
||||
if (file.isEmpty()) {
|
||||
throw new IllegalArgumentException("Background image file is empty");
|
||||
}
|
||||
String contentType = file.getContentType();
|
||||
if (!(JPEG_MIME_TYPE.equalsIgnoreCase(contentType) || PNG_MIME_TYPE.equalsIgnoreCase(contentType))) {
|
||||
throw new IllegalArgumentException("Background image must be JPEG or PNG format");
|
||||
}
|
||||
if (file.getSize() > MAX_FILE_SIZE_BYTES) {
|
||||
throw new IllegalArgumentException("Background image size must not exceed 5 MB");
|
||||
}
|
||||
}
|
||||
|
||||
private String getFileExtension(String filename) {
|
||||
int lastDotIndex = filename.lastIndexOf('.');
|
||||
if (lastDotIndex > 0 && lastDotIndex < filename.length() - 1) {
|
||||
return filename.substring(lastDotIndex + 1).toLowerCase();
|
||||
}
|
||||
return "jpg";
|
||||
}
|
||||
}
|
||||
+21
-15
@@ -42,7 +42,6 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
private static final Pattern UNDERSCORE_HYPHEN_PATTERN = Pattern.compile("[_\\-]");
|
||||
private static final Pattern IMAGE_EXTENSION_PATTERN = Pattern.compile(".*\\.(jpg|jpeg|png|webp)");
|
||||
private static final Pattern IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN = Pattern.compile("(?i).*\\.(jpg|jpeg|png|webp)");
|
||||
private static final Pattern CBX_FILE_EXTENSION_PATTERN = Pattern.compile("(?i)\\.cb[rz7]$");
|
||||
private final CbxMetadataExtractor cbxMetadataExtractor;
|
||||
|
||||
public CbxProcessor(BookRepository bookRepository,
|
||||
@@ -99,17 +98,20 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
}
|
||||
|
||||
private Optional<BufferedImage> extractImagesFromArchive(File file) {
|
||||
String name = file.getName().toLowerCase();
|
||||
if (name.endsWith(".cbz")) {
|
||||
return extractFirstImageFromZip(file);
|
||||
} else if (name.endsWith(".cb7")) {
|
||||
return extractFirstImageFrom7z(file);
|
||||
} else if (name.endsWith(".cbr")) {
|
||||
return extractFirstImageFromRar(file);
|
||||
} else {
|
||||
String name = file.getName();
|
||||
String extension = FileUtils.getExtension(name).toLowerCase();
|
||||
|
||||
if (!BookFileType.CBX.supports(extension)) {
|
||||
log.warn("Unsupported CBX format: {}", name);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return switch (extension) {
|
||||
case "cbz" -> extractFirstImageFromZip(file);
|
||||
case "cb7" -> extractFirstImageFrom7z(file);
|
||||
case "cbr" -> extractFirstImageFromRar(file);
|
||||
default -> Optional.empty();
|
||||
};
|
||||
}
|
||||
|
||||
private Optional<BufferedImage> extractFirstImageFromZip(File file) {
|
||||
@@ -144,7 +146,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
.min(Comparator.comparing(ZipArchiveEntry::getName))
|
||||
.map(entry -> {
|
||||
try (InputStream is = zipFile.getInputStream(entry)) {
|
||||
return ImageIO.read(is);
|
||||
return FileService.readImage(is);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage());
|
||||
return null;
|
||||
@@ -175,7 +177,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
if (bytesRead < 0) break;
|
||||
offset += bytesRead;
|
||||
}
|
||||
return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(content)));
|
||||
return Optional.ofNullable(FileService.readImage(new ByteArrayInputStream(content)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -196,7 +198,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
for (FileHeader header : imageHeaders) {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
archive.extractFile(header, baos);
|
||||
return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(baos.toByteArray())));
|
||||
return Optional.ofNullable(FileService.readImage(new ByteArrayInputStream(baos.toByteArray())));
|
||||
} catch (Exception e) {
|
||||
log.warn("Error reading RAR entry {}: {}", header.getFileName(), e.getMessage());
|
||||
}
|
||||
@@ -242,8 +244,12 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
|
||||
private void setMetadata(BookEntity bookEntity) {
|
||||
String baseName = new File(bookEntity.getFileName()).getName();
|
||||
String title = UNDERSCORE_HYPHEN_PATTERN.matcher(CBX_FILE_EXTENSION_PATTERN.matcher(baseName).replaceAll("")).replaceAll(" ")
|
||||
.trim();
|
||||
String extension = FileUtils.getExtension(baseName);
|
||||
if (BookFileType.CBX.supports(extension)) {
|
||||
baseName = baseName.substring(0, baseName.length() - extension.length() - 1);
|
||||
}
|
||||
String title = UNDERSCORE_HYPHEN_PATTERN.matcher(baseName).replaceAll(" ").trim();
|
||||
bookEntity.getMetadata().setTitle(truncate(title, 1000));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -68,9 +68,9 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
|
||||
|
||||
boolean saved;
|
||||
try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) {
|
||||
BufferedImage originalImage = ImageIO.read(bais);
|
||||
BufferedImage originalImage = FileService.readImage(bais);
|
||||
if (originalImage == null) {
|
||||
log.warn("Cover image found but could not be decoded (possibly SVG or unsupported format) in EPUB '{}'", bookEntity.getFileName());
|
||||
log.warn("Failed to decode cover image for EPUB '{}'", bookEntity.getFileName());
|
||||
return false;
|
||||
}
|
||||
saved = fileService.saveCoverImages(originalImage, bookEntity.getId());
|
||||
|
||||
+6
-7
@@ -125,13 +125,12 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce
|
||||
}
|
||||
|
||||
private boolean saveCoverImage(byte[] coverData, long bookId) throws Exception {
|
||||
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(coverData));
|
||||
try {
|
||||
return fileService.saveCoverImages(originalImage, bookId);
|
||||
} finally {
|
||||
if (originalImage != null) {
|
||||
originalImage.flush(); // Release resources after processing
|
||||
}
|
||||
BufferedImage originalImage = FileService.readImage(coverData);
|
||||
if (originalImage == null) {
|
||||
log.warn("Failed to decode cover image for FB2");
|
||||
return false;
|
||||
}
|
||||
|
||||
return fileService.saveCoverImages(originalImage, bookId);
|
||||
}
|
||||
}
|
||||
|
||||
+132
-15
@@ -1,14 +1,12 @@
|
||||
package com.adityachandel.booklore.service.hardcover;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.KoboSyncSettings;
|
||||
import com.adityachandel.booklore.model.dto.HardcoverSyncSettings;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.kobo.KoboSettingsService;
|
||||
import com.adityachandel.booklore.service.metadata.parser.hardcover.GraphQLRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
@@ -25,7 +23,7 @@ import java.util.Map;
|
||||
/**
|
||||
* Service to sync reading progress to Hardcover.
|
||||
* Uses per-user Hardcover API tokens for reading progress sync.
|
||||
* Each user can configure their own Hardcover API key in Kobo settings.
|
||||
* Each user can configure their own Hardcover API key in their sync settings.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -36,15 +34,15 @@ public class HardcoverSyncService {
|
||||
private static final int STATUS_READ = 3;
|
||||
|
||||
private final RestClient restClient;
|
||||
private final KoboSettingsService koboSettingsService;
|
||||
private final HardcoverSyncSettingsService hardcoverSyncSettingsService;
|
||||
private final BookRepository bookRepository;
|
||||
|
||||
// Thread-local to hold the current API token for GraphQL requests
|
||||
private final ThreadLocal<String> currentApiToken = new ThreadLocal<>();
|
||||
|
||||
@Autowired
|
||||
public HardcoverSyncService(@Lazy KoboSettingsService koboSettingsService, BookRepository bookRepository) {
|
||||
this.koboSettingsService = koboSettingsService;
|
||||
public HardcoverSyncService(HardcoverSyncSettingsService hardcoverSyncSettingsService, BookRepository bookRepository) {
|
||||
this.hardcoverSyncSettingsService = hardcoverSyncSettingsService;
|
||||
this.bookRepository = bookRepository;
|
||||
this.restClient = RestClient.builder()
|
||||
.baseUrl(HARDCOVER_API_URL)
|
||||
@@ -65,7 +63,7 @@ public class HardcoverSyncService {
|
||||
public void syncProgressToHardcover(Long bookId, Float progressPercent, Long userId) {
|
||||
try {
|
||||
// Get user's Hardcover settings
|
||||
KoboSyncSettings userSettings = koboSettingsService.getSettingsByUserId(userId);
|
||||
HardcoverSyncSettings userSettings = hardcoverSyncSettingsService.getSettingsForUserId(userId);
|
||||
|
||||
if (!isHardcoverSyncEnabledForUser(userSettings)) {
|
||||
log.trace("Hardcover sync skipped for user {}: not enabled or no API token configured", userId);
|
||||
@@ -102,6 +100,18 @@ public class HardcoverSyncService {
|
||||
hardcoverBook.bookId = metadata.getHardcoverBookId();
|
||||
hardcoverBook.pages = metadata.getPageCount();
|
||||
log.debug("Using stored Hardcover book ID: {}", hardcoverBook.bookId);
|
||||
|
||||
if (hardcoverBook.bookId != null && (hardcoverBook.pages == null || hardcoverBook.pages <= 0 || hardcoverBook.editionId == null)) {
|
||||
HardcoverBookInfo fetched = findHardcoverBookById(hardcoverBook.bookId);
|
||||
if (fetched != null) {
|
||||
if (hardcoverBook.editionId == null) {
|
||||
hardcoverBook.editionId = fetched.editionId;
|
||||
}
|
||||
if ((hardcoverBook.pages == null || hardcoverBook.pages <= 0) && fetched.pages != null) {
|
||||
hardcoverBook.pages = fetched.pages;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Search by ISBN
|
||||
hardcoverBook = findHardcoverBook(metadata);
|
||||
@@ -152,7 +162,7 @@ public class HardcoverSyncService {
|
||||
/**
|
||||
* Check if Hardcover sync is enabled for a specific user.
|
||||
*/
|
||||
private boolean isHardcoverSyncEnabledForUser(KoboSyncSettings userSettings) {
|
||||
private boolean isHardcoverSyncEnabledForUser(HardcoverSyncSettings userSettings) {
|
||||
if (userSettings == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -247,15 +257,17 @@ public class HardcoverSyncService {
|
||||
}
|
||||
|
||||
// If no default edition, try to look up edition by ISBN
|
||||
// This also gets the page count from the specific edition
|
||||
if (info.bookId != null) {
|
||||
if (info.bookId != null && info.editionId == null) {
|
||||
EditionInfo edition = findEditionByIsbn(info.bookId, isbn);
|
||||
if (edition != null) {
|
||||
info.editionId = edition.id;
|
||||
// Prefer edition page count over book page count
|
||||
if (edition.pages != null && edition.pages > 0) {
|
||||
info.pages = edition.pages;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (info.editionId != null && (info.pages == null || info.pages <= 0)) {
|
||||
EditionInfo edition = findEditionById(info.editionId);
|
||||
if (edition != null && edition.pages != null && edition.pages > 0) {
|
||||
info.pages = edition.pages;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,6 +338,111 @@ public class HardcoverSyncService {
|
||||
}
|
||||
}
|
||||
|
||||
private EditionInfo findEditionById(Integer editionId) {
|
||||
String query = """
|
||||
query FindEditionById($editionId: Int!) {
|
||||
editions(where: {id: {_eq: $editionId}}, limit: 1) {
|
||||
id
|
||||
pages
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
GraphQLRequest request = new GraphQLRequest();
|
||||
request.setQuery(query);
|
||||
request.setVariables(Map.of("editionId", editionId));
|
||||
|
||||
try {
|
||||
Map<String, Object> response = executeGraphQL(request);
|
||||
if (response == null) return null;
|
||||
|
||||
Map<String, Object> data = (Map<String, Object>) response.get("data");
|
||||
if (data == null) return null;
|
||||
|
||||
List<Map<String, Object>> editions = (List<Map<String, Object>>) data.get("editions");
|
||||
if (editions == null || editions.isEmpty()) return null;
|
||||
|
||||
Map<String, Object> edition = editions.getFirst();
|
||||
EditionInfo info = new EditionInfo();
|
||||
|
||||
Object idObj = edition.get("id");
|
||||
if (idObj instanceof Number) {
|
||||
info.id = ((Number) idObj).intValue();
|
||||
}
|
||||
|
||||
Object pagesObj = edition.get("pages");
|
||||
if (pagesObj instanceof Number) {
|
||||
info.pages = ((Number) pagesObj).intValue();
|
||||
}
|
||||
|
||||
return info.id != null ? info : null;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to find edition by ID: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private HardcoverBookInfo findHardcoverBookById(Integer bookId) {
|
||||
String query = """
|
||||
query FindBookById($bookId: Int!) {
|
||||
books(where: {id: {_eq: $bookId}}, limit: 1) {
|
||||
id
|
||||
default_edition_id
|
||||
pages
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
GraphQLRequest request = new GraphQLRequest();
|
||||
request.setQuery(query);
|
||||
request.setVariables(Map.of("bookId", bookId));
|
||||
|
||||
try {
|
||||
Map<String, Object> response = executeGraphQL(request);
|
||||
if (response == null) return null;
|
||||
|
||||
Map<String, Object> data = (Map<String, Object>) response.get("data");
|
||||
if (data == null) return null;
|
||||
|
||||
List<Map<String, Object>> books = (List<Map<String, Object>>) data.get("books");
|
||||
if (books == null || books.isEmpty()) return null;
|
||||
|
||||
Map<String, Object> book = books.getFirst();
|
||||
HardcoverBookInfo info = new HardcoverBookInfo();
|
||||
info.bookId = bookId;
|
||||
|
||||
Object defaultEditionObj = book.get("default_edition_id");
|
||||
if (defaultEditionObj instanceof Number) {
|
||||
info.editionId = ((Number) defaultEditionObj).intValue();
|
||||
} else if (defaultEditionObj instanceof String) {
|
||||
try {
|
||||
info.editionId = Integer.parseInt((String) defaultEditionObj);
|
||||
} catch (NumberFormatException e) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
Object pagesObj = book.get("pages");
|
||||
if (pagesObj instanceof Number) {
|
||||
info.pages = ((Number) pagesObj).intValue();
|
||||
}
|
||||
|
||||
if (info.editionId != null && (info.pages == null || info.pages <= 0)) {
|
||||
EditionInfo edition = findEditionById(info.editionId);
|
||||
if (edition != null && edition.pages != null && edition.pages > 0) {
|
||||
info.pages = edition.pages;
|
||||
}
|
||||
}
|
||||
|
||||
return info.editionId != null || info.pages != null ? info : null;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to find Hardcover book by ID {}: {}", bookId, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a book into the user's library or get existing user_book_id.
|
||||
*/
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.adityachandel.booklore.service.hardcover;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.HardcoverSyncSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserSettingEntity;
|
||||
import com.adityachandel.booklore.repository.KoboUserSettingsRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class HardcoverSyncSettingsService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final KoboUserSettingsRepository koboUserSettingsRepository;
|
||||
|
||||
@Transactional
|
||||
public HardcoverSyncSettings getCurrentUserSettings() {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
return getSettingsForUserId(user.getId());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public HardcoverSyncSettings getSettingsForUserId(Long userId) {
|
||||
BookLoreUserEntity user = userRepository.findById(userId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
return readSettings(user, userId);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public HardcoverSyncSettings updateCurrentUserSettings(HardcoverSyncSettings settings) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
return updateSettingsForUserId(user.getId(), settings);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public HardcoverSyncSettings updateSettingsForUserId(Long userId, HardcoverSyncSettings settings) {
|
||||
if (settings == null) {
|
||||
throw ApiError.INVALID_INPUT.createException("Hardcover settings cannot be null.");
|
||||
}
|
||||
|
||||
BookLoreUserEntity user = userRepository.findById(userId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
|
||||
String apiKey = settings.getHardcoverApiKey();
|
||||
if (apiKey == null) {
|
||||
apiKey = "";
|
||||
} else {
|
||||
apiKey = apiKey.trim();
|
||||
}
|
||||
upsertSetting(user, UserSettingKey.HARDCOVER_API_KEY, apiKey);
|
||||
upsertSetting(user, UserSettingKey.HARDCOVER_SYNC_ENABLED, Boolean.toString(settings.isHardcoverSyncEnabled()));
|
||||
|
||||
userRepository.save(user);
|
||||
|
||||
HardcoverSyncSettings updated = new HardcoverSyncSettings();
|
||||
updated.setHardcoverApiKey(apiKey);
|
||||
updated.setHardcoverSyncEnabled(settings.isHardcoverSyncEnabled());
|
||||
return updated;
|
||||
}
|
||||
|
||||
private HardcoverSyncSettings readSettings(BookLoreUserEntity user, Long userId) {
|
||||
UserSettingEntity apiKeySetting = findSetting(user, UserSettingKey.HARDCOVER_API_KEY).orElse(null);
|
||||
UserSettingEntity syncEnabledSetting = findSetting(user, UserSettingKey.HARDCOVER_SYNC_ENABLED).orElse(null);
|
||||
|
||||
String apiKey = apiKeySetting != null ? apiKeySetting.getSettingValue() : null;
|
||||
boolean syncEnabled = syncEnabledSetting != null && Boolean.parseBoolean(syncEnabledSetting.getSettingValue());
|
||||
|
||||
boolean shouldSave = false;
|
||||
if (apiKeySetting == null || syncEnabledSetting == null) {
|
||||
KoboUserSettingsEntity legacySettings = koboUserSettingsRepository.findByUserId(userId).orElse(null);
|
||||
if (legacySettings != null) {
|
||||
if (apiKeySetting == null && legacySettings.getHardcoverApiKey() != null && !legacySettings.getHardcoverApiKey().isBlank()) {
|
||||
apiKey = legacySettings.getHardcoverApiKey();
|
||||
upsertSetting(user, UserSettingKey.HARDCOVER_API_KEY, apiKey);
|
||||
shouldSave = true;
|
||||
}
|
||||
if (syncEnabledSetting == null && legacySettings.isHardcoverSyncEnabled()) {
|
||||
syncEnabled = legacySettings.isHardcoverSyncEnabled();
|
||||
upsertSetting(user, UserSettingKey.HARDCOVER_SYNC_ENABLED, Boolean.toString(syncEnabled));
|
||||
shouldSave = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (shouldSave) {
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
HardcoverSyncSettings settings = new HardcoverSyncSettings();
|
||||
settings.setHardcoverApiKey(apiKey);
|
||||
settings.setHardcoverSyncEnabled(syncEnabled);
|
||||
return settings;
|
||||
}
|
||||
|
||||
private Optional<UserSettingEntity> findSetting(BookLoreUserEntity user, UserSettingKey key) {
|
||||
return user.getSettings().stream()
|
||||
.filter(setting -> key.getDbKey().equals(setting.getSettingKey()))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private void upsertSetting(BookLoreUserEntity user, UserSettingKey key, String value) {
|
||||
UserSettingEntity setting = findSetting(user, key)
|
||||
.orElseGet(() -> {
|
||||
UserSettingEntity newSetting = new UserSettingEntity();
|
||||
newSetting.setUser(user);
|
||||
newSetting.setSettingKey(key.getDbKey());
|
||||
user.getSettings().add(newSetting);
|
||||
return newSetting;
|
||||
});
|
||||
setting.setSettingValue(value);
|
||||
}
|
||||
}
|
||||
+11
-2
@@ -21,6 +21,8 @@ import com.github.junrar.exception.RarException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.FileSystemUtils;
|
||||
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageWriteParam;
|
||||
import javax.imageio.ImageWriter;
|
||||
@@ -314,7 +316,8 @@ public class CbxConversionService {
|
||||
|
||||
return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") ||
|
||||
lowerName.endsWith(".png") || lowerName.endsWith(".webp") ||
|
||||
lowerName.endsWith(".gif") || lowerName.endsWith(".bmp");
|
||||
lowerName.endsWith(".gif") || lowerName.endsWith(".bmp") ||
|
||||
lowerName.endsWith(".avif") || lowerName.endsWith(".heic");
|
||||
}
|
||||
|
||||
private boolean isJpegFile(Path path) {
|
||||
@@ -404,7 +407,13 @@ public class CbxConversionService {
|
||||
}
|
||||
} else {
|
||||
try (InputStream fis = Files.newInputStream(sourceImagePath)) {
|
||||
BufferedImage image = ImageIO.read(fis);
|
||||
BufferedImage image = null;
|
||||
try {
|
||||
image = FileService.readImage(fis);
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to decode image {} with FileService: {}", sourceImagePath, e.getMessage());
|
||||
}
|
||||
|
||||
if (image != null) {
|
||||
writeJpegImage(image, zipOut, compressionPercentage/100f);
|
||||
} else {
|
||||
|
||||
+12
-2
@@ -17,6 +17,7 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Collections;
|
||||
@@ -208,13 +209,22 @@ public class KoboEntitlementService {
|
||||
.orElse(Collections.emptyList());
|
||||
|
||||
KoboBookMetadata.Series series = null;
|
||||
if (metadata.getSeriesName() != null) {
|
||||
if (metadata.getSeriesName() != null && !metadata.getSeriesName().isBlank()) {
|
||||
series = KoboBookMetadata.Series.builder()
|
||||
.id("series_" + metadata.getSeriesName().hashCode())
|
||||
.name(metadata.getSeriesName())
|
||||
.number(metadata.getSeriesNumber() != null ? metadata.getSeriesNumber().toString() : "1")
|
||||
.number(metadata.getSeriesNumber() != null
|
||||
? BigDecimal.valueOf(metadata.getSeriesNumber()).stripTrailingZeros().toPlainString()
|
||||
: "1")
|
||||
.numberFloat(metadata.getSeriesNumber() != null ? metadata.getSeriesNumber().doubleValue() : 1.0)
|
||||
.build();
|
||||
} else {
|
||||
series = KoboBookMetadata.Series.builder()
|
||||
.id("")
|
||||
.name("")
|
||||
.number("")
|
||||
.numberFloat(0.0)
|
||||
.build();
|
||||
}
|
||||
|
||||
String downloadUrl = koboUrlBuilder.downloadUrl(token, book.getId());
|
||||
|
||||
+17
-9
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.service.kobo;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.HardcoverSyncSettings;
|
||||
import com.adityachandel.booklore.model.dto.KoboSyncSettings;
|
||||
import com.adityachandel.booklore.model.dto.Shelf;
|
||||
import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest;
|
||||
@@ -11,6 +12,7 @@ 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;
|
||||
import com.adityachandel.booklore.service.hardcover.HardcoverSyncSettingsService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -25,6 +27,7 @@ public class KoboSettingsService {
|
||||
private final KoboUserSettingsRepository repository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final ShelfService shelfService;
|
||||
private final HardcoverSyncSettingsService hardcoverSyncSettingsService;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public KoboSyncSettings getCurrentUserSettings() {
|
||||
@@ -82,12 +85,8 @@ public class KoboSettingsService {
|
||||
|
||||
entity.setAutoAddToShelf(settings.isAutoAddToShelf());
|
||||
|
||||
// Update Hardcover settings
|
||||
entity.setHardcoverApiKey(settings.getHardcoverApiKey());
|
||||
entity.setHardcoverSyncEnabled(settings.isHardcoverSyncEnabled());
|
||||
|
||||
repository.save(entity);
|
||||
return mapToDto(entity);
|
||||
return mapToDto(entity, hardcoverSyncSettingsService.getSettingsForUserId(user.getId()));
|
||||
}
|
||||
|
||||
private KoboUserSettingsEntity initDefaultSettings(Long userId) {
|
||||
@@ -118,6 +117,11 @@ public class KoboSettingsService {
|
||||
}
|
||||
|
||||
private KoboSyncSettings mapToDto(KoboUserSettingsEntity entity) {
|
||||
HardcoverSyncSettings hardcoverSettings = hardcoverSyncSettingsService.getSettingsForUserId(entity.getUserId());
|
||||
return mapToDto(entity, hardcoverSettings);
|
||||
}
|
||||
|
||||
private KoboSyncSettings mapToDto(KoboUserSettingsEntity entity, HardcoverSyncSettings hardcoverSettings) {
|
||||
KoboSyncSettings dto = new KoboSyncSettings();
|
||||
dto.setId(entity.getId());
|
||||
dto.setUserId(entity.getUserId().toString());
|
||||
@@ -126,14 +130,17 @@ public class KoboSettingsService {
|
||||
dto.setProgressMarkAsReadingThreshold(entity.getProgressMarkAsReadingThreshold());
|
||||
dto.setProgressMarkAsFinishedThreshold(entity.getProgressMarkAsFinishedThreshold());
|
||||
dto.setAutoAddToShelf(entity.isAutoAddToShelf());
|
||||
dto.setHardcoverApiKey(entity.getHardcoverApiKey());
|
||||
dto.setHardcoverSyncEnabled(entity.isHardcoverSyncEnabled());
|
||||
if (hardcoverSettings != null) {
|
||||
dto.setHardcoverApiKey(hardcoverSettings.getHardcoverApiKey());
|
||||
dto.setHardcoverSyncEnabled(hardcoverSettings.isHardcoverSyncEnabled());
|
||||
} else {
|
||||
dto.setHardcoverSyncEnabled(false);
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Hardcover settings for a specific user by ID.
|
||||
* Used by HardcoverSyncService to get user-specific API key.
|
||||
* Get Kobo settings for a specific user by ID.
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public KoboSyncSettings getSettingsByUserId(Long userId) {
|
||||
@@ -141,4 +148,5 @@ public class KoboSettingsService {
|
||||
.map(this::mapToDto)
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+15
@@ -22,6 +22,7 @@ import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.KoreaderUserRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.hardcover.HardcoverSyncService;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@@ -32,6 +33,7 @@ public class KoreaderService {
|
||||
private final BookRepository bookRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final KoreaderUserRepository koreaderUserRepository;
|
||||
private final HardcoverSyncService hardcoverSyncService;
|
||||
|
||||
public ResponseEntity<Map<String, String>> authorizeUser() {
|
||||
KoreaderUserDetails authDetails = getAuthDetails();
|
||||
@@ -76,6 +78,9 @@ public class KoreaderService {
|
||||
progressRepository.save(userProgress);
|
||||
|
||||
log.info("saveProgress: saved progress='{}' percentage={} for userId={} bookHash={}", koProgress.getProgress(), koProgress.getPercentage(), authDetails.getBookLoreUserId(), bookHash);
|
||||
|
||||
Float progressPercent = normalizeProgressPercent(koProgress.getPercentage());
|
||||
hardcoverSyncService.syncProgressToHardcover(book.getId(), progressPercent, authDetails.getBookLoreUserId());
|
||||
}
|
||||
|
||||
private void updateProgressData(UserBookProgressEntity userProgress, KoreaderProgress koProgress) {
|
||||
@@ -101,6 +106,16 @@ public class KoreaderService {
|
||||
}
|
||||
}
|
||||
|
||||
private Float normalizeProgressPercent(Float progress) {
|
||||
if (progress == null) {
|
||||
return null;
|
||||
}
|
||||
if (progress <= 1.0f) {
|
||||
return progress * 100.0f;
|
||||
}
|
||||
return progress;
|
||||
}
|
||||
|
||||
private KoreaderUserDetails getAuthDetails() {
|
||||
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
if (!(principal instanceof KoreaderUserDetails details)) {
|
||||
|
||||
+49
-24
@@ -5,19 +5,24 @@ import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileExtension;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jspecify.annotations.NonNull;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileVisitOption;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class LibraryFileHelper {
|
||||
|
||||
public List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
@@ -31,30 +36,50 @@ public class LibraryFileHelper {
|
||||
private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
Path libraryPath = Path.of(pathEntity.getPath());
|
||||
boolean supportsSupplementaryFiles = processor.supportsSupplementaryFiles();
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
try (Stream<Path> stream = Files.walk(libraryPath, FileVisitOption.FOLLOW_LINKS)) {
|
||||
return stream
|
||||
.filter(Files::isReadable)
|
||||
.filter(Files::isRegularFile)
|
||||
.filter(path -> !FileUtils.shouldIgnore(path))
|
||||
.map(fullPath -> {
|
||||
String fileName = fullPath.getFileName().toString();
|
||||
Optional<BookFileExtension> bookExtension = BookFileExtension.fromFileName(fileName);
|
||||
Files.walkFileTree(libraryPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<>() {
|
||||
@Override
|
||||
@NonNull
|
||||
public FileVisitResult visitFile(@NonNull Path file, @NonNull BasicFileAttributes attrs) {
|
||||
if (FileUtils.shouldIgnore(file) || !Files.isReadable(file) || !Files.isRegularFile(file)) {
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
if (bookExtension.isEmpty() && !supportsSupplementaryFiles) {
|
||||
return null;
|
||||
}
|
||||
String fileName = file.getFileName().toString();
|
||||
Optional<BookFileExtension> bookExtension = BookFileExtension.fromFileName(fileName);
|
||||
|
||||
return LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), fullPath))
|
||||
.fileName(fileName)
|
||||
.bookFileType(bookExtension.map(BookFileExtension::getType).orElse(null))
|
||||
.build();
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
}
|
||||
if (bookExtension.isEmpty() && !supportsSupplementaryFiles) {
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
libraryFiles.add(LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), file))
|
||||
.fileName(fileName)
|
||||
.bookFileType(bookExtension.map(BookFileExtension::getType).orElse(null))
|
||||
.build());
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public FileVisitResult visitFileFailed(@NonNull Path file, IOException e) {
|
||||
log.error("Failed read path [{}]: {}", file, e.getMessage(), e);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public FileVisitResult preVisitDirectory(@NonNull Path dir, @NonNull BasicFileAttributes attrs) throws IOException {
|
||||
if (FileUtils.shouldIgnore(dir) || !Files.isReadable(dir)) {
|
||||
return FileVisitResult.SKIP_SUBTREE;
|
||||
}
|
||||
|
||||
return super.preVisitDirectory(dir, attrs);
|
||||
}
|
||||
});
|
||||
return libraryFiles;
|
||||
}
|
||||
}
|
||||
|
||||
+55
-2
@@ -13,6 +13,7 @@ import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
@@ -33,9 +34,14 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@@ -250,4 +256,51 @@ public class LibraryService {
|
||||
library.setFileNamingPattern(pattern);
|
||||
return libraryMapper.toLibrary(libraryRepository.save(library));
|
||||
}
|
||||
}
|
||||
|
||||
public int scanLibraryPaths(CreateLibraryRequest request) {
|
||||
int count = 0;
|
||||
if (request.getPaths() == null || request.getPaths().isEmpty()) {
|
||||
return count;
|
||||
}
|
||||
for (LibraryPath libraryPath : request.getPaths()) {
|
||||
Path path = Paths.get(libraryPath.getPath());
|
||||
if (!Files.exists(path)) {
|
||||
log.warn("Path does not exist: {}", path);
|
||||
continue;
|
||||
}
|
||||
if (Files.isDirectory(path)) {
|
||||
count += scanDirectory(path);
|
||||
} else if (Files.isRegularFile(path) && isProcessableFile(path)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private int scanDirectory(Path directory) {
|
||||
int count = 0;
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
|
||||
for (Path entry : stream) {
|
||||
if (Files.isDirectory(entry)) {
|
||||
count += scanDirectory(entry);
|
||||
} else if (Files.isRegularFile(entry) && isProcessableFile(entry)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error scanning directory: {}", directory, e);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private boolean isProcessableFile(Path file) {
|
||||
String fileName = file.getFileName().toString().toLowerCase();
|
||||
for (BookFileType fileType : BookFileType.values()) {
|
||||
if (fileName.endsWith("." + fileType.name().toLowerCase())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+149
-116
@@ -1,8 +1,6 @@
|
||||
package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
@@ -10,6 +8,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.websocket.LogNotification;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.projection.BookCoverUpdateProjection;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.book.BookQueryService;
|
||||
@@ -29,7 +28,9 @@ import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -41,7 +42,6 @@ public class BookCoverService {
|
||||
private static final int BATCH_SIZE = 100;
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookMetadataMapper bookMetadataMapper;
|
||||
private final NotificationService notificationService;
|
||||
private final AppSettingService appSettingService;
|
||||
private final FileService fileService;
|
||||
@@ -54,79 +54,153 @@ public class BookCoverService {
|
||||
private record BookCoverInfo(Long id, String title) {
|
||||
}
|
||||
|
||||
private record BookRegenerationInfo(Long id, String title, BookFileType bookType) {
|
||||
private record BookRegenerationInfo(Long id, String title, BookFileType bookType, boolean coverLocked) {
|
||||
}
|
||||
|
||||
// =========================
|
||||
// SECTION: COVER UPDATES
|
||||
// =========================
|
||||
|
||||
/**
|
||||
* Generate a custom cover for a single book.
|
||||
*/
|
||||
public void generateCustomCover(long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
if (isCoverLocked(bookEntity)) {
|
||||
throw ApiError.METADATA_LOCKED.createException();
|
||||
}
|
||||
|
||||
String title = bookEntity.getMetadata().getTitle();
|
||||
String author = getAuthorNames(bookEntity);
|
||||
byte[] coverBytes = coverImageGenerator.generateCover(title, author);
|
||||
|
||||
fileService.createThumbnailFromBytes(bookId, coverBytes);
|
||||
writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromBytes(book, coverBytes));
|
||||
updateBookCoverMetadata(bookEntity);
|
||||
bookRepository.save(bookEntity);
|
||||
notifyBookCoverUpdate(bookEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update cover image from uploaded file for a single book.
|
||||
*/
|
||||
@Transactional
|
||||
public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) {
|
||||
public void updateCoverFromFile(Long bookId, MultipartFile file) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
if (isCoverLocked(bookEntity)) {
|
||||
throw ApiError.METADATA_LOCKED.createException();
|
||||
}
|
||||
|
||||
fileService.createThumbnailFromFile(bookId, file);
|
||||
return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUpload(book, file));
|
||||
writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromUpload(book, file));
|
||||
updateBookCoverMetadata(bookEntity);
|
||||
bookRepository.save(bookEntity);
|
||||
notifyBookCoverUpdate(bookEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update cover image from a URL for a single book.
|
||||
*/
|
||||
@Transactional
|
||||
public BookMetadata updateCoverImageFromUrl(Long bookId, String url) {
|
||||
public void updateCoverFromUrl(Long bookId, String url) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
if (isCoverLocked(bookEntity)) {
|
||||
throw ApiError.METADATA_LOCKED.createException();
|
||||
}
|
||||
|
||||
fileService.createThumbnailFromUrl(bookId, url);
|
||||
return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUrl(book, url));
|
||||
writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromUrl(book, url));
|
||||
updateBookCoverMetadata(bookEntity);
|
||||
bookRepository.save(bookEntity);
|
||||
notifyBookCoverUpdate(bookEntity);
|
||||
}
|
||||
|
||||
public void updateCoverImageFromFileForBooks(Set<Long> bookIds, MultipartFile file) {
|
||||
/**
|
||||
* Bulk update cover images from a file for multiple books.
|
||||
*/
|
||||
public void updateCoverFromFileForBooks(Set<Long> bookIds, MultipartFile file) {
|
||||
validateCoverFile(file);
|
||||
byte[] coverImageBytes = extractBytesFromMultipartFile(file);
|
||||
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
|
||||
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverUpdate(unlockedBooks, coverImageBytes));
|
||||
}
|
||||
|
||||
public void regenerateCover(long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
// =========================
|
||||
// SECTION: COVER REGENERATION
|
||||
// =========================
|
||||
|
||||
/**
|
||||
* Regenerate cover for a single book.
|
||||
*/
|
||||
public void regenerateCover(long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
if (isCoverLocked(bookEntity)) {
|
||||
throw ApiError.METADATA_LOCKED.createException();
|
||||
}
|
||||
|
||||
regenerateCoverForBook(bookEntity, "");
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookEntity.getBookType());
|
||||
boolean success = processor.generateCover(bookEntity);
|
||||
if (!success) {
|
||||
throw ApiError.FAILED_TO_REGENERATE_COVER.createException();
|
||||
}
|
||||
updateBookCoverMetadata(bookEntity);
|
||||
bookRepository.save(bookEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate covers for a set of books.
|
||||
*/
|
||||
public void regenerateCoversForBooks(Set<Long> bookIds) {
|
||||
List<BookRegenerationInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds);
|
||||
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks));
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate covers for all books.
|
||||
*/
|
||||
public void regenerateCovers() {
|
||||
SecurityContextVirtualThread.runWithSecurityContext(() -> {
|
||||
try {
|
||||
List<BookEntity> books = bookQueryService.getAllFullBookEntities().stream()
|
||||
List<BookRegenerationInfo> books = bookQueryService.getAllFullBookEntities().stream()
|
||||
.filter(book -> !isCoverLocked(book))
|
||||
.map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType(), false))
|
||||
.toList();
|
||||
int total = books.size();
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " books"));
|
||||
|
||||
int current = 1;
|
||||
for (BookEntity book : books) {
|
||||
List<Long> refreshedIds = new ArrayList<>();
|
||||
|
||||
for (BookRegenerationInfo bookInfo : books) {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
regenerateCoverForBook(book, progress);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findById(bookInfo.id()).ifPresent(book -> {
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType());
|
||||
boolean success = processor.generateCover(book);
|
||||
|
||||
if (success) {
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
refreshedIds.add(book.getId());
|
||||
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), bookInfo.title());
|
||||
} else {
|
||||
log.warn("{}Failed to regenerate cover for book ID {} ({})", progress, book.getId(), bookInfo.title());
|
||||
}
|
||||
});
|
||||
return null;
|
||||
});
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to regenerate cover for book ID {}: {}", book.getId(), e.getMessage(), e);
|
||||
log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
|
||||
}
|
||||
current++;
|
||||
}
|
||||
|
||||
notifyBulkCoverUpdate(refreshedIds);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers"));
|
||||
} catch (Exception e) {
|
||||
log.error("Error during cover regeneration: {}", e.getMessage(), e);
|
||||
@@ -135,30 +209,9 @@ public class BookCoverService {
|
||||
});
|
||||
}
|
||||
|
||||
private BookMetadata updateCover(Long bookId, BiConsumer<MetadataWriter, BookEntity> writerAction) {
|
||||
BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(Collections.singleton(bookId)).stream()
|
||||
.findFirst()
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
updateBookCoverMetadata(bookEntity);
|
||||
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
boolean saveToOriginalFile = settings.isSaveToOriginalFile();
|
||||
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
|
||||
|
||||
if (saveToOriginalFile && (bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) {
|
||||
metadataWriterFactory.getWriter(bookEntity.getBookType())
|
||||
.ifPresent(writer -> {
|
||||
writerAction.accept(writer, bookEntity);
|
||||
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
|
||||
bookEntity.setCurrentHash(newHash);
|
||||
});
|
||||
}
|
||||
|
||||
bookEntity.setMetadataUpdatedAt(Instant.now());
|
||||
bookRepository.save(bookEntity);
|
||||
return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
|
||||
}
|
||||
// =========================
|
||||
// SECTION: BULK OPERATIONS
|
||||
// =========================
|
||||
|
||||
private void processBulkCoverUpdate(List<BookCoverInfo> books, byte[] coverImageBytes) {
|
||||
try {
|
||||
@@ -166,24 +219,32 @@ public class BookCoverService {
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started updating covers for " + total + " selected book(s)"));
|
||||
|
||||
int current = 1;
|
||||
List<Long> refreshedIds = new ArrayList<>();
|
||||
|
||||
for (BookCoverInfo bookInfo : books) {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Updating cover for: " + bookInfo.title()));
|
||||
fileService.createThumbnailFromBytes(bookInfo.id(), coverImageBytes);
|
||||
|
||||
bookRepository.findById(bookInfo.id()).ifPresent(book -> {
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findById(bookInfo.id()).ifPresent(book -> {
|
||||
fileService.createThumbnailFromBytes(bookInfo.id(), coverImageBytes);
|
||||
writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverImageBytes));
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
refreshedIds.add(book.getId());
|
||||
});
|
||||
return null;
|
||||
});
|
||||
|
||||
log.info("{}Successfully updated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to update cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
|
||||
}
|
||||
pauseAfterBatchIfNeeded(current, total);
|
||||
current++;
|
||||
}
|
||||
|
||||
notifyBulkCoverUpdate(refreshedIds);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished updating covers for selected books"));
|
||||
} catch (Exception e) {
|
||||
log.error("Error during cover update: {}", e.getMessage(), e);
|
||||
@@ -203,13 +264,25 @@ public class BookCoverService {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
||||
regenerateCoverForBookId(bookInfo);
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findById(bookInfo.id()).ifPresent(book -> {
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType());
|
||||
boolean success = processor.generateCover(book);
|
||||
|
||||
if (success) {
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
refreshedIds.add(book.getId());
|
||||
}
|
||||
});
|
||||
return null;
|
||||
});
|
||||
|
||||
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
|
||||
refreshedIds.add(bookInfo.id());
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
|
||||
}
|
||||
pauseAfterBatchIfNeeded(current, total);
|
||||
current++;
|
||||
}
|
||||
|
||||
@@ -221,31 +294,9 @@ public class BookCoverService {
|
||||
}
|
||||
}
|
||||
|
||||
private void regenerateCoverForBook(BookEntity book, String progress) {
|
||||
String title = book.getMetadata().getTitle();
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + title));
|
||||
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getBookType());
|
||||
boolean success = processor.generateCover(book);
|
||||
|
||||
if (success) {
|
||||
Instant now = Instant.now();
|
||||
book.getMetadata().setCoverUpdatedOn(now);
|
||||
book.setBookCoverHash(BookCoverUtils.generateCoverHash());
|
||||
}
|
||||
|
||||
log.info("{} regenerated cover regeneration for book ID {} ({}) finished with success={}", progress, book.getId(), title, success);
|
||||
if (!success) {
|
||||
throw ApiError.FAILED_TO_REGENERATE_COVER.createException();
|
||||
}
|
||||
}
|
||||
|
||||
private void regenerateCoverForBookId(BookRegenerationInfo bookInfo) {
|
||||
bookRepository.findById(bookInfo.id()).ifPresent(book -> {
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType());
|
||||
processor.generateCover(book);
|
||||
});
|
||||
}
|
||||
// =========================
|
||||
// SECTION: INTERNAL HELPERS
|
||||
// =========================
|
||||
|
||||
private void validateCoverFile(MultipartFile file) {
|
||||
if (file.isEmpty()) {
|
||||
@@ -280,7 +331,7 @@ public class BookCoverService {
|
||||
private List<BookRegenerationInfo> getUnlockedBookRegenerationInfos(Set<Long> bookIds) {
|
||||
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
|
||||
.filter(book -> !isCoverLocked(book))
|
||||
.map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType()))
|
||||
.map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType(), false))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@@ -297,6 +348,20 @@ public class BookCoverService {
|
||||
return null;
|
||||
}
|
||||
|
||||
private void writeCoverToBookFile(BookEntity bookEntity, BiConsumer<MetadataWriter, BookEntity> writerAction) {
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
|
||||
|
||||
if ((bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) {
|
||||
metadataWriterFactory.getWriter(bookEntity.getBookType())
|
||||
.ifPresent(writer -> {
|
||||
writerAction.accept(writer, bookEntity);
|
||||
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
|
||||
bookEntity.setCurrentHash(newHash);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void updateBookCoverMetadata(BookEntity bookEntity) {
|
||||
Instant now = Instant.now();
|
||||
bookEntity.setMetadataUpdatedAt(now);
|
||||
@@ -305,51 +370,19 @@ public class BookCoverService {
|
||||
}
|
||||
|
||||
private void notifyBookCoverUpdate(BookEntity bookEntity) {
|
||||
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, List.of(Map.of(
|
||||
"id", bookEntity.getId(),
|
||||
"coverUpdatedOn", bookEntity.getMetadata().getCoverUpdatedOn()
|
||||
)));
|
||||
List<BookCoverUpdateProjection> updates = bookRepository.findCoverUpdateInfoByIds(List.of(bookEntity.getId()));
|
||||
if (!updates.isEmpty()) {
|
||||
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, updates);
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyBulkCoverUpdate(List<Long> refreshedIds) {
|
||||
if (refreshedIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<Map<String, Object>> refreshedPatches = transactionTemplate.execute(status -> {
|
||||
List<BookEntity> entities = bookQueryService.findAllWithMetadataByIds(new HashSet<>(refreshedIds));
|
||||
if (entities == null || entities.isEmpty()) {
|
||||
return List.<Map<String, Object>>of();
|
||||
}
|
||||
|
||||
entities.forEach(e -> {
|
||||
if (e.getMetadata() != null) {
|
||||
e.getMetadata().getCoverUpdatedOn();
|
||||
}
|
||||
});
|
||||
|
||||
return entities.stream()
|
||||
.map(e -> Map.<String, Object>of(
|
||||
"id", e.getId(),
|
||||
"coverUpdatedOn", e.getMetadata() == null ? null : e.getMetadata().getCoverUpdatedOn()
|
||||
))
|
||||
.toList();
|
||||
});
|
||||
|
||||
if (refreshedPatches != null && !refreshedPatches.isEmpty()) {
|
||||
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, refreshedPatches);
|
||||
}
|
||||
}
|
||||
|
||||
private void pauseAfterBatchIfNeeded(int current, int total) {
|
||||
if (current % BATCH_SIZE == 0 && current < total) {
|
||||
try {
|
||||
log.info("Processed {} items, pausing briefly before next batch...", current);
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("Batch pause interrupted");
|
||||
}
|
||||
List<BookCoverUpdateProjection> updates = bookRepository.findCoverUpdateInfoByIds(refreshedIds);
|
||||
if (!updates.isEmpty()) {
|
||||
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, updates);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+16
-57
@@ -29,12 +29,14 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@@ -52,39 +54,22 @@ public class BookMetadataService {
|
||||
private final Map<MetadataProvider, BookParser> parserMap;
|
||||
private final CbxMetadataExtractor cbxMetadataExtractor;
|
||||
private final MetadataClearFlagsMapper metadataClearFlagsMapper;
|
||||
private final BookCoverService bookCoverService;
|
||||
|
||||
public void generateCustomCover(long bookId) {
|
||||
bookCoverService.generateCustomCover(bookId);
|
||||
}
|
||||
|
||||
public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
|
||||
public Flux<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
List<List<BookMetadata>> allMetadata = request.getProviders().stream()
|
||||
.map(provider -> CompletableFuture.supplyAsync(() -> fetchMetadataListFromAProvider(provider, book, request))
|
||||
.exceptionally(e -> {
|
||||
log.error("Error fetching metadata from provider: {}", provider, e);
|
||||
return List.of();
|
||||
}))
|
||||
.toList()
|
||||
.stream()
|
||||
.map(CompletableFuture::join)
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
|
||||
List<BookMetadata> interleavedMetadata = new ArrayList<>();
|
||||
int maxSize = allMetadata.stream().mapToInt(List::size).max().orElse(0);
|
||||
|
||||
for (int i = 0; i < maxSize; i++) {
|
||||
for (List<BookMetadata> metadataList : allMetadata) {
|
||||
if (i < metadataList.size()) {
|
||||
interleavedMetadata.add(metadataList.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return interleavedMetadata;
|
||||
return Flux.fromIterable(request.getProviders())
|
||||
.flatMap(provider ->
|
||||
Mono.fromCallable(() -> fetchMetadataListFromAProvider(provider, book, request))
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
.flatMapMany(Flux::fromIterable)
|
||||
.onErrorResume(e -> {
|
||||
log.error("Error fetching metadata from provider: {}", provider, e);
|
||||
return Flux.empty();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public List<BookMetadata> fetchMetadataListFromAProvider(MetadataProvider provider, Book book, FetchMetadataRequest request) {
|
||||
@@ -137,32 +122,6 @@ public class BookMetadataService {
|
||||
return books.stream().map(b -> bookMetadataMapper.toBookMetadata(b.getMetadata(), false)).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) {
|
||||
return bookCoverService.updateCoverImageFromFile(bookId, file);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookMetadata updateCoverImageFromUrl(Long bookId, String url) {
|
||||
return bookCoverService.updateCoverImageFromUrl(bookId, url);
|
||||
}
|
||||
|
||||
public void updateCoverImageFromFileForBooks(Set<Long> bookIds, MultipartFile file) {
|
||||
bookCoverService.updateCoverImageFromFileForBooks(bookIds, file);
|
||||
}
|
||||
|
||||
public void regenerateCover(long bookId) {
|
||||
bookCoverService.regenerateCover(bookId);
|
||||
}
|
||||
|
||||
public void regenerateCoversForBooks(Set<Long> bookIds) {
|
||||
bookCoverService.regenerateCoversForBooks(bookIds);
|
||||
}
|
||||
|
||||
public void regenerateCovers() {
|
||||
bookCoverService.regenerateCovers();
|
||||
}
|
||||
|
||||
public BookMetadata getComicInfoMetadata(long bookId) {
|
||||
log.info("Extracting ComicInfo metadata for book ID: {}", bookId);
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
+16
-17
@@ -9,15 +9,12 @@ import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.MetadataReplaceMode;
|
||||
import com.adityachandel.booklore.repository.AuthorRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.CategoryRepository;
|
||||
import com.adityachandel.booklore.repository.MoodRepository;
|
||||
import com.adityachandel.booklore.repository.TagRepository;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.file.FileMoveService;
|
||||
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
|
||||
import com.adityachandel.booklore.util.BookCoverUtils;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.MetadataChangeDetector;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -82,14 +79,13 @@ public class BookMetadataUpdater {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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();
|
||||
MetadataPersistenceSettings.SaveToOriginalFile writeToFile = settings.getSaveToOriginalFile();
|
||||
BookFileType bookType = bookEntity.getBookType();
|
||||
|
||||
boolean hasValueChangesForFileWrite = MetadataChangeDetector.hasValueChangesForFileWrite(newMetadata, metadata, clearFlags);
|
||||
@@ -100,7 +96,7 @@ public class BookMetadataUpdater {
|
||||
updateMoodsIfNeeded(newMetadata, metadata, clearFlags, mergeMoods, replaceMode);
|
||||
updateTagsIfNeeded(newMetadata, metadata, clearFlags, mergeTags, replaceMode);
|
||||
bookReviewUpdateService.updateBookReviews(newMetadata, metadata, clearFlags, mergeCategories);
|
||||
updateThumbnailIfNeeded(bookId, newMetadata, metadata, updateThumbnail);
|
||||
updateThumbnailIfNeeded(bookId, bookEntity, newMetadata, metadata, updateThumbnail);
|
||||
updateLocks(newMetadata, metadata);
|
||||
|
||||
bookEntity.setMetadataUpdatedAt(Instant.now());
|
||||
@@ -112,7 +108,7 @@ public class BookMetadataUpdater {
|
||||
log.warn("Failed to calculate metadata match score for book ID {}: {}", bookId, e.getMessage());
|
||||
}
|
||||
|
||||
if ((writeToFile && hasValueChangesForFileWrite) || thumbnailRequiresUpdate) {
|
||||
if ((writeToFile.isAnyFormatEnabled() && hasValueChangesForFileWrite) || thumbnailRequiresUpdate) {
|
||||
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
|
||||
try {
|
||||
String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null;
|
||||
@@ -121,7 +117,7 @@ public class BookMetadataUpdater {
|
||||
thumbnailUrl = null;
|
||||
}
|
||||
File file = new File(bookEntity.getFullFilePath().toUri());
|
||||
writer.writeMetadataToFile(file, metadata, thumbnailUrl, clearFlags);
|
||||
writer.saveMetadataToFile(file, metadata, thumbnailUrl, clearFlags);
|
||||
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
|
||||
bookEntity.setMetadataForWriteUpdatedAt(Instant.now());
|
||||
bookEntity.setCurrentHash(newHash);
|
||||
@@ -229,14 +225,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
|
||||
e.updateSearchText();
|
||||
} else if (replaceMissing && e.getAuthors().isEmpty()) {
|
||||
e.getAuthors().addAll(newAuthors);
|
||||
e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
|
||||
e.updateSearchText();
|
||||
} 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
|
||||
e.updateSearchText();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,17 +350,18 @@ public class BookMetadataUpdater {
|
||||
}
|
||||
}
|
||||
|
||||
private void updateThumbnailIfNeeded(long bookId, BookMetadata m, BookMetadataEntity e, boolean set) {
|
||||
private void updateThumbnailIfNeeded(long bookId, BookEntity bookEntity, BookMetadata m, BookMetadataEntity e, boolean set) {
|
||||
if (Boolean.TRUE.equals(e.getCoverLocked())) {
|
||||
return; // Locked — do nothing
|
||||
return;
|
||||
}
|
||||
if (!set) return;
|
||||
if (!StringUtils.hasText(m.getThumbnailUrl()) || isLocalOrPrivateUrl(m.getThumbnailUrl())) return;
|
||||
try {
|
||||
fileService.createThumbnailFromUrl(bookId, m.getThumbnailUrl());
|
||||
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
|
||||
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
} catch (Exception ex) {
|
||||
log.warn("Failed to download cover for book {}: {}", bookId, ex.getMessage());
|
||||
// Don't rethrow - cover failures shouldn't roll back metadata updates
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,6 +382,8 @@ public class BookMetadataUpdater {
|
||||
Pair.of(m.getComicvineIdLocked(), e::setComicvineIdLocked),
|
||||
Pair.of(m.getHardcoverIdLocked(), e::setHardcoverIdLocked),
|
||||
Pair.of(m.getHardcoverBookIdLocked(), e::setHardcoverBookIdLocked),
|
||||
Pair.of(m.getLubimyczytacIdLocked(), e::setLubimyczytacIdLocked),
|
||||
Pair.of(m.getLubimyczytacRatingLocked(), e::setLubimyczytacRatingLocked),
|
||||
Pair.of(m.getGoogleIdLocked(), e::setGoogleIdLocked),
|
||||
Pair.of(m.getPageCountLocked(), e::setPageCountLocked),
|
||||
Pair.of(m.getLanguageLocked(), e::setLanguageLocked),
|
||||
|
||||
+655
-142
@@ -9,7 +9,7 @@ import javax.imageio.ImageWriteParam;
|
||||
import javax.imageio.ImageWriter;
|
||||
import javax.imageio.stream.ImageOutputStream;
|
||||
import java.awt.*;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.awt.geom.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
@@ -21,168 +21,681 @@ import java.util.regex.Pattern;
|
||||
@Service
|
||||
public class CoverImageGenerator {
|
||||
|
||||
private static final int WIDTH = 250;
|
||||
private static final int HEIGHT = 350;
|
||||
private static final int PADDING = 20;
|
||||
private static final int TITLE_TOP_MARGIN = 40;
|
||||
private static final int TITLE_PADDING = 15;
|
||||
private static final int AUTHOR_BOTTOM_MARGIN = 330;
|
||||
private static final int MAX_LINES = 5;
|
||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
||||
private static final int WIDTH = 1200;
|
||||
private static final int HEIGHT = 1600;
|
||||
private static final int SCALE = 2;
|
||||
private static final double PHI = 1.618033988749;
|
||||
private static final double PHI_INV = 1.0 / PHI;
|
||||
private static final double PHI_SQ_INV = 1.0 / (PHI * PHI);
|
||||
private static final int MAX_TITLE_LINES = 5;
|
||||
private static final int MAX_AUTHOR_LINES = 2;
|
||||
private static final int MAX_TITLE_LEN = 200;
|
||||
private static final int MAX_AUTHOR_LEN = 100;
|
||||
private static final int MIN_FONT = 36 * SCALE;
|
||||
private static final Pattern WS = Pattern.compile("\\s+");
|
||||
|
||||
public byte[] generateCover(String title, String author) {
|
||||
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = image.createGraphics();
|
||||
|
||||
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
||||
|
||||
Color[] colors = getColorScheme(title);
|
||||
Color bgColor1 = colors[0];
|
||||
Color bgColor2 = colors[1];
|
||||
|
||||
GradientPaint backgroundGradient = new GradientPaint(
|
||||
0, 0, bgColor1,
|
||||
0, HEIGHT, bgColor2
|
||||
);
|
||||
g2d.setPaint(backgroundGradient);
|
||||
g2d.fillRect(0, 0, WIDTH, HEIGHT);
|
||||
|
||||
String effectiveTitle = title != null && !title.isBlank() ? title : "Unknown Title";
|
||||
String effectiveAuthor = author != null && !author.isBlank() ? author : "Unknown Author";
|
||||
|
||||
Font titleFont = getTitleFont(effectiveTitle.length());
|
||||
g2d.setFont(titleFont);
|
||||
FontMetrics titleFm = g2d.getFontMetrics();
|
||||
|
||||
List<String> titleLines = wrapText(effectiveTitle, titleFm);
|
||||
int titleLineHeight = titleFm.getHeight();
|
||||
int titleBoxHeight = (titleLines.size() * titleLineHeight) + (TITLE_PADDING * 2);
|
||||
|
||||
GradientPaint titleBgGradient = new GradientPaint(
|
||||
0, TITLE_TOP_MARGIN, new Color(221, 221, 221), // #dddddd
|
||||
0, TITLE_TOP_MARGIN + titleBoxHeight, new Color(223, 223, 223, 153) // #dfdfdf with 0.6 opacity
|
||||
);
|
||||
g2d.setPaint(titleBgGradient);
|
||||
g2d.fillRect(0, TITLE_TOP_MARGIN, WIDTH, titleBoxHeight);
|
||||
|
||||
g2d.setColor(Color.BLACK);
|
||||
int currentY = TITLE_TOP_MARGIN + TITLE_PADDING + titleFm.getAscent();
|
||||
for (String line : titleLines) {
|
||||
g2d.drawString(line, PADDING, currentY);
|
||||
currentY += titleLineHeight;
|
||||
}
|
||||
|
||||
Font authorFont = getAuthorFont(effectiveAuthor.length());
|
||||
g2d.setFont(authorFont);
|
||||
FontMetrics authorFm = g2d.getFontMetrics();
|
||||
|
||||
List<String> authorLines = wrapText(effectiveAuthor, authorFm);
|
||||
int authorLineHeight = authorFm.getHeight();
|
||||
int authorStartY = AUTHOR_BOTTOM_MARGIN - ((authorLines.size() - 1) * authorLineHeight);
|
||||
|
||||
g2d.setColor(Color.BLACK);
|
||||
for (int i = 0; i < authorLines.size(); i++) {
|
||||
String line = authorLines.get(i);
|
||||
Rectangle2D rect = authorFm.getStringBounds(line, g2d);
|
||||
int x = WIDTH - PADDING - (int) rect.getWidth(); // Right align
|
||||
g2d.drawString(line, x, authorStartY + (i * authorLineHeight));
|
||||
}
|
||||
|
||||
g2d.dispose();
|
||||
|
||||
return writeHighQualityJpeg(image);
|
||||
return generateCover(title, author, null);
|
||||
}
|
||||
|
||||
private byte[] writeHighQualityJpeg(BufferedImage image) {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
|
||||
ImageWriteParam param = writer.getDefaultWriteParam();
|
||||
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
||||
param.setCompressionQuality(0.95f); // High quality
|
||||
public byte[] generateCover(String title, String author, String subtitle) {
|
||||
BufferedImage render = null;
|
||||
BufferedImage result = null;
|
||||
Graphics2D g = null;
|
||||
|
||||
try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) {
|
||||
writer.setOutput(ios);
|
||||
writer.write(null, new IIOImage(image, null, null), param);
|
||||
writer.dispose();
|
||||
return baos.toByteArray();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to generate cover image", e);
|
||||
throw new RuntimeException("Failed to generate cover image", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Font getTitleFont(int length) {
|
||||
try {
|
||||
Font font = new Font("Georgia", Font.BOLD, getTitleFontSize(length));
|
||||
if (font.getFamily().equals("Georgia")) return font;
|
||||
String safeTitle = sanitize(title, MAX_TITLE_LEN, "Unknown Title");
|
||||
String safeAuthor = sanitize(author, MAX_AUTHOR_LEN, "Unknown Author");
|
||||
String safeSubtitle = sanitize(subtitle, MAX_TITLE_LEN, ""); // Using title length limit for subtitle
|
||||
|
||||
int w = WIDTH * SCALE;
|
||||
int h = HEIGHT * SCALE;
|
||||
|
||||
render = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
|
||||
g = render.createGraphics();
|
||||
|
||||
try {
|
||||
configureGraphics(g);
|
||||
Palette p = selectPalette(safeTitle);
|
||||
int margin = calcMargin(w);
|
||||
|
||||
renderBaseGradient(g, p, w, h);
|
||||
renderDepthGradient(g, p, w, h);
|
||||
renderGlow(g, p, w, h);
|
||||
renderBokeh(g, p, w, h);
|
||||
renderTexture(g, w, h);
|
||||
renderFrame(g, p, w, h);
|
||||
int titleEnd = renderTitle(g, safeTitle, p, w, h, margin);
|
||||
int subtitleEnd = titleEnd;
|
||||
if (safeSubtitle != null && !safeSubtitle.isEmpty()) {
|
||||
subtitleEnd = renderSubtitle(g, safeSubtitle, p, w, h, margin, titleEnd);
|
||||
}
|
||||
renderDivider(g, p, w, subtitleEnd, h);
|
||||
renderAuthor(g, safeAuthor, p, w, h, margin);
|
||||
renderVignette(g, w, h);
|
||||
renderEdges(g, w, h);
|
||||
|
||||
} finally {
|
||||
if (g != null) g.dispose();
|
||||
}
|
||||
|
||||
result = downscale(render);
|
||||
render.flush();
|
||||
render = null;
|
||||
|
||||
return encodeJpeg(result);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to load preferred font, using fallback");
|
||||
log.error("Cover generation failed: {}", title, e);
|
||||
throw new RuntimeException("Cover generation failed", e);
|
||||
} finally {
|
||||
cleanup(g, render, result);
|
||||
}
|
||||
return new Font(Font.SERIF, Font.BOLD, getTitleFontSize(length));
|
||||
}
|
||||
|
||||
private int getTitleFontSize(int length) {
|
||||
if (length < 20) return 36;
|
||||
if (length < 40) return 30;
|
||||
return 24;
|
||||
private record Palette(Color primary, Color secondary, Color tertiary, Color accent,
|
||||
Color textMain, Color textSub, Color ornament) {}
|
||||
|
||||
private int calcMargin(int w) {
|
||||
int frameOuter = (int) (w * PHI_SQ_INV * 0.12);
|
||||
int frameInner = (int) (frameOuter * PHI);
|
||||
return frameInner + (int) (w * 0.04);
|
||||
}
|
||||
|
||||
private Font getAuthorFont(int length) {
|
||||
if (length < 20) return new Font(Font.SANS_SERIF, Font.PLAIN, 28);
|
||||
return new Font(Font.SANS_SERIF, Font.PLAIN, 22);
|
||||
private Palette selectPalette(String title) {
|
||||
Palette[] palettes = {
|
||||
new Palette(new Color(20, 30, 55), new Color(40, 55, 90), new Color(30, 42, 72),
|
||||
new Color(218, 180, 120), new Color(252, 250, 245), new Color(210, 200, 185), new Color(190, 165, 110)),
|
||||
new Palette(new Color(70, 30, 40), new Color(105, 50, 60), new Color(85, 40, 50),
|
||||
new Color(230, 205, 175), new Color(255, 252, 248), new Color(225, 215, 200), new Color(200, 175, 145)),
|
||||
new Palette(new Color(25, 50, 45), new Color(45, 80, 70), new Color(35, 65, 57),
|
||||
new Color(205, 190, 150), new Color(250, 248, 242), new Color(215, 210, 195), new Color(180, 165, 130)),
|
||||
new Palette(new Color(45, 30, 65), new Color(75, 50, 100), new Color(60, 40, 82),
|
||||
new Color(215, 195, 165), new Color(252, 250, 248), new Color(220, 210, 200), new Color(190, 170, 145)),
|
||||
new Palette(new Color(55, 45, 35), new Color(90, 75, 60), new Color(72, 60, 47),
|
||||
new Color(210, 185, 145), new Color(255, 252, 245), new Color(230, 220, 200), new Color(185, 165, 125)),
|
||||
new Palette(new Color(25, 50, 60), new Color(45, 85, 100), new Color(35, 67, 80),
|
||||
new Color(220, 200, 165), new Color(250, 250, 248), new Color(215, 210, 200), new Color(190, 175, 145)),
|
||||
new Palette(new Color(40, 40, 45), new Color(65, 67, 73), new Color(52, 52, 58),
|
||||
new Color(205, 190, 160), new Color(252, 252, 250), new Color(205, 203, 200), new Color(180, 170, 150)),
|
||||
new Palette(new Color(65, 40, 30), new Color(105, 70, 50), new Color(85, 55, 40),
|
||||
new Color(225, 200, 160), new Color(255, 250, 242), new Color(230, 220, 200), new Color(200, 180, 145)),
|
||||
new Palette(new Color(30, 40, 75), new Color(50, 65, 115), new Color(40, 52, 95),
|
||||
new Color(220, 200, 155), new Color(252, 250, 248), new Color(210, 205, 195), new Color(190, 170, 135)),
|
||||
new Palette(new Color(50, 55, 40), new Color(80, 90, 65), new Color(65, 72, 52),
|
||||
new Color(215, 205, 170), new Color(252, 250, 245), new Color(220, 215, 200), new Color(185, 180, 150))
|
||||
};
|
||||
return palettes[Math.abs(title.hashCode()) % palettes.length];
|
||||
}
|
||||
|
||||
private static List<String> wrapText(String text, FontMetrics fm) {
|
||||
private static void renderBaseGradient(Graphics2D g, Palette p, int w, int h) {
|
||||
float[] fractions = {0f, (float) PHI_SQ_INV, 0.5f, (float) PHI_INV, 1f};
|
||||
Color[] colors = {darken(p.primary, 0.2f), p.primary, p.tertiary, p.secondary, darken(p.secondary, 0.15f)};
|
||||
g.setPaint(new LinearGradientPaint(0, 0, w * (float) PHI_INV, h, fractions, colors));
|
||||
g.fillRect(0, 0, w, h);
|
||||
}
|
||||
|
||||
private void renderDepthGradient(Graphics2D g, Palette p, int w, int h) {
|
||||
g.setPaint(new RadialGradientPaint(w * 0.5f, h * 0.35f, (float) (h * PHI_INV),
|
||||
new float[]{0f, 0.5f, 1f},
|
||||
new Color[]{alpha(lighten(p.tertiary, 0.15f), 45), alpha(p.tertiary, 25), alpha(p.primary, 0)}));
|
||||
g.fillRect(0, 0, w, h);
|
||||
|
||||
g.setPaint(new RadialGradientPaint(w * 0.85f, h * 1.15f, (float) (w * PHI_INV),
|
||||
new float[]{0f, 0.6f, 1f},
|
||||
new Color[]{alpha(darken(p.secondary, 0.25f), 55), alpha(darken(p.secondary, 0.15f), 30), alpha(p.secondary, 0)}));
|
||||
g.fillRect(0, 0, w, h);
|
||||
|
||||
g.setPaint(new RadialGradientPaint(w * 0.1f, h * 0.9f, (float) (w * PHI_SQ_INV),
|
||||
new float[]{0f, 0.5f, 1f},
|
||||
new Color[]{alpha(darken(p.primary, 0.2f), 40), alpha(p.primary, 20), alpha(p.primary, 0)}));
|
||||
g.fillRect(0, 0, w, h);
|
||||
}
|
||||
|
||||
private static void renderGlow(Graphics2D g, Palette p, int w, int h) {
|
||||
int cy = (int) (h * PHI_SQ_INV);
|
||||
float r = (float) (w * PHI_INV * 1.3);
|
||||
Color glow = new Color(
|
||||
Math.min(255, p.accent.getRed() + 55),
|
||||
Math.min(255, p.accent.getGreen() + 45),
|
||||
Math.min(255, p.accent.getBlue() + 35));
|
||||
|
||||
g.setPaint(new RadialGradientPaint(w / 2f, cy, r,
|
||||
new float[]{0f, (float) PHI_SQ_INV, (float) PHI_INV, 1f},
|
||||
new Color[]{alpha(glow, 32), alpha(glow, 20), alpha(glow, 10), alpha(glow, 0)}));
|
||||
g.fillRect(0, 0, w, h);
|
||||
|
||||
g.setPaint(new RadialGradientPaint(w / 2f, (float) (h * (1 - PHI_SQ_INV * 0.45)), r * 0.65f,
|
||||
new float[]{0f, 0.5f, 1f},
|
||||
new Color[]{alpha(Color.WHITE, 14), alpha(Color.WHITE, 7), alpha(Color.WHITE, 0)}));
|
||||
g.fillRect(0, 0, w, h);
|
||||
}
|
||||
|
||||
private void renderBokeh(Graphics2D g, Palette p, int w, int h) {
|
||||
Composite orig = g.getComposite();
|
||||
int seed = p.primary.getRGB();
|
||||
|
||||
for (int i = 0; i < 15; i++) {
|
||||
int px = ((seed * (i + 1) * 17) % w + w) % w;
|
||||
int py = ((seed * (i + 1) * 31) % h + h) % h;
|
||||
int size = Math.max(1, ((25 + Math.abs((seed * (i + 1) * 7) % 60)) * SCALE));
|
||||
float opacity = 0.018f + Math.abs((seed * (i + 1) * 3) % 25) * 0.0012f;
|
||||
|
||||
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
|
||||
Color bokehColor = (i % 3 == 0) ? lighten(p.accent, 0.25f) : (i % 3 == 1) ? Color.WHITE : lighten(p.ornament, 0.2f);
|
||||
|
||||
g.setPaint(new RadialGradientPaint(px, py, size,
|
||||
new float[]{0f, 0.6f, 1f},
|
||||
new Color[]{alpha(bokehColor, 90), alpha(bokehColor, 35), alpha(bokehColor, 0)}));
|
||||
g.fillOval(px - size, py - size, size * 2, size * 2);
|
||||
}
|
||||
|
||||
g.setComposite(orig);
|
||||
}
|
||||
|
||||
private static void renderTexture(Graphics2D g, int w, int h) {
|
||||
Composite orig = g.getComposite();
|
||||
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.018f));
|
||||
|
||||
for (int y = 0; y < h; y += 2) {
|
||||
for (int x = 0; x < w; x += 2) {
|
||||
int n = (x * 17 + y * 31) % 29;
|
||||
if (n < 10) {
|
||||
g.setColor(n < 5 ? Color.WHITE : Color.BLACK);
|
||||
g.fillRect(x, y, 1, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
g.setComposite(orig);
|
||||
}
|
||||
|
||||
private void renderFrame(Graphics2D g, Palette p, int w, int h) {
|
||||
int outer = (int) (w * PHI_SQ_INV * 0.12);
|
||||
int inner = (int) (outer * PHI);
|
||||
|
||||
g.setColor(alpha(p.ornament, 28));
|
||||
g.setStroke(new BasicStroke(10f));
|
||||
g.drawRect(outer - 4, outer - 4, w - (outer - 4) * 2, h - (outer - 4) * 2);
|
||||
|
||||
g.setColor(alpha(p.ornament, 95));
|
||||
g.setStroke(new BasicStroke(2.5f));
|
||||
g.drawRect(outer, outer, w - outer * 2, h - outer * 2);
|
||||
|
||||
g.setColor(alpha(p.ornament, 55));
|
||||
g.setStroke(new BasicStroke(1f));
|
||||
g.drawRect(inner, inner, w - inner * 2, h - inner * 2);
|
||||
|
||||
renderCorners(g, p, w, h, outer);
|
||||
renderAccents(g, p, w, h, outer);
|
||||
}
|
||||
|
||||
private static void renderCorners(Graphics2D g, Palette p, int w, int h, int m) {
|
||||
g.setColor(alpha(p.ornament, 105));
|
||||
g.setStroke(new BasicStroke(2.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
|
||||
int size = (int) (m * PHI);
|
||||
|
||||
int[][] corners = {{m, m, 0}, {w - m, m, 90}, {w - m, h - m, 180}, {m, h - m, 270}};
|
||||
for (int[] c : corners) renderCorner(g, c[0], c[1], size, c[2]);
|
||||
}
|
||||
|
||||
private static void renderCorner(Graphics2D g, int x, int y, int size, int angle) {
|
||||
AffineTransform saved = g.getTransform();
|
||||
g.translate(x, y);
|
||||
g.rotate(Math.toRadians(angle));
|
||||
|
||||
Path2D path = new Path2D.Float();
|
||||
path.moveTo(0, size);
|
||||
path.lineTo(0, size * PHI_SQ_INV);
|
||||
path.quadTo(0, 0, size * PHI_SQ_INV, 0);
|
||||
path.lineTo(size, 0);
|
||||
g.draw(path);
|
||||
|
||||
Path2D inner = new Path2D.Float();
|
||||
inner.moveTo(size * 0.15, size * PHI_INV);
|
||||
inner.quadTo(size * 0.15, size * 0.15, size * PHI_INV, size * 0.15);
|
||||
g.draw(inner);
|
||||
|
||||
g.fillOval(-5, -5, 10, 10);
|
||||
g.fillOval((int) (size * 0.92), -4, 8, 8);
|
||||
g.fillOval(-4, (int) (size * 0.92), 8, 8);
|
||||
|
||||
g.setTransform(saved);
|
||||
}
|
||||
|
||||
private static void renderAccents(Graphics2D g, Palette p, int w, int h, int m) {
|
||||
g.setColor(alpha(p.ornament, 65));
|
||||
g.setStroke(new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
|
||||
int len = (int) (m * PHI);
|
||||
|
||||
g.drawLine(w / 2 - len, m, w / 2 + len, m);
|
||||
g.fillOval(w / 2 - 5, m - 5, 10, 10);
|
||||
|
||||
g.drawLine(w / 2 - len, h - m, w / 2 + len, h - m);
|
||||
g.fillOval(w / 2 - 5, h - m - 5, 10, 10);
|
||||
|
||||
g.drawLine(m, h / 2 - len, m, h / 2 + len);
|
||||
g.fillOval(m - 5, h / 2 - 5, 10, 10);
|
||||
|
||||
g.drawLine(w - m, h / 2 - len, w - m, h / 2 + len);
|
||||
g.fillOval(w - m - 5, h / 2 - 5, 10, 10);
|
||||
}
|
||||
|
||||
private int renderTitle(Graphics2D g, String title, Palette p, int w, int h, int margin) {
|
||||
int maxW = w - margin * 2;
|
||||
int bottomBound = (int) (h * PHI_INV);
|
||||
|
||||
String text = title.toUpperCase();
|
||||
Font font = resolveFont(g, text, maxW, titleSize(title.length()), MAX_TITLE_LINES, true);
|
||||
g.setFont(font);
|
||||
FontMetrics fm = g.getFontMetrics();
|
||||
|
||||
List<String> lines = wrapText(text, fm, maxW, MAX_TITLE_LINES);
|
||||
int lineH = (int) (fm.getHeight() * 1.12);
|
||||
int totalH = lines.size() * lineH;
|
||||
|
||||
int availableH = bottomBound - margin - totalH;
|
||||
int startY = margin + (int) (availableH * PHI_SQ_INV) + fm.getAscent();
|
||||
startY = Math.max(startY, margin + fm.getAscent());
|
||||
|
||||
float tracking = 0.05f;
|
||||
int lastY = startY;
|
||||
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i);
|
||||
int lw = trackedWidth(fm, line, tracking);
|
||||
int x = (w - lw) / 2;
|
||||
int y = startY + i * lineH;
|
||||
if (y + fm.getDescent() > bottomBound) break;
|
||||
renderText(g, line, x, y, tracking, p.textMain, true);
|
||||
lastY = y;
|
||||
}
|
||||
|
||||
return lastY + fm.getDescent() + lineH / 2;
|
||||
}
|
||||
|
||||
private static void renderDivider(Graphics2D g, Palette p, int w, int titleEnd, int h) {
|
||||
int minY = titleEnd + (int) (h * 0.02);
|
||||
int maxY = (int) (h * (1 - PHI_SQ_INV * 0.7));
|
||||
int cy = minY + (int) ((maxY - minY) * PHI_SQ_INV);
|
||||
int cx = w / 2;
|
||||
int lineLen = (int) (w * PHI_SQ_INV * 0.38);
|
||||
|
||||
for (int dir : new int[]{-1, 1}) {
|
||||
int sx = cx + dir * 50;
|
||||
int ex = cx + dir * (50 + lineLen);
|
||||
g.setPaint(new GradientPaint(sx, cy, alpha(p.ornament, 115), ex, cy, alpha(p.ornament, 25)));
|
||||
g.setStroke(new BasicStroke(2.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
|
||||
g.drawLine(sx, cy, ex, cy);
|
||||
}
|
||||
|
||||
g.setColor(alpha(p.ornament, 130));
|
||||
g.setStroke(new BasicStroke(2f));
|
||||
|
||||
int ds = 14;
|
||||
Path2D diamond = new Path2D.Float();
|
||||
diamond.moveTo(cx, cy - ds);
|
||||
diamond.lineTo(cx + ds, cy);
|
||||
diamond.lineTo(cx, cy + ds);
|
||||
diamond.lineTo(cx - ds, cy);
|
||||
diamond.closePath();
|
||||
g.draw(diamond);
|
||||
|
||||
int is = 6;
|
||||
Path2D inner = new Path2D.Float();
|
||||
inner.moveTo(cx, cy - is);
|
||||
inner.lineTo(cx + is, cy);
|
||||
inner.lineTo(cx, cy + is);
|
||||
inner.lineTo(cx - is, cy);
|
||||
inner.closePath();
|
||||
g.fill(inner);
|
||||
|
||||
g.fillOval(cx - 50 - 5, cy - 5, 10, 10);
|
||||
g.fillOval(cx + 50 - 5, cy - 5, 10, 10);
|
||||
g.fillOval(cx - 32 - 4, cy - 4, 8, 8);
|
||||
g.fillOval(cx + 32 - 4, cy - 4, 8, 8);
|
||||
}
|
||||
|
||||
private void renderAuthor(Graphics2D g, String author, Palette p, int w, int h, int margin) {
|
||||
int maxW = w - margin * 2;
|
||||
int bottomBound = h - margin;
|
||||
|
||||
String[] authors = author.split(",");
|
||||
StringBuilder formattedAuthors = new StringBuilder();
|
||||
for (int i = 0; i < authors.length; i++) {
|
||||
if (i > 0) formattedAuthors.append("\n").append(authors[i].trim());
|
||||
else formattedAuthors.append(authors[i].trim());
|
||||
}
|
||||
|
||||
Font authorFont = resolveFont(g, formattedAuthors.toString(), maxW, authorSize(formattedAuthors.length()), MAX_AUTHOR_LINES, false);
|
||||
g.setFont(authorFont);
|
||||
FontMetrics authorFm = g.getFontMetrics();
|
||||
|
||||
String[] authorLinesArray = formattedAuthors.toString().split("\n");
|
||||
List<String> lines = new ArrayList<>();
|
||||
String[] words = WHITESPACE_PATTERN.split(text);
|
||||
StringBuilder currentLine = new StringBuilder();
|
||||
for (String line : authorLinesArray) {
|
||||
lines.add(line.trim());
|
||||
}
|
||||
|
||||
for (String word : words) {
|
||||
if (currentLine.isEmpty()) {
|
||||
currentLine.append(word);
|
||||
int authorLineH = (int) (authorFm.getHeight() * 1.18);
|
||||
int authorTotalH = lines.size() * authorLineH;
|
||||
|
||||
// Remove the "by" prefix for multiple authors
|
||||
boolean showByPrefix = lines.size() == 1 && author.length() < 45 && !author.contains(",");
|
||||
|
||||
Font byFont = authorFont.deriveFont(authorFont.getSize() * 0.58f);
|
||||
FontMetrics byFm = g.getFontMetrics(byFont);
|
||||
String byText = "— by —";
|
||||
int byHeight = showByPrefix ? byFm.getHeight() : 0;
|
||||
int bySpacing = showByPrefix ? (int) (authorLineH * PHI_SQ_INV * 0.8) : 0;
|
||||
|
||||
int totalBlockH = byHeight + bySpacing + authorTotalH;
|
||||
|
||||
int blockBottom = (int) (h * (1 - PHI_SQ_INV * 0.32));
|
||||
blockBottom = Math.min(blockBottom, bottomBound);
|
||||
int blockTop = blockBottom - totalBlockH;
|
||||
|
||||
int minTop = (int) (h * PHI_INV) + margin;
|
||||
if (blockTop < minTop) blockTop = minTop;
|
||||
|
||||
int currentY = blockTop;
|
||||
|
||||
if (showByPrefix) {
|
||||
g.setFont(byFont);
|
||||
int byW = byFm.stringWidth(byText);
|
||||
int byX = (w - byW) / 2;
|
||||
int byY = currentY + byFm.getAscent();
|
||||
|
||||
g.setColor(new Color(0, 0, 0, 35));
|
||||
g.drawString(byText, byX + 3, byY + 3);
|
||||
|
||||
g.setColor(alpha(p.ornament, 155));
|
||||
g.drawString(byText, byX, byY);
|
||||
|
||||
currentY = byY + byFm.getDescent() + bySpacing;
|
||||
}
|
||||
|
||||
g.setFont(authorFont);
|
||||
float tracking = 0.08f;
|
||||
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i);
|
||||
if (!line.isEmpty()) { // Only render non-empty lines
|
||||
int lw = trackedWidth(authorFm, line, tracking);
|
||||
int x = (w - lw) / 2;
|
||||
int y = currentY + authorFm.getAscent() + i * authorLineH;
|
||||
if (y + authorFm.getDescent() > bottomBound) break;
|
||||
renderText(g, line, x, y, tracking, p.textSub, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int renderSubtitle(Graphics2D g, String subtitle, Palette p, int w, int h, int margin, int titleEnd) {
|
||||
int maxW = w - margin * 2;
|
||||
int bottomBound = h - margin;
|
||||
|
||||
Font subtitleFont = resolveFont(g, subtitle, maxW, subtitleSize(subtitle.length()), 2, false);
|
||||
g.setFont(subtitleFont);
|
||||
FontMetrics subtitleFm = g.getFontMetrics();
|
||||
|
||||
List<String> lines = wrapText(subtitle, subtitleFm, maxW, 2);
|
||||
int subtitleLineH = (int) (subtitleFm.getHeight() * 1.12);
|
||||
|
||||
// Position subtitle below the title with some spacing
|
||||
int spacing = (int) (subtitleLineH * 0.5);
|
||||
int startY = titleEnd + spacing + subtitleFm.getAscent();
|
||||
|
||||
g.setFont(subtitleFont);
|
||||
float tracking = 0.06f;
|
||||
|
||||
int lastY = startY;
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i);
|
||||
int lw = trackedWidth(subtitleFm, line, tracking);
|
||||
int x = (w - lw) / 2;
|
||||
int y = startY + i * subtitleLineH;
|
||||
if (y + subtitleFm.getDescent() > bottomBound) break;
|
||||
renderText(g, line, x, y, tracking, p.textSub, false);
|
||||
lastY = y;
|
||||
}
|
||||
|
||||
return lastY + subtitleFm.getDescent();
|
||||
}
|
||||
|
||||
private int subtitleSize(int len) {
|
||||
if (len < 12) return 130 * SCALE;
|
||||
if (len < 22) return 110 * SCALE;
|
||||
if (len < 35) return 90 * SCALE;
|
||||
return 75 * SCALE;
|
||||
}
|
||||
|
||||
private void renderText(Graphics2D g, String text, int x, int y, float tracking, Color color, boolean isTitle) {
|
||||
FontMetrics fm = g.getFontMetrics();
|
||||
int tp = (int) (fm.getHeight() * tracking);
|
||||
|
||||
int[][] shadows = isTitle
|
||||
? new int[][]{{8, 8, 14}, {5, 5, 28}, {2, 2, 45}}
|
||||
: new int[][]{{5, 5, 18}, {2, 2, 35}};
|
||||
|
||||
for (int[] s : shadows) {
|
||||
g.setColor(new Color(0, 0, 0, s[2]));
|
||||
drawTracked(g, text, x + s[0], y + s[1], tp);
|
||||
}
|
||||
|
||||
g.setColor(color);
|
||||
drawTracked(g, text, x, y, tp);
|
||||
|
||||
if (isTitle) {
|
||||
g.setColor(alpha(Color.WHITE, 22));
|
||||
drawTracked(g, text, x, y - 1, tp);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawTracked(Graphics2D g, String text, int x, int y, int tracking) {
|
||||
FontMetrics fm = g.getFontMetrics();
|
||||
int cx = x;
|
||||
for (char c : text.toCharArray()) {
|
||||
g.drawString(String.valueOf(c), cx, y);
|
||||
cx += fm.charWidth(c) + tracking;
|
||||
}
|
||||
}
|
||||
|
||||
private int trackedWidth(FontMetrics fm, String text, float tracking) {
|
||||
int tp = (int) (fm.getHeight() * tracking);
|
||||
int w = 0;
|
||||
for (char c : text.toCharArray()) w += fm.charWidth(c) + tp;
|
||||
return Math.max(0, w - tp);
|
||||
}
|
||||
|
||||
private static void renderVignette(Graphics2D g, int w, int h) {
|
||||
float r = (float) (Math.sqrt(w * w + h * h) / 2 * 1.12);
|
||||
g.setPaint(new RadialGradientPaint(w / 2f, h / 2f, r,
|
||||
new float[]{0f, (float) PHI_INV, (float) (PHI_INV + PHI_SQ_INV * 0.25), 0.9f, 1f},
|
||||
new Color[]{alpha(Color.BLACK, 0), alpha(Color.BLACK, 0), alpha(Color.BLACK, 15),
|
||||
alpha(Color.BLACK, 50), alpha(Color.BLACK, 85)}));
|
||||
g.fillRect(0, 0, w, h);
|
||||
|
||||
g.setPaint(new GradientPaint(0, 0, alpha(Color.WHITE, 14), 0, (int) (h * PHI_SQ_INV), alpha(Color.WHITE, 0)));
|
||||
g.fillRect(0, 0, w, (int) (h * PHI_SQ_INV));
|
||||
}
|
||||
|
||||
private static void renderEdges(Graphics2D g, int w, int h) {
|
||||
g.setColor(alpha(Color.BLACK, 50));
|
||||
g.setStroke(new BasicStroke(3f));
|
||||
g.drawRect(0, 0, w - 1, h - 1);
|
||||
|
||||
g.setColor(alpha(Color.WHITE, 10));
|
||||
g.drawRect(3, 3, w - 7, h - 7);
|
||||
}
|
||||
|
||||
private static String sanitize(String input, int max, String fallback) {
|
||||
if (input == null || input.isBlank()) return fallback;
|
||||
String s = input.trim();
|
||||
return s.length() > max ? s.substring(0, max) : s;
|
||||
}
|
||||
|
||||
private void configureGraphics(Graphics2D g) {
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
|
||||
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
|
||||
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
|
||||
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
|
||||
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
|
||||
}
|
||||
|
||||
private static Color alpha(Color c, int a) {
|
||||
return new Color(c.getRed(), c.getGreen(), c.getBlue(), Math.min(255, Math.max(0, a)));
|
||||
}
|
||||
|
||||
private static Color darken(Color c, float f) {
|
||||
return new Color(Math.max(0, (int) (c.getRed() * (1 - f))),
|
||||
Math.max(0, (int) (c.getGreen() * (1 - f))),
|
||||
Math.max(0, (int) (c.getBlue() * (1 - f))));
|
||||
}
|
||||
|
||||
private Color lighten(Color c, float f) {
|
||||
return new Color(Math.min(255, (int) (c.getRed() + (255 - c.getRed()) * f)),
|
||||
Math.min(255, (int) (c.getGreen() + (255 - c.getGreen()) * f)),
|
||||
Math.min(255, (int) (c.getBlue() + (255 - c.getBlue()) * f)));
|
||||
}
|
||||
|
||||
private Font resolveFont(Graphics2D g, String text, int maxW, int startSize, int maxLines, boolean isTitle) {
|
||||
String[] serif = {"Palatino Linotype", "Garamond", "Georgia", "Book Antiqua"};
|
||||
String[] sans = {"Optima", "Gill Sans", "Helvetica Neue", "Calibri"};
|
||||
String[] preferred = isTitle ? serif : sans;
|
||||
String fallback = isTitle ? Font.SERIF : Font.SANS_SERIF;
|
||||
int style = isTitle ? Font.BOLD : Font.PLAIN;
|
||||
|
||||
String selected = fallback;
|
||||
for (String name : preferred) {
|
||||
Font test = new Font(name, style, startSize);
|
||||
if (test.getFamily().equalsIgnoreCase(name)) {
|
||||
selected = name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
float tracking = isTitle ? 0.05f : 0.08f;
|
||||
|
||||
for (int size = startSize; size >= MIN_FONT; size -= 2) {
|
||||
Font font = new Font(selected, style, size);
|
||||
g.setFont(font);
|
||||
FontMetrics fm = g.getFontMetrics();
|
||||
List<String> lines = wrapText(text, fm, maxW, maxLines);
|
||||
if (lines.stream().allMatch(l -> trackedWidth(fm, l, tracking) <= maxW)) return font;
|
||||
}
|
||||
|
||||
return new Font(selected, style, MIN_FONT);
|
||||
}
|
||||
|
||||
private List<String> wrapText(String text, FontMetrics fm, int maxW, int maxLines) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
StringBuilder cur = new StringBuilder();
|
||||
|
||||
for (String word : WS.split(text.trim())) {
|
||||
if (fm.stringWidth(word) > maxW) {
|
||||
if (!cur.isEmpty()) {
|
||||
lines.add(cur.toString().trim());
|
||||
cur = new StringBuilder();
|
||||
}
|
||||
lines.addAll(breakWord(word, fm, maxW));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (cur.isEmpty()) {
|
||||
cur.append(word);
|
||||
} else if (fm.stringWidth(cur + " " + word) <= maxW) {
|
||||
cur.append(" ").append(word);
|
||||
} else {
|
||||
int currentWidth = fm.stringWidth(currentLine.toString());
|
||||
int spaceWidth = fm.stringWidth(" ");
|
||||
int wordWidth = fm.stringWidth(word);
|
||||
if (currentWidth + spaceWidth + wordWidth <= 210) {
|
||||
currentLine.append(" ").append(word);
|
||||
} else {
|
||||
lines.add(currentLine.toString().trim());
|
||||
currentLine = new StringBuilder(word);
|
||||
}
|
||||
lines.add(cur.toString().trim());
|
||||
cur = new StringBuilder(word);
|
||||
}
|
||||
}
|
||||
if (!currentLine.isEmpty()) {
|
||||
lines.add(currentLine.toString().trim());
|
||||
}
|
||||
|
||||
if (lines.size() > MAX_LINES) {
|
||||
List<String> truncated = lines.subList(0, MAX_LINES);
|
||||
String lastLine = truncated.get(MAX_LINES - 1);
|
||||
|
||||
if (fm.stringWidth(lastLine + "...") > 210) {
|
||||
while (lastLine.length() > 3 && fm.stringWidth(lastLine + "...") > 210) {
|
||||
lastLine = lastLine.substring(0, lastLine.length() - 1);
|
||||
}
|
||||
}
|
||||
truncated.set(MAX_LINES - 1, lastLine.trim() + "...");
|
||||
return truncated;
|
||||
|
||||
if (!cur.isEmpty()) lines.add(cur.toString().trim());
|
||||
|
||||
if (lines.size() > maxLines) {
|
||||
lines = new ArrayList<>(lines.subList(0, maxLines));
|
||||
String last = lines.get(maxLines - 1);
|
||||
while (!last.isEmpty() && fm.stringWidth(last + "…") > maxW)
|
||||
last = last.substring(0, last.length() - 1).trim();
|
||||
lines.set(maxLines - 1, last + "…");
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
private Color[] getColorScheme(String title) {
|
||||
int hash = Math.abs((title != null ? title : "").hashCode());
|
||||
Color[][] schemes = {
|
||||
{new Color(85, 119, 102), new Color(102, 153, 136)}, // Green (Original)
|
||||
{new Color(102, 119, 153), new Color(136, 153, 187)}, // Blue
|
||||
{new Color(153, 102, 119), new Color(187, 136, 153)}, // Purple
|
||||
{new Color(153, 153, 102), new Color(187, 187, 136)}, // Olive
|
||||
{new Color(102, 153, 153), new Color(136, 187, 187)}, // Teal
|
||||
{new Color(119, 102, 153), new Color(153, 136, 187)} // Indigo
|
||||
};
|
||||
return schemes[hash % schemes.length];
|
||||
private List<String> breakWord(String word, FontMetrics fm, int maxW) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
StringBuilder cur = new StringBuilder();
|
||||
|
||||
for (char c : word.toCharArray()) {
|
||||
if (fm.stringWidth(cur.toString() + c) > maxW && !cur.isEmpty()) {
|
||||
parts.add(cur.toString());
|
||||
cur = new StringBuilder();
|
||||
}
|
||||
cur.append(c);
|
||||
}
|
||||
if (!cur.isEmpty()) parts.add(cur.toString());
|
||||
|
||||
return parts;
|
||||
}
|
||||
}
|
||||
|
||||
private int titleSize(int len) {
|
||||
if (len < 8) return 150 * SCALE;
|
||||
if (len < 15) return 130 * SCALE;
|
||||
if (len < 25) return 110 * SCALE;
|
||||
if (len < 40) return 92 * SCALE;
|
||||
if (len < 60) return 78 * SCALE;
|
||||
if (len < 85) return 66 * SCALE;
|
||||
return 56 * SCALE;
|
||||
}
|
||||
|
||||
private int authorSize(int len) {
|
||||
if (len < 12) return 78 * SCALE;
|
||||
if (len < 22) return 68 * SCALE;
|
||||
if (len < 35) return 58 * SCALE;
|
||||
return 50 * SCALE;
|
||||
}
|
||||
|
||||
private BufferedImage downscale(BufferedImage src) {
|
||||
BufferedImage dst = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = dst.createGraphics();
|
||||
try {
|
||||
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
|
||||
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
|
||||
g.drawImage(src, 0, 0, WIDTH, HEIGHT, null);
|
||||
return dst;
|
||||
} finally {
|
||||
g.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] encodeJpeg(BufferedImage img) {
|
||||
ImageWriter writer = null;
|
||||
ImageOutputStream ios = null;
|
||||
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
writer = ImageIO.getImageWritersByFormatName("jpg").next();
|
||||
ImageWriteParam param = writer.getDefaultWriteParam();
|
||||
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
||||
param.setCompressionQuality(0.95f);
|
||||
|
||||
ios = ImageIO.createImageOutputStream(baos);
|
||||
writer.setOutput(ios);
|
||||
writer.write(null, new IIOImage(img, null, null), param);
|
||||
return baos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("JPEG encoding failed", e);
|
||||
} finally {
|
||||
if (writer != null) writer.dispose();
|
||||
if (ios != null) try { ios.close(); } catch (IOException ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanup(Graphics2D g, BufferedImage... images) {
|
||||
if (g != null) try { g.dispose(); } catch (Exception ignored) {}
|
||||
for (BufferedImage img : images)
|
||||
if (img != null) try { img.flush(); } catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
+44
-94
@@ -41,16 +41,15 @@ public class MetadataManagementService {
|
||||
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
boolean moveFile = settings.isMoveFilesToLibraryPattern();
|
||||
boolean writeToFile = settings.isSaveToOriginalFile();
|
||||
|
||||
switch (metadataType) {
|
||||
case authors -> consolidateAuthors(targetValues, valuesToMerge, writeToFile, moveFile);
|
||||
case categories -> consolidateCategories(targetValues, valuesToMerge, writeToFile, moveFile);
|
||||
case moods -> consolidateMoods(targetValues, valuesToMerge, writeToFile, moveFile);
|
||||
case tags -> consolidateTags(targetValues, valuesToMerge, writeToFile, moveFile);
|
||||
case series -> consolidateSeries(targetValues, valuesToMerge, writeToFile, moveFile);
|
||||
case publishers -> consolidatePublishers(targetValues, valuesToMerge, writeToFile, moveFile);
|
||||
case languages -> consolidateLanguages(targetValues, valuesToMerge, writeToFile, moveFile);
|
||||
case authors -> consolidateAuthors(targetValues, valuesToMerge, moveFile);
|
||||
case categories -> consolidateCategories(targetValues, valuesToMerge, moveFile);
|
||||
case moods -> consolidateMoods(targetValues, valuesToMerge, moveFile);
|
||||
case tags -> consolidateTags(targetValues, valuesToMerge, moveFile);
|
||||
case series -> consolidateSeries(targetValues, valuesToMerge, moveFile);
|
||||
case publishers -> consolidatePublishers(targetValues, valuesToMerge, moveFile);
|
||||
case languages -> consolidateLanguages(targetValues, valuesToMerge, moveFile);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +63,7 @@ public class MetadataManagementService {
|
||||
Optional<MetadataWriter> writerOpt = metadataWriterFactory.getWriter(bookType);
|
||||
if (writerOpt.isPresent()) {
|
||||
File file = book.getFullFilePath().toFile();
|
||||
writerOpt.get().writeMetadataToFile(file, metadata, null, null);
|
||||
writerOpt.get().saveMetadataToFile(file, metadata, null, null);
|
||||
String newHash = FileFingerprint.generateHash(book.getFullFilePath());
|
||||
book.setCurrentHash(newHash);
|
||||
bookModified = true;
|
||||
@@ -86,7 +85,7 @@ public class MetadataManagementService {
|
||||
}
|
||||
}
|
||||
|
||||
private void consolidateAuthors(List<String> targetValues, List<String> valuesToMerge, boolean writeToFile, boolean moveFile) {
|
||||
private void consolidateAuthors(List<String> targetValues, List<String> valuesToMerge, boolean moveFile) {
|
||||
List<AuthorEntity> targetAuthors = targetValues.stream()
|
||||
.map(name -> authorRepository.findByNameIgnoreCase(name)
|
||||
.map(existing -> {
|
||||
@@ -112,23 +111,19 @@ 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
|
||||
metadata.updateSearchText();
|
||||
}
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithOldAuthor);
|
||||
bookMetadataRepository.flush();
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithOldAuthor, moveFile);
|
||||
}
|
||||
|
||||
writeMetadataToFile(booksWithOldAuthor, moveFile);
|
||||
authorRepository.delete(oldAuthor);
|
||||
}
|
||||
|
||||
log.info("Consolidated {} authors into {}: {}", authorsToMerge.size(), targetValues, valuesToMerge);
|
||||
}
|
||||
|
||||
private void consolidateCategories(List<String> targetValues, List<String> valuesToMerge, boolean writeToFile, boolean moveFile) {
|
||||
private void consolidateCategories(List<String> targetValues, List<String> valuesToMerge, boolean moveFile) {
|
||||
List<CategoryEntity> targetCategories = targetValues.stream()
|
||||
.map(name -> categoryRepository.findByNameIgnoreCase(name)
|
||||
.map(existing -> {
|
||||
@@ -158,18 +153,14 @@ public class MetadataManagementService {
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithOldCategory);
|
||||
bookMetadataRepository.flush();
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithOldCategory, moveFile);
|
||||
}
|
||||
|
||||
writeMetadataToFile(booksWithOldCategory, moveFile);
|
||||
categoryRepository.delete(oldCategory);
|
||||
}
|
||||
|
||||
log.info("Consolidated {} categories into {}: {}", categoriesToMerge.size(), targetValues, valuesToMerge);
|
||||
}
|
||||
|
||||
private void consolidateMoods(List<String> targetValues, List<String> valuesToMerge, boolean writeToFile, boolean moveFile) {
|
||||
private void consolidateMoods(List<String> targetValues, List<String> valuesToMerge, boolean moveFile) {
|
||||
List<MoodEntity> targetMoods = targetValues.stream()
|
||||
.map(name -> moodRepository.findByNameIgnoreCase(name)
|
||||
.map(existing -> {
|
||||
@@ -200,17 +191,14 @@ public class MetadataManagementService {
|
||||
bookMetadataRepository.saveAll(booksWithOldMood);
|
||||
bookMetadataRepository.flush();
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithOldMood, moveFile);
|
||||
}
|
||||
|
||||
writeMetadataToFile(booksWithOldMood, moveFile);
|
||||
moodRepository.delete(oldMood);
|
||||
}
|
||||
|
||||
log.info("Consolidated {} moods into {}: {}", moodsToMerge.size(), targetValues, valuesToMerge);
|
||||
}
|
||||
|
||||
private void consolidateTags(List<String> targetValues, List<String> valuesToMerge, boolean writeToFile, boolean moveFile) {
|
||||
private void consolidateTags(List<String> targetValues, List<String> valuesToMerge, boolean moveFile) {
|
||||
List<TagEntity> targetTags = targetValues.stream()
|
||||
.map(name -> tagRepository.findByNameIgnoreCase(name)
|
||||
.map(existing -> {
|
||||
@@ -241,17 +229,14 @@ public class MetadataManagementService {
|
||||
bookMetadataRepository.saveAll(booksWithOldTag);
|
||||
bookMetadataRepository.flush();
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithOldTag, moveFile);
|
||||
}
|
||||
|
||||
writeMetadataToFile(booksWithOldTag, moveFile);
|
||||
tagRepository.delete(oldTag);
|
||||
}
|
||||
|
||||
log.info("Consolidated {} tags into {}: {}", tagsToMerge.size(), targetValues, valuesToMerge);
|
||||
}
|
||||
|
||||
private void consolidateSeries(List<String> targetValues, List<String> valuesToMerge, boolean writeToFile, boolean moveFile) {
|
||||
private void consolidateSeries(List<String> targetValues, List<String> valuesToMerge, boolean moveFile) {
|
||||
if (targetValues.size() != 1) {
|
||||
throw new IllegalArgumentException("Series merge requires exactly one target value");
|
||||
}
|
||||
@@ -265,16 +250,13 @@ public class MetadataManagementService {
|
||||
}
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithOldSeries);
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithOldSeries, moveFile);
|
||||
}
|
||||
writeMetadataToFile(booksWithOldSeries, moveFile);
|
||||
}
|
||||
|
||||
log.info("Consolidated {} series into '{}': {}", valuesToMerge.size(), targetSeriesName, valuesToMerge);
|
||||
}
|
||||
|
||||
private void consolidatePublishers(List<String> targetValues, List<String> valuesToMerge, boolean writeToFile, boolean moveFile) {
|
||||
private void consolidatePublishers(List<String> targetValues, List<String> valuesToMerge, boolean moveFile) {
|
||||
if (targetValues.size() != 1) {
|
||||
throw new IllegalArgumentException("Publisher merge requires exactly one target value");
|
||||
}
|
||||
@@ -288,16 +270,13 @@ public class MetadataManagementService {
|
||||
}
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithOldPublisher);
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithOldPublisher, moveFile);
|
||||
}
|
||||
writeMetadataToFile(booksWithOldPublisher, moveFile);
|
||||
}
|
||||
|
||||
log.info("Consolidated {} publishers into '{}': {}", valuesToMerge.size(), targetPublisher, valuesToMerge);
|
||||
}
|
||||
|
||||
private void consolidateLanguages(List<String> targetValues, List<String> valuesToMerge, boolean writeToFile, boolean moveFile) {
|
||||
private void consolidateLanguages(List<String> targetValues, List<String> valuesToMerge, boolean moveFile) {
|
||||
if (targetValues.size() != 1) {
|
||||
throw new IllegalArgumentException("Language merge requires exactly one target value");
|
||||
}
|
||||
@@ -311,10 +290,7 @@ public class MetadataManagementService {
|
||||
}
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithOldLanguage);
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithOldLanguage, moveFile);
|
||||
}
|
||||
writeMetadataToFile(booksWithOldLanguage, moveFile);
|
||||
}
|
||||
|
||||
log.info("Consolidated {} languages into '{}': {}", valuesToMerge.size(), targetLanguage, valuesToMerge);
|
||||
@@ -324,20 +300,19 @@ public class MetadataManagementService {
|
||||
public void deleteMetadata(MergeMetadataType metadataType, List<String> valuesToDelete) {
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
boolean moveFile = settings.isMoveFilesToLibraryPattern();
|
||||
boolean writeToFile = settings.isSaveToOriginalFile();
|
||||
|
||||
switch (metadataType) {
|
||||
case authors -> deleteAuthors(valuesToDelete, writeToFile, moveFile);
|
||||
case categories -> deleteCategories(valuesToDelete, writeToFile, moveFile);
|
||||
case moods -> deleteMoods(valuesToDelete, writeToFile, moveFile);
|
||||
case tags -> deleteTags(valuesToDelete, writeToFile, moveFile);
|
||||
case series -> deleteSeries(valuesToDelete, writeToFile, moveFile);
|
||||
case publishers -> deletePublishers(valuesToDelete, writeToFile, moveFile);
|
||||
case languages -> deleteLanguages(valuesToDelete, writeToFile, moveFile);
|
||||
case authors -> deleteAuthors(valuesToDelete, moveFile);
|
||||
case categories -> deleteCategories(valuesToDelete, moveFile);
|
||||
case moods -> deleteMoods(valuesToDelete, moveFile);
|
||||
case tags -> deleteTags(valuesToDelete, moveFile);
|
||||
case series -> deleteSeries(valuesToDelete, moveFile);
|
||||
case publishers -> deletePublishers(valuesToDelete, moveFile);
|
||||
case languages -> deleteLanguages(valuesToDelete, moveFile);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteAuthors(List<String> valuesToDelete, boolean writeToFile, boolean moveFile) {
|
||||
private void deleteAuthors(List<String> valuesToDelete, boolean moveFile) {
|
||||
List<AuthorEntity> authorsToDelete = valuesToDelete.stream()
|
||||
.map(authorRepository::findByName)
|
||||
.filter(java.util.Optional::isPresent)
|
||||
@@ -353,18 +328,14 @@ public class MetadataManagementService {
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithAuthor);
|
||||
bookMetadataRepository.flush();
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithAuthor, moveFile);
|
||||
}
|
||||
|
||||
writeMetadataToFile(booksWithAuthor, moveFile);
|
||||
authorRepository.delete(author);
|
||||
}
|
||||
|
||||
log.info("Deleted {} authors: {}", authorsToDelete.size(), valuesToDelete);
|
||||
}
|
||||
|
||||
private void deleteCategories(List<String> valuesToDelete, boolean writeToFile, boolean moveFile) {
|
||||
private void deleteCategories(List<String> valuesToDelete, boolean moveFile) {
|
||||
List<CategoryEntity> categoriesToDelete = valuesToDelete.stream()
|
||||
.map(categoryRepository::findByNameIgnoreCase)
|
||||
.filter(java.util.Optional::isPresent)
|
||||
@@ -380,18 +351,14 @@ public class MetadataManagementService {
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithCategory);
|
||||
bookMetadataRepository.flush();
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithCategory, moveFile);
|
||||
}
|
||||
|
||||
writeMetadataToFile(booksWithCategory, moveFile);
|
||||
categoryRepository.delete(category);
|
||||
}
|
||||
|
||||
log.info("Deleted {} categories: {}", categoriesToDelete.size(), valuesToDelete);
|
||||
}
|
||||
|
||||
private void deleteMoods(List<String> valuesToDelete, boolean writeToFile, boolean moveFile) {
|
||||
private void deleteMoods(List<String> valuesToDelete, boolean moveFile) {
|
||||
List<MoodEntity> moodsToDelete = valuesToDelete.stream()
|
||||
.map(moodRepository::findByNameIgnoreCase)
|
||||
.filter(java.util.Optional::isPresent)
|
||||
@@ -407,18 +374,14 @@ public class MetadataManagementService {
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithMood);
|
||||
bookMetadataRepository.flush();
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithMood, moveFile);
|
||||
}
|
||||
|
||||
writeMetadataToFile(booksWithMood, moveFile);
|
||||
moodRepository.delete(mood);
|
||||
}
|
||||
|
||||
log.info("Deleted {} moods: {}", moodsToDelete.size(), valuesToDelete);
|
||||
}
|
||||
|
||||
private void deleteTags(List<String> valuesToDelete, boolean writeToFile, boolean moveFile) {
|
||||
private void deleteTags(List<String> valuesToDelete, boolean moveFile) {
|
||||
List<TagEntity> tagsToDelete = valuesToDelete.stream()
|
||||
.map(tagRepository::findByNameIgnoreCase)
|
||||
.filter(java.util.Optional::isPresent)
|
||||
@@ -434,18 +397,14 @@ public class MetadataManagementService {
|
||||
|
||||
bookMetadataRepository.saveAll(booksWithTag);
|
||||
bookMetadataRepository.flush();
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithTag, moveFile);
|
||||
}
|
||||
|
||||
writeMetadataToFile(booksWithTag, moveFile);
|
||||
tagRepository.delete(tag);
|
||||
}
|
||||
|
||||
log.info("Deleted {} tags: {}", tagsToDelete.size(), valuesToDelete);
|
||||
}
|
||||
|
||||
private void deleteSeries(List<String> valuesToDelete, boolean writeToFile, boolean moveFile) {
|
||||
private void deleteSeries(List<String> valuesToDelete, boolean moveFile) {
|
||||
for (String seriesName : valuesToDelete) {
|
||||
List<BookMetadataEntity> booksWithSeries = bookMetadataRepository.findAllBySeriesNameIgnoreCase(seriesName);
|
||||
|
||||
@@ -457,17 +416,14 @@ public class MetadataManagementService {
|
||||
|
||||
if (!booksWithSeries.isEmpty()) {
|
||||
bookMetadataRepository.saveAll(booksWithSeries);
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithSeries, moveFile);
|
||||
}
|
||||
writeMetadataToFile(booksWithSeries, moveFile);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("Deleted {} series: {}", valuesToDelete.size(), valuesToDelete);
|
||||
}
|
||||
|
||||
private void deletePublishers(List<String> valuesToDelete, boolean writeToFile, boolean moveFile) {
|
||||
private void deletePublishers(List<String> valuesToDelete, boolean moveFile) {
|
||||
for (String publisher : valuesToDelete) {
|
||||
List<BookMetadataEntity> booksWithPublisher = bookMetadataRepository.findAllByPublisherIgnoreCase(publisher);
|
||||
|
||||
@@ -477,17 +433,14 @@ public class MetadataManagementService {
|
||||
|
||||
if (!booksWithPublisher.isEmpty()) {
|
||||
bookMetadataRepository.saveAll(booksWithPublisher);
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithPublisher, moveFile);
|
||||
}
|
||||
writeMetadataToFile(booksWithPublisher, moveFile);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("Deleted {} publishers: {}", valuesToDelete.size(), valuesToDelete);
|
||||
}
|
||||
|
||||
private void deleteLanguages(List<String> valuesToDelete, boolean writeToFile, boolean moveFile) {
|
||||
private void deleteLanguages(List<String> valuesToDelete, boolean moveFile) {
|
||||
for (String language : valuesToDelete) {
|
||||
List<BookMetadataEntity> booksWithLanguage = bookMetadataRepository.findAllByLanguageIgnoreCase(language);
|
||||
|
||||
@@ -497,10 +450,7 @@ public class MetadataManagementService {
|
||||
|
||||
if (!booksWithLanguage.isEmpty()) {
|
||||
bookMetadataRepository.saveAll(booksWithLanguage);
|
||||
|
||||
if (writeToFile) {
|
||||
writeMetadataToFile(booksWithLanguage, moveFile);
|
||||
}
|
||||
writeMetadataToFile(booksWithLanguage, moveFile);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+780
-696
File diff suppressed because it is too large
Load Diff
+554
-116
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.comicvineapi.Comic;
|
||||
import com.adityachandel.booklore.model.dto.response.comicvineapi.ComicvineApiResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.comicvineapi.ComicvineIssueResponse;
|
||||
import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.util.BookUtils;
|
||||
@@ -23,11 +24,10 @@ import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -39,6 +39,14 @@ public class ComicvineBookParser implements BookParser {
|
||||
private static final String COMICVINE_URL = "https://comicvine.gamespot.com/api/";
|
||||
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
private static final Pattern DIGIT_PATTERN = Pattern.compile("\\d+");
|
||||
private static final Pattern SERIES_ISSUE_PATTERN = Pattern.compile("^(.+?)\\s+#?(\\d+(?:\\.\\d+)?)(?:\\s|$)", Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern DIGITAL_PATTERN = Pattern.compile("\\(digital\\)", Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern PARENTHETICAL_PATTERN = Pattern.compile("\\([^)]*\\)");
|
||||
private static final Pattern BRACKETED_PATTERN = Pattern.compile("\\[[^\\]]*\\]");
|
||||
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
|
||||
private static final Pattern SPECIAL_ISSUE_PATTERN = Pattern.compile("(annual|special|one-?shot)\\s+(\\d+)", Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern YEAR_PATTERN = Pattern.compile("\\(?(\\d{4})\\)?");
|
||||
private static final long MIN_REQUEST_INTERVAL_MS = 1000;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AppSettingService appSettingService;
|
||||
@@ -46,6 +54,22 @@ public class ComicvineBookParser implements BookParser {
|
||||
|
||||
private final AtomicBoolean rateLimited = new AtomicBoolean(false);
|
||||
private final AtomicLong rateLimitResetTime = new AtomicLong(0);
|
||||
private final AtomicLong lastRequestTime = new AtomicLong(0);
|
||||
private final Map<String, CachedVolumes> volumeCache = new java.util.concurrent.ConcurrentHashMap<>();
|
||||
|
||||
private static class CachedVolumes {
|
||||
final List<Comic> volumes;
|
||||
final long timestamp;
|
||||
|
||||
CachedVolumes(List<Comic> volumes) {
|
||||
this.volumes = volumes;
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
boolean isExpired() {
|
||||
return System.currentTimeMillis() - timestamp > 300_000;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
|
||||
@@ -64,37 +88,247 @@ public class ComicvineBookParser implements BookParser {
|
||||
}
|
||||
|
||||
public List<BookMetadata> getMetadataListByTerm(String term) {
|
||||
SeriesAndIssue seriesAndIssue = extractSeriesAndIssue(term);
|
||||
|
||||
// Try precise search if issue number present
|
||||
if (seriesAndIssue.issue() != null) {
|
||||
log.info("Attempting structured search for Series: '{}', Issue: '{}', Year: '{}', Type: '{}'",
|
||||
seriesAndIssue.series(), seriesAndIssue.issue(), seriesAndIssue.year(), seriesAndIssue.issueType());
|
||||
List<BookMetadata> preciseResults = searchVolumesAndIssues(seriesAndIssue.series(), seriesAndIssue.issue(), seriesAndIssue.year());
|
||||
if (!preciseResults.isEmpty()) {
|
||||
return preciseResults;
|
||||
}
|
||||
log.info("Structured search yielded no results, falling back to general search.");
|
||||
}
|
||||
|
||||
// Fallback to general search
|
||||
return searchGeneral(term);
|
||||
}
|
||||
|
||||
private List<BookMetadata> searchVolumesAndIssues(String seriesName, String issueNumber, Integer extractedYear) {
|
||||
String normalizedIssue = normalizeIssueNumber(issueNumber);
|
||||
if (seriesName.endsWith(" " + issueNumber) || seriesName.endsWith(" " + normalizedIssue)) {
|
||||
// Strip issue number from series name if it leaked in
|
||||
seriesName = seriesName.replaceAll("\\s+" + Pattern.quote(issueNumber) + "$", "")
|
||||
.replaceAll("\\s+" + Pattern.quote(normalizedIssue) + "$", "")
|
||||
.trim();
|
||||
log.warn("Issue number found in series name, corrected to: '{}'", seriesName);
|
||||
}
|
||||
|
||||
final String finalSeriesName = seriesName;
|
||||
log.debug("searchVolumesAndIssues: seriesName='{}', issueNumber='{}', year='{}'", finalSeriesName, issueNumber, extractedYear);
|
||||
List<Comic> volumes = searchVolumes(finalSeriesName);
|
||||
if (volumes.isEmpty()) {
|
||||
log.debug("No volumes found for series '{}'", finalSeriesName);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
// Sort volumes by relevance
|
||||
volumes.sort((v1, v2) -> {
|
||||
int score1 = 0;
|
||||
int score2 = 0;
|
||||
|
||||
if (extractedYear != null) {
|
||||
if (matchesYear(v1, extractedYear)) score1 += 100;
|
||||
if (matchesYear(v2, extractedYear)) score2 += 100;
|
||||
}
|
||||
|
||||
if (v1.getName() != null && v1.getName().equalsIgnoreCase(finalSeriesName)) score1 += 50;
|
||||
if (v2.getName() != null && v2.getName().equalsIgnoreCase(finalSeriesName)) score2 += 50;
|
||||
|
||||
try {
|
||||
int requestedIssue = (int) Math.floor(Double.parseDouble(normalizedIssue));
|
||||
if (v1.getCountOfIssues() != null && v1.getCountOfIssues() >= requestedIssue) score1 += 20;
|
||||
if (v2.getCountOfIssues() != null && v2.getCountOfIssues() >= requestedIssue) score2 += 20;
|
||||
} catch (NumberFormatException ignored) {}
|
||||
|
||||
Set<String> majorPublishers = Set.of("Marvel", "DC Comics", "Image", "Dark Horse Comics", "IDW Publishing");
|
||||
if (v1.getPublisher() != null && majorPublishers.stream().anyMatch(p -> v1.getPublisher().getName().contains(p))) score1 += 10;
|
||||
if (v2.getPublisher() != null && majorPublishers.stream().anyMatch(p -> v2.getPublisher().getName().contains(p))) score2 += 10;
|
||||
|
||||
return Integer.compare(score2, score1);
|
||||
});
|
||||
|
||||
List<BookMetadata> results = new ArrayList<>();
|
||||
// Limit to top 3 volumes to minimize API calls
|
||||
int limit = Math.min(volumes.size(), 3);
|
||||
|
||||
for (int i = 0; i < limit; i++) {
|
||||
Comic volume = volumes.get(i);
|
||||
log.debug("Checking volume: id='{}', name='{}', start_year='{}'", volume.getId(), volume.getName(), volume.getStartYear());
|
||||
|
||||
List<BookMetadata> issues = searchIssuesInVolume(volume.getId(), issueNumber);
|
||||
if (!issues.isEmpty()) {
|
||||
results.addAll(issues);
|
||||
|
||||
// If we found a result in a high-score volume (e.g. year matched), stop.
|
||||
if (extractedYear != null && matchesYear(volume, extractedYear)) {
|
||||
log.info("Found match in year-aligned volume '{}' ({}) . Stopping further volume searches.", volume.getName(), volume.getStartYear());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private boolean matchesYear(Comic volume, int targetYear) {
|
||||
if (volume.getStartYear() == null) return false;
|
||||
try {
|
||||
int volYear = Integer.parseInt(volume.getStartYear());
|
||||
return Math.abs(volYear - targetYear) <= 1;
|
||||
} catch (NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private List<Comic> searchVolumes(String seriesName) {
|
||||
CachedVolumes cached = volumeCache.get(seriesName.toLowerCase());
|
||||
if (cached != null && !cached.isExpired()) {
|
||||
log.debug("Using cached volume search for '{}'", seriesName);
|
||||
return cached.volumes;
|
||||
}
|
||||
|
||||
String apiToken = getApiToken();
|
||||
if (apiToken == null) return Collections.emptyList();
|
||||
|
||||
URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL)
|
||||
.path("/search/")
|
||||
.queryParam("api_key", apiToken)
|
||||
.queryParam("format", "json")
|
||||
.queryParam("resources", "volume")
|
||||
.queryParam("query", seriesName)
|
||||
.queryParam("limit", 10)
|
||||
.queryParam("field_list", "id,name,publisher,start_year,count_of_issues")
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
ComicvineApiResponse response = sendRequest(uri, ComicvineApiResponse.class);
|
||||
List<Comic> volumes = response != null && response.getResults() != null ? response.getResults() : Collections.emptyList();
|
||||
|
||||
if (!volumes.isEmpty()) {
|
||||
volumeCache.put(seriesName.toLowerCase(), new CachedVolumes(volumes));
|
||||
} else if (seriesName.contains(" - ")) {
|
||||
String alternativeName = seriesName.replace(" - ", ": ");
|
||||
log.debug("No results for '{}', trying alternative name '{}'", seriesName, alternativeName);
|
||||
return searchVolumes(alternativeName);
|
||||
}
|
||||
|
||||
return volumes;
|
||||
}
|
||||
|
||||
private List<BookMetadata> searchIssuesInVolume(int volumeId, String issueNumber) {
|
||||
String apiToken = getApiToken();
|
||||
if (apiToken == null) return Collections.emptyList();
|
||||
|
||||
String normalizedIssue = normalizeIssueNumber(issueNumber);
|
||||
log.debug("searchIssuesInVolume: volumeId='{}', original='{}', normalized='{}'",
|
||||
volumeId, issueNumber, normalizedIssue);
|
||||
|
||||
String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "volume", "site_detail_url");
|
||||
|
||||
URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL)
|
||||
.path("/issues/")
|
||||
.queryParam("api_key", apiToken)
|
||||
.queryParam("format", "json")
|
||||
.queryParam("filter", "volume:" + volumeId + ",issue_number:" + normalizedIssue)
|
||||
.queryParam("field_list", fieldsList)
|
||||
.queryParam("limit", 5)
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
ComicvineApiResponse response = sendRequest(uri, ComicvineApiResponse.class);
|
||||
if (response != null && response.getResults() != null && !response.getResults().isEmpty()) {
|
||||
Comic firstIssue = response.getResults().getFirst();
|
||||
String returnedIssue = normalizeIssueNumber(firstIssue.getIssueNumber());
|
||||
|
||||
if (!normalizedIssue.equals(returnedIssue)) {
|
||||
log.warn("Issue number mismatch! Requested '{}', got '{}' from volume {}",
|
||||
normalizedIssue, returnedIssue, volumeId);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
BookMetadata detailed = fetchIssueDetails(firstIssue.getId());
|
||||
|
||||
return Collections.singletonList(Objects.requireNonNullElseGet(detailed, () -> convertToBookMetadata(firstIssue)));
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
private BookMetadata fetchIssueDetails(int issueId) {
|
||||
String apiToken = getApiToken();
|
||||
if (apiToken == null) return null;
|
||||
|
||||
String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "person_credits", "volume", "site_detail_url");
|
||||
|
||||
URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL)
|
||||
.path("/issue/4000-" + issueId + "/")
|
||||
.queryParam("api_key", apiToken)
|
||||
.queryParam("format", "json")
|
||||
.queryParam("field_list", fieldsList)
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
ComicvineIssueResponse response = sendRequest(uri, ComicvineIssueResponse.class);
|
||||
if (response != null && response.getResults() != null) {
|
||||
return convertToBookMetadata(response.getResults());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<BookMetadata> searchGeneral(String term) {
|
||||
String apiToken = getApiToken();
|
||||
if (apiToken == null) return Collections.emptyList();
|
||||
|
||||
String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "publisher", "volume", "site_detail_url", "resource_type", "start_year", "count_of_issues");
|
||||
String resources = "volume,issue";
|
||||
|
||||
URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL)
|
||||
.path("/search/")
|
||||
.queryParam("api_key", apiToken)
|
||||
.queryParam("format", "json")
|
||||
.queryParam("resources", resources)
|
||||
.queryParam("query", term)
|
||||
.queryParam("limit", 10)
|
||||
.queryParam("field_list", fieldsList)
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
ComicvineApiResponse response = sendRequest(uri, ComicvineApiResponse.class);
|
||||
if (response != null && response.getResults() != null) {
|
||||
return response.getResults().stream()
|
||||
.map(this::convertToBookMetadata)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
private <T> T sendRequest(URI uri, Class<T> responseType) {
|
||||
return sendRequestWithRetry(uri, responseType, 2);
|
||||
}
|
||||
|
||||
private <T> T sendRequestWithRetry(URI uri, Class<T> responseType, int retriesLeft) {
|
||||
if (rateLimited.get()) {
|
||||
long currentTime = System.currentTimeMillis();
|
||||
if (currentTime < rateLimitResetTime.get()) {
|
||||
log.warn("ComicVine API is currently rate limited. Skipping request for term: '{}'. Rate limit resets at: {}",
|
||||
term, Instant.ofEpochMilli(rateLimitResetTime.get()));
|
||||
return Collections.emptyList();
|
||||
log.warn("ComicVine API is currently rate limited. Skipping request. Rate limit resets at: {}",
|
||||
Instant.ofEpochMilli(rateLimitResetTime.get()));
|
||||
return null;
|
||||
} else {
|
||||
// Rate limit has expired, reset the flag
|
||||
rateLimited.compareAndSet(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("Comicvine: Fetching metadata for term: '{}'", term);
|
||||
long now = System.currentTimeMillis();
|
||||
long timeSinceLastRequest = now - lastRequestTime.get();
|
||||
if (timeSinceLastRequest < MIN_REQUEST_INTERVAL_MS) {
|
||||
try {
|
||||
Thread.sleep(MIN_REQUEST_INTERVAL_MS - timeSinceLastRequest);
|
||||
} catch (InterruptedException ignored) {}
|
||||
}
|
||||
lastRequestTime.set(System.currentTimeMillis());
|
||||
|
||||
try {
|
||||
String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "publisher", "volume");
|
||||
String resources = "volume,issue";
|
||||
|
||||
URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL)
|
||||
.path("/search/")
|
||||
.queryParam("api_key", apiToken)
|
||||
.queryParam("format", "json")
|
||||
.queryParam("resources", resources)
|
||||
.queryParam("query", term)
|
||||
.queryParam("limit", 10)
|
||||
.queryParam("field_list", fieldsList)
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
log.debug("Sending request to ComicVine: {}", uri);
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(uri)
|
||||
.header("User-Agent", "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)")
|
||||
@@ -102,77 +336,323 @@ public class ComicvineBookParser implements BookParser {
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
log.debug("Received response from ComicVine: status='{}', body_length='{}'",
|
||||
response.statusCode(), response.body() != null ? response.body().length() : 0);
|
||||
|
||||
if (response.statusCode() == 200) {
|
||||
return parseComicvineApiResponse(response.body());
|
||||
return objectMapper.readValue(response.body(), responseType);
|
||||
} else if (response.statusCode() == 420 || response.statusCode() == 429) {
|
||||
log.error("ComicVine API rate limit exceeded (Error {}). Setting rate limit flag.", response.statusCode());
|
||||
handleRateLimit(response);
|
||||
return null;
|
||||
} else if (response.statusCode() >= 500 && retriesLeft > 0) {
|
||||
log.warn("ComicVine API returned status {}. Retrying... ({} retries left)",
|
||||
response.statusCode(), retriesLeft);
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException ignored) {}
|
||||
return sendRequestWithRetry(uri, responseType, retriesLeft - 1);
|
||||
} else {
|
||||
log.error("Comicvine API returned status code {}. Body: {}", response.statusCode(), response.body());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
if (retriesLeft > 0) {
|
||||
log.warn("IOException during ComicVine request. Retrying... ({} retries left)", retriesLeft, e);
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException ignored) {}
|
||||
return sendRequestWithRetry(uri, responseType, retriesLeft - 1);
|
||||
} else {
|
||||
log.error("Error fetching data from Comicvine API after retries", e);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
log.error("Request interrupted", e);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
long resetDelayMs = 3600000; // Default to 1 hour
|
||||
List<String> retryAfterHeaders = response.headers().allValues("Retry-After");
|
||||
if (!retryAfterHeaders.isEmpty()) {
|
||||
try {
|
||||
String retryAfter = retryAfterHeaders.getFirst();
|
||||
if (DIGIT_PATTERN.matcher(retryAfter).matches()) {
|
||||
resetDelayMs = Long.parseLong(retryAfter) * 1000;
|
||||
} else {
|
||||
Instant instant = Instant.parse(retryAfter);
|
||||
resetDelayMs = instant.toEpochMilli() - System.currentTimeMillis();
|
||||
if (resetDelayMs <= 0) {
|
||||
resetDelayMs = 3600000; // Default to 1 hour if date is in the past
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Could not parse Retry-After header '{}', using default 1 hour delay", retryAfterHeaders.getFirst());
|
||||
private void handleRateLimit(HttpResponse<String> response) {
|
||||
log.error("ComicVine API rate limit exceeded (Error {}). Setting rate limit flag.", response.statusCode());
|
||||
|
||||
long resetDelayMs = 3600000;
|
||||
List<String> retryAfterHeaders = response.headers().allValues("Retry-After");
|
||||
if (!retryAfterHeaders.isEmpty()) {
|
||||
try {
|
||||
String retryAfter = retryAfterHeaders.getFirst();
|
||||
if (DIGIT_PATTERN.matcher(retryAfter).matches()) {
|
||||
resetDelayMs = Long.parseLong(retryAfter) * 1000;
|
||||
} else {
|
||||
Instant instant = Instant.parse(retryAfter);
|
||||
resetDelayMs = instant.toEpochMilli() - System.currentTimeMillis();
|
||||
if (resetDelayMs <= 0) {
|
||||
resetDelayMs = 3600000;
|
||||
}
|
||||
}
|
||||
|
||||
if (rateLimited.compareAndSet(false, true)) {
|
||||
rateLimitResetTime.set(System.currentTimeMillis() + resetDelayMs);
|
||||
log.info("Rate limit will reset at: {}", Instant.ofEpochMilli(rateLimitResetTime.get()));
|
||||
}
|
||||
|
||||
return Collections.emptyList();
|
||||
} else {
|
||||
log.error("Comicvine Search API returned status code {}", response.statusCode());
|
||||
} catch (Exception e) {
|
||||
log.warn("Could not parse Retry-After header '{}', using default 1 hour delay", retryAfterHeaders.getFirst());
|
||||
}
|
||||
} catch (IOException | InterruptedException e) {
|
||||
log.error("Error fetching metadata from Comicvine Search API", e);
|
||||
}
|
||||
return Collections.emptyList();
|
||||
|
||||
if (rateLimited.compareAndSet(false, true)) {
|
||||
rateLimitResetTime.set(System.currentTimeMillis() + resetDelayMs);
|
||||
log.info("Rate limit will reset at: {}", Instant.ofEpochMilli(rateLimitResetTime.get()));
|
||||
}
|
||||
}
|
||||
|
||||
private BookMetadata convertToBookMetadata(Comic comic) {
|
||||
// Check if this is a Volume
|
||||
if ("volume".equalsIgnoreCase(comic.getResourceType())) {
|
||||
return BookMetadata.builder()
|
||||
.provider(MetadataProvider.Comicvine)
|
||||
.comicvineId(String.valueOf(comic.getId()))
|
||||
.title(comic.getName()) // Use volume name as title
|
||||
.seriesName(comic.getName())
|
||||
.seriesTotal(comic.getCountOfIssues())
|
||||
.publishedDate(safeParseDate(comic.getStartYear() + "-01-01")) // Rough estimate if only year
|
||||
.description(comic.getDescription())
|
||||
.publisher(comic.getPublisher() != null ? comic.getPublisher().getName() : null)
|
||||
.thumbnailUrl(comic.getImage() != null ? comic.getImage().getMediumUrl() : null)
|
||||
.externalUrl(comic.getSiteDetailUrl())
|
||||
.build();
|
||||
}
|
||||
|
||||
Set<String> authors = extractAuthors(comic.getPersonCredits());
|
||||
String formattedTitle = formatTitle(comic.getVolume() != null ? comic.getVolume().getName() : null, comic.getIssueNumber(), comic.getName());
|
||||
|
||||
BookMetadata metadata = BookMetadata.builder()
|
||||
.provider(MetadataProvider.Comicvine)
|
||||
.comicvineId(String.valueOf(comic.getId()))
|
||||
.title(formattedTitle)
|
||||
.authors(authors)
|
||||
.thumbnailUrl(comic.getImage() != null ? comic.getImage().getMediumUrl() : null)
|
||||
.description(comic.getDescription())
|
||||
.seriesName(comic.getVolume() != null ? comic.getVolume().getName() : null)
|
||||
.seriesNumber(safeParseFloat(comic.getIssueNumber()))
|
||||
.publishedDate(safeParseDate(comic.getCoverDate()))
|
||||
.externalUrl(comic.getSiteDetailUrl())
|
||||
.build();
|
||||
|
||||
if (metadata.getSeriesName() == null || metadata.getSeriesNumber() == null) {
|
||||
log.warn("Incomplete metadata for issue {}: missing series name or number", metadata.getComicvineId());
|
||||
}
|
||||
|
||||
if (metadata.getAuthors().isEmpty()) {
|
||||
log.debug("No authors found for issue {} ({})", metadata.getComicvineId(), metadata.getTitle());
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private BookMetadata convertToBookMetadata(ComicvineIssueResponse.IssueResults issue) {
|
||||
// Extract ID from api_detail_url: "https://comicvine.gamespot.com/api/issue/4000-12345/"
|
||||
String comicvineId = null;
|
||||
if (issue.getApiDetailUrl() != null) {
|
||||
Matcher matcher = Pattern.compile("/(\\d+)/?$").matcher(issue.getApiDetailUrl());
|
||||
if (matcher.find()) {
|
||||
comicvineId = matcher.group(1);
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> authors = extractAuthors(issue.getPersonCredits());
|
||||
String formattedTitle = formatTitle(issue.getVolume() != null ? issue.getVolume().getName() : null, issue.getIssueNumber(), issue.getName());
|
||||
|
||||
BookMetadata metadata = BookMetadata.builder()
|
||||
.provider(MetadataProvider.Comicvine)
|
||||
.comicvineId(comicvineId)
|
||||
.title(formattedTitle)
|
||||
.authors(authors)
|
||||
.thumbnailUrl(issue.getImage() != null ? issue.getImage().getMediumUrl() : null)
|
||||
.description(issue.getDescription())
|
||||
.seriesName(issue.getVolume() != null ? issue.getVolume().getName() : null)
|
||||
.seriesNumber(safeParseFloat(issue.getIssueNumber()))
|
||||
.publishedDate(safeParseDate(issue.getCoverDate()))
|
||||
.externalUrl(issue.getSiteDetailUrl())
|
||||
.build();
|
||||
|
||||
if (metadata.getSeriesName() == null || metadata.getSeriesNumber() == null) {
|
||||
log.warn("Incomplete metadata for issue {}: missing series name or number", comicvineId);
|
||||
}
|
||||
|
||||
if (metadata.getAuthors().isEmpty()) {
|
||||
log.debug("No authors found for issue {} ({})", comicvineId, metadata.getTitle());
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private String formatTitle(String seriesName, String issueNumber, String issueName) {
|
||||
if (seriesName == null) return issueName;
|
||||
|
||||
String normalizedIssue = normalizeIssueNumber(issueNumber);
|
||||
String title = seriesName + " #" + (normalizedIssue != null ? normalizedIssue : "");
|
||||
|
||||
// Append issue title if it exists and isn't just "Issue #X" or identical to series
|
||||
if (issueName != null && !issueName.isBlank()) {
|
||||
String lowerName = issueName.toLowerCase();
|
||||
boolean isGeneric = lowerName.matches("issue\\s*#?\\d+") || lowerName.equals(seriesName.toLowerCase());
|
||||
if (!isGeneric) {
|
||||
title += " - " + issueName;
|
||||
}
|
||||
}
|
||||
return title;
|
||||
}
|
||||
|
||||
private Set<String> extractAuthors(List<Comic.PersonCredit> personCredits) {
|
||||
if (personCredits == null || personCredits.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
// Primary writer roles
|
||||
Set<String> writerRoles = Set.of("writer", "script", "story", "plotter", "plot");
|
||||
|
||||
// Collect writers
|
||||
Set<String> authors = personCredits.stream()
|
||||
.filter(pc -> {
|
||||
if (pc.getRole() == null) return false;
|
||||
String role = pc.getRole().toLowerCase();
|
||||
return writerRoles.stream().anyMatch(role::contains);
|
||||
})
|
||||
.map(Comic.PersonCredit::getName)
|
||||
.filter(name -> name != null && !name.isEmpty())
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// Fallback: If no writers found, check for "creator" role
|
||||
if (authors.isEmpty()) {
|
||||
// DEBUG: Log all roles if we missed them
|
||||
List<String> allRoles = personCredits.stream()
|
||||
.map(pc -> pc.getName() + " (" + pc.getRole() + ")")
|
||||
.toList();
|
||||
log.debug("No writers found. Available roles: {}", allRoles);
|
||||
|
||||
authors = personCredits.stream()
|
||||
.filter(pc -> pc.getRole() != null && pc.getRole().toLowerCase().contains("creator"))
|
||||
.map(Comic.PersonCredit::getName)
|
||||
.filter(name -> name != null && !name.isEmpty())
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
return authors;
|
||||
}
|
||||
|
||||
private String getSearchTerm(Book book, FetchMetadataRequest request) {
|
||||
if (request.getTitle() != null && !request.getTitle().isEmpty()) {
|
||||
return request.getTitle();
|
||||
} else if (book.getFileName() != null && !book.getFileName().isEmpty()) {
|
||||
return BookUtils.cleanFileName(book.getFileName());
|
||||
// Use filename but preserve parentheses for year extraction
|
||||
String name = book.getFileName();
|
||||
// Remove extension only
|
||||
int dotIndex = name.lastIndexOf('.');
|
||||
if (dotIndex > 0) {
|
||||
name = name.substring(0, dotIndex);
|
||||
}
|
||||
return name.trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<BookMetadata> parseComicvineApiResponse(String responseBody) throws IOException {
|
||||
ComicvineApiResponse apiResponse = objectMapper.readValue(responseBody, ComicvineApiResponse.class);
|
||||
if (apiResponse.getResults() == null) {
|
||||
return Collections.emptyList();
|
||||
private SeriesAndIssue extractSeriesAndIssue(String term) {
|
||||
// 1. Extract Year
|
||||
Integer year = null;
|
||||
Matcher yearMatcher = YEAR_PATTERN.matcher(term);
|
||||
String yearString = null;
|
||||
if (yearMatcher.find()) {
|
||||
try {
|
||||
int y = Integer.parseInt(yearMatcher.group(1));
|
||||
if (y > 1900 && y <= LocalDate.now().getYear() + 1) {
|
||||
year = y;
|
||||
yearString = yearMatcher.group(0);
|
||||
}
|
||||
} catch (NumberFormatException ignored) {}
|
||||
}
|
||||
return apiResponse.getResults().stream()
|
||||
.map(this::convertToBookMetadata)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private BookMetadata convertToBookMetadata(Comic comic) {
|
||||
return BookMetadata.builder()
|
||||
.provider(MetadataProvider.Comicvine)
|
||||
.comicvineId(String.valueOf(comic.getId()))
|
||||
.title(comic.getName())
|
||||
.authors(new HashSet<>())
|
||||
.thumbnailUrl(comic.getImage() != null ? comic.getImage().getMediumUrl() : null)
|
||||
.description(comic.getDescription())
|
||||
.seriesName(comic.getVolume() != null ? comic.getVolume().getName() : null)
|
||||
.seriesNumber(safeParseFloat(comic.getIssueNumber()))
|
||||
.publishedDate(safeParseDate(comic.getCoverDate()))
|
||||
.build();
|
||||
// 2. Remove ONLY the found year and noise from the term
|
||||
String cleaned = term;
|
||||
if (yearString != null) {
|
||||
cleaned = cleaned.replace(yearString, "");
|
||||
}
|
||||
cleaned = DIGITAL_PATTERN.matcher(cleaned).replaceAll("");
|
||||
cleaned = PARENTHETICAL_PATTERN.matcher(cleaned).replaceAll("");
|
||||
cleaned = BRACKETED_PATTERN.matcher(cleaned).replaceAll("");
|
||||
cleaned = cleaned.trim();
|
||||
cleaned = WHITESPACE_PATTERN.matcher(cleaned).replaceAll(" ");
|
||||
|
||||
log.debug("Cleaned filename: '{}'", cleaned);
|
||||
|
||||
// 3. Check for special issue keywords BEFORE extracting issue number
|
||||
String lowerCleaned = cleaned.toLowerCase();
|
||||
if (lowerCleaned.contains("annual") ||
|
||||
lowerCleaned.contains("special") ||
|
||||
lowerCleaned.contains("one-shot") ||
|
||||
lowerCleaned.contains("one shot")) {
|
||||
|
||||
// Try to extract number from "Annual 2" or "Special 3"
|
||||
Matcher specialMatcher = SPECIAL_ISSUE_PATTERN.matcher(cleaned);
|
||||
if (specialMatcher.find()) {
|
||||
String type = specialMatcher.group(1);
|
||||
String num = specialMatcher.group(2);
|
||||
// Return series name before the special keyword
|
||||
String series = cleaned.substring(0, specialMatcher.start()).trim();
|
||||
return new SeriesAndIssue(series, num, year, type);
|
||||
} else {
|
||||
// "Batman Annual" without number - search for all annuals
|
||||
return new SeriesAndIssue(cleaned, null, year, "annual");
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Standard issue extraction with IMPROVED PATTERN
|
||||
Matcher matcher = SERIES_ISSUE_PATTERN.matcher(cleaned);
|
||||
if (matcher.find()) {
|
||||
String series = matcher.group(1).trim();
|
||||
String issueNum = matcher.group(2);
|
||||
|
||||
if (series.endsWith("#")) {
|
||||
series = series.substring(0, series.length() - 1).trim();
|
||||
}
|
||||
|
||||
log.debug("Extracted - Series: '{}', Issue: '{}'", series, issueNum);
|
||||
return new SeriesAndIssue(series, issueNum, year, null);
|
||||
}
|
||||
|
||||
log.debug("No issue number found in: '{}'", cleaned);
|
||||
return new SeriesAndIssue(cleaned, null, year, null);
|
||||
}
|
||||
|
||||
private String normalizeIssueNumber(String issueNumber) {
|
||||
if (issueNumber == null || issueNumber.isEmpty()) {
|
||||
return issueNumber;
|
||||
}
|
||||
|
||||
issueNumber = issueNumber.trim();
|
||||
|
||||
if (issueNumber.contains("/")) {
|
||||
try {
|
||||
String[] parts = issueNumber.split("/");
|
||||
if (parts.length == 2) {
|
||||
double numerator = Double.parseDouble(parts[0]);
|
||||
double denominator = Double.parseDouble(parts[1]);
|
||||
return String.valueOf(numerator / denominator);
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("Could not parse fractional issue number '{}'", issueNumber);
|
||||
return issueNumber;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (issueNumber.contains(".")) {
|
||||
double d = Double.parseDouble(issueNumber);
|
||||
if (d == Math.floor(d)) {
|
||||
return String.valueOf((int) d);
|
||||
} else {
|
||||
return new java.text.DecimalFormat("0.#####").format(d);
|
||||
}
|
||||
} else {
|
||||
return String.valueOf(Integer.parseInt(issueNumber));
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
log.debug("Non-numeric issue number '{}', using as-is", issueNumber);
|
||||
return issueNumber;
|
||||
}
|
||||
}
|
||||
|
||||
private static LocalDate safeParseDate(String dateStr) {
|
||||
@@ -203,47 +683,5 @@ public class ComicvineBookParser implements BookParser {
|
||||
return apiToken;
|
||||
}
|
||||
|
||||
/*public Set<String> fetchAuthors(int issueId) {
|
||||
String apiToken = getApiToken();
|
||||
if (apiToken == null) return Collections.emptySet();
|
||||
|
||||
try {
|
||||
String fieldsList = String.join(",", "person_credits");
|
||||
|
||||
URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL)
|
||||
.path("/issue/4000-" + issueId + "/")
|
||||
.queryParam("api_key", apiToken)
|
||||
.queryParam("format", "json")
|
||||
.queryParam("field_list", fieldsList)
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(uri)
|
||||
.header("User-Agent", "Booklore/1.0")
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() == 200) {
|
||||
ComicvineIssueResponse issueResponse = objectMapper.readValue(response.body(), ComicvineIssueResponse.class);
|
||||
if (issueResponse.getResults() == null || issueResponse.getResults().getPersonCredits() == null) {
|
||||
log.warn("No person credits found for issue ID {}", issueId);
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
return issueResponse.getResults().getPersonCredits().stream()
|
||||
.filter(pc -> pc.getRole() != null && pc.getRole().toLowerCase().contains("writer"))
|
||||
.map(ComicvineIssueResponse.PersonCredit::getName)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
} else {
|
||||
log.error("Comicvine Issue API returned status code {}", response.statusCode());
|
||||
}
|
||||
} catch (IOException | InterruptedException e) {
|
||||
log.error("Error fetching issue metadata from Comicvine Issue API", e);
|
||||
}
|
||||
return Collections.emptySet();
|
||||
}*/
|
||||
private record SeriesAndIssue(String series, String issue, Integer year, String issueType) {}
|
||||
}
|
||||
+9
-4
@@ -478,10 +478,15 @@ public class GoodReadsParser implements BookParser {
|
||||
|
||||
try {
|
||||
String searchUrl = generateSearchUrl(searchTerm);
|
||||
Elements previewBooks = fetchDoc(searchUrl)
|
||||
.select("table.tableList")
|
||||
.first()
|
||||
.select("tr[itemtype=http://schema.org/Book]");
|
||||
Document doc = fetchDoc(searchUrl);
|
||||
Element tableList = doc.select("table.tableList").first();
|
||||
|
||||
if (tableList == null) {
|
||||
log.warn("GoodReads: No results table found for search term: {}", searchTerm);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
Elements previewBooks = tableList.select("tr[itemtype=http://schema.org/Book]");
|
||||
|
||||
List<BookMetadata> metadataPreviews = new ArrayList<>();
|
||||
FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);
|
||||
|
||||
+420
-327
@@ -1,10 +1,13 @@
|
||||
package com.adityachandel.booklore.service.metadata.writer;
|
||||
|
||||
import com.adityachandel.booklore.model.MetadataClearFlags;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
|
||||
@@ -38,414 +41,509 @@ import java.util.zip.ZipOutputStream;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class CbxMetadataWriter implements MetadataWriter {
|
||||
|
||||
private static final Pattern VALID_FILENAME_PATTERN = Pattern.compile("^[\\w./\\\\-]+$");
|
||||
private static final int BUFFER_SIZE = 8192;
|
||||
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
@Override
|
||||
public void writeMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags) {
|
||||
Path backup = null;
|
||||
Path tempDir = null;
|
||||
Path tempFile = null;
|
||||
boolean writeSucceeded = false;
|
||||
try {
|
||||
// Create a backup next to the source file (temp name, safe to delete later)
|
||||
backup = Files.createTempFile(file.getParentFile().toPath(), "cbx_backup_", ".bak");
|
||||
Files.copy(file.toPath(), backup, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (Exception ex) {
|
||||
log.warn("Unable to create backup for {}: {}", file.getAbsolutePath(), ex.getMessage(), ex);
|
||||
public void saveMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags) {
|
||||
if (!shouldSaveMetadataToFile(file)) {
|
||||
return;
|
||||
}
|
||||
String fileName = file.getName().toLowerCase(Locale.ROOT);
|
||||
boolean isCbz = fileName.endsWith(".cbz");
|
||||
boolean isCbr = fileName.endsWith(".cbr");
|
||||
boolean isCb7 = fileName.endsWith(".cb7");
|
||||
|
||||
if (!isCbz && !isCbr && !isCb7) {
|
||||
log.warn("Unsupported file type for CBX writer: {}", file.getName());
|
||||
return;
|
||||
}
|
||||
|
||||
Path backupPath = createBackupFile(file);
|
||||
Path extractDir = null;
|
||||
Path tempArchive = null;
|
||||
boolean writeSucceeded = false;
|
||||
|
||||
try {
|
||||
String nameLower = file.getName().toLowerCase(Locale.ROOT);
|
||||
boolean isCbz = nameLower.endsWith(".cbz");
|
||||
boolean isCbr = nameLower.endsWith(".cbr");
|
||||
boolean isCb7 = nameLower.endsWith(".cb7");
|
||||
Document xmlDoc = loadOrCreateComicInfoXml(file, isCbz, isCb7, isCbr);
|
||||
applyMetadataChanges(xmlDoc, metadata, clearFlags);
|
||||
byte[] xmlContent = convertDocumentToBytes(xmlDoc);
|
||||
|
||||
if (!isCbz && !isCbr && !isCb7) {
|
||||
log.warn("Unsupported file type for CBX writer: {}", file.getName());
|
||||
return;
|
||||
}
|
||||
|
||||
// Build (or load and update) ComicInfo.xml as a Document
|
||||
Document doc;
|
||||
if (isCbz) {
|
||||
try (ZipFile zipFile = new ZipFile(file)) {
|
||||
ZipEntry existing = findComicInfoEntry(zipFile);
|
||||
if (existing != null) {
|
||||
try (InputStream is = zipFile.getInputStream(existing)) {
|
||||
doc = buildSecureDocument(is);
|
||||
}
|
||||
} else {
|
||||
doc = newEmptyComicInfo();
|
||||
}
|
||||
}
|
||||
tempArchive = updateZipArchive(file, xmlContent);
|
||||
writeSucceeded = true;
|
||||
} else if (isCb7) {
|
||||
try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) {
|
||||
SevenZArchiveEntry existing = null;
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (e != null && !e.isDirectory() && isComicInfoName(e.getName())) {
|
||||
existing = e;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (existing != null) {
|
||||
try (InputStream is = sevenZ.getInputStream(existing)) {
|
||||
doc = buildSecureDocument(is);
|
||||
}
|
||||
} else {
|
||||
doc = newEmptyComicInfo();
|
||||
}
|
||||
}
|
||||
} else { // CBR
|
||||
try (Archive archive = new Archive(file)) {
|
||||
FileHeader existing = findComicInfoHeader(archive);
|
||||
if (existing != null) {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
archive.extractFile(existing, baos);
|
||||
try (InputStream is = new java.io.ByteArrayInputStream(baos.toByteArray())) {
|
||||
doc = buildSecureDocument(is);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
doc = newEmptyComicInfo();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply metadata to the Document
|
||||
Element root = doc.getDocumentElement();
|
||||
MetadataCopyHelper helper = new MetadataCopyHelper(metadata);
|
||||
helper.copyTitle(clearFlags != null && clearFlags.isTitle(), val -> setElement(doc, root, "Title", val));
|
||||
helper.copyDescription(clearFlags != null && clearFlags.isDescription(), val -> {
|
||||
setElement(doc, root, "Summary", val);
|
||||
removeElement(root, "Description");
|
||||
});
|
||||
helper.copyPublisher(clearFlags != null && clearFlags.isPublisher(), val -> setElement(doc, root, "Publisher", val));
|
||||
helper.copySeriesName(clearFlags != null && clearFlags.isSeriesName(), val -> setElement(doc, root, "Series", val));
|
||||
helper.copySeriesNumber(clearFlags != null && clearFlags.isSeriesNumber(), val -> setElement(doc, root, "Number", formatFloat(val)));
|
||||
helper.copySeriesTotal(clearFlags != null && clearFlags.isSeriesTotal(), val -> setElement(doc, root, "Count", val != null ? val.toString() : null));
|
||||
helper.copyPublishedDate(clearFlags != null && clearFlags.isPublishedDate(), date -> setDateElements(doc, root, date));
|
||||
helper.copyPageCount(clearFlags != null && clearFlags.isPageCount(), val -> setElement(doc, root, "PageCount", val != null ? val.toString() : null));
|
||||
helper.copyLanguage(clearFlags != null && clearFlags.isLanguage(), val -> setElement(doc, root, "LanguageISO", val));
|
||||
helper.copyAuthors(clearFlags != null && clearFlags.isAuthors(), set -> {
|
||||
setElement(doc, root, "Writer", join(set));
|
||||
removeElement(root, "Penciller");
|
||||
removeElement(root, "Inker");
|
||||
removeElement(root, "Colorist");
|
||||
removeElement(root, "Letterer");
|
||||
removeElement(root, "CoverArtist");
|
||||
});
|
||||
helper.copyCategories(clearFlags != null && clearFlags.isCategories(), set -> {
|
||||
setElement(doc, root, "Genre", join(set));
|
||||
removeElement(root, "Tags");
|
||||
});
|
||||
|
||||
// Serialize ComicInfo.xml
|
||||
Transformer transformer = TransformerFactory.newInstance().newTransformer();
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||
ByteArrayOutputStream xmlBaos = new ByteArrayOutputStream();
|
||||
transformer.transform(new DOMSource(doc), new StreamResult(xmlBaos));
|
||||
byte[] xmlBytes = xmlBaos.toByteArray();
|
||||
|
||||
// Repack depending on container type; always write to a temp target then atomic move
|
||||
if (isCbz) {
|
||||
tempFile = Files.createTempFile("cbx_edit", ".cbz");
|
||||
repackZipReplacingComicInfo(file.toPath(), tempFile, xmlBytes);
|
||||
atomicReplace(tempFile, file.toPath());
|
||||
tempFile = null; // Successfully moved, don't delete in finally
|
||||
tempArchive = convert7zToZip(file, xmlContent);
|
||||
writeSucceeded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (isCb7) {
|
||||
// Convert to CBZ with updated ComicInfo.xml
|
||||
tempFile = Files.createTempFile("cbx_edit", ".cbz");
|
||||
try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get();
|
||||
ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(tempFile))) {
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (e.isDirectory()) continue;
|
||||
String entryName = e.getName();
|
||||
if (isComicInfoName(entryName)) continue; // skip old
|
||||
if (!isSafeEntryName(entryName)) {
|
||||
log.warn("Skipping unsafe 7z entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry(entryName));
|
||||
try (InputStream is = sevenZ.getInputStream(e)) {
|
||||
if (is != null) is.transferTo(zos);
|
||||
}
|
||||
zos.closeEntry();
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry("ComicInfo.xml"));
|
||||
zos.write(xmlBytes);
|
||||
zos.closeEntry();
|
||||
}
|
||||
Path target = file.toPath().resolveSibling(stripExtension(file.getName()) + ".cbz");
|
||||
atomicReplace(tempFile, target);
|
||||
tempFile = null; // Successfully moved, don't delete in finally
|
||||
try {
|
||||
Files.deleteIfExists(file.toPath());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
writeSucceeded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// CBR path
|
||||
String rarBin = System.getenv().getOrDefault("BOOKLORE_RAR_BIN", "rar");
|
||||
boolean rarAvailable = isRarAvailable(rarBin);
|
||||
|
||||
if (rarAvailable) {
|
||||
tempDir = Files.createTempDirectory("cbx_rar_");
|
||||
// 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);
|
||||
|
||||
// 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());
|
||||
tempArchive = updateRarArchive(file, xmlContent, extractDir);
|
||||
writeSucceeded = true;
|
||||
}
|
||||
|
||||
// Fallback: convert the CBR to CBZ containing updated ComicInfo.xml
|
||||
tempFile = Files.createTempFile("cbx_edit", ".cbz");
|
||||
try (Archive archive = new Archive(file);
|
||||
ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(tempFile))) {
|
||||
for (FileHeader fh : archive.getFileHeaders()) {
|
||||
if (fh.isDirectory()) continue;
|
||||
String entryName = fh.getFileName();
|
||||
if (isComicInfoName(entryName)) continue; // skip old
|
||||
if (!isSafeEntryName(entryName)) {
|
||||
log.warn("Skipping unsafe RAR entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry(entryName));
|
||||
archive.extractFile(fh, zos);
|
||||
zos.closeEntry();
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry("ComicInfo.xml"));
|
||||
zos.write(xmlBytes);
|
||||
zos.closeEntry();
|
||||
}
|
||||
Path target = file.toPath().resolveSibling(stripExtension(file.getName()) + ".cbz");
|
||||
atomicReplace(tempFile, target);
|
||||
tempFile = null; // Successfully moved, don't delete in finally
|
||||
try {
|
||||
Files.deleteIfExists(file.toPath());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
writeSucceeded = true;
|
||||
} catch (Exception e) {
|
||||
// Attempt to restore the original file from backup
|
||||
try {
|
||||
if (backup != null) {
|
||||
Files.copy(backup, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
log.info("Restored original file from backup after failure: {}", file.getAbsolutePath());
|
||||
}
|
||||
} catch (Exception restoreEx) {
|
||||
log.warn("Failed to restore original file from backup: {} -> {}", backup, file.getAbsolutePath(), restoreEx);
|
||||
}
|
||||
restoreOriginalFile(backupPath, file);
|
||||
log.warn("Failed to write metadata for {}: {}", file.getName(), e.getMessage(), e);
|
||||
} finally {
|
||||
// Clean up temporary file if it wasn't successfully moved
|
||||
if (tempFile != null) {
|
||||
try {
|
||||
Files.deleteIfExists(tempFile);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to delete temp file: {}", tempFile, e);
|
||||
cleanupTempFiles(tempArchive, extractDir, backupPath, writeSucceeded);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean shouldSaveMetadataToFile(File file) {
|
||||
MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings().getMetadataPersistenceSettings().getSaveToOriginalFile();
|
||||
|
||||
MetadataPersistenceSettings.FormatSettings cbxSettings = settings.getCbx();
|
||||
if (cbxSettings == null || !cbxSettings.isEnabled()) {
|
||||
log.debug("CBX metadata writing is disabled. Skipping: {}", file.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
long fileSizeInMb = file.length() / (1024 * 1024);
|
||||
if (fileSizeInMb > cbxSettings.getMaxFileSizeInMb()) {
|
||||
log.info("CBX file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", file.getName(), fileSizeInMb, cbxSettings.getMaxFileSizeInMb());
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private Path createBackupFile(File file) {
|
||||
try {
|
||||
Path backupPath = Files.createTempFile(file.getParentFile().toPath(), "cbx_backup_", ".bak");
|
||||
Files.copy(file.toPath(), backupPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
return backupPath;
|
||||
} catch (Exception ex) {
|
||||
log.warn("Unable to create backup for {}: {}", file.getAbsolutePath(), ex.getMessage(), ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Document loadOrCreateComicInfoXml(File file, boolean isCbz, boolean isCb7, boolean isCbr) throws Exception {
|
||||
if (isCbz) {
|
||||
return loadXmlFromZip(file);
|
||||
} else if (isCb7) {
|
||||
return loadXmlFrom7z(file);
|
||||
} else {
|
||||
return loadXmlFromRar(file);
|
||||
}
|
||||
}
|
||||
|
||||
private Document loadXmlFromZip(File file) throws Exception {
|
||||
try (ZipFile zipFile = new ZipFile(file)) {
|
||||
ZipEntry xmlEntry = findComicInfoEntry(zipFile);
|
||||
if (xmlEntry != null) {
|
||||
try (InputStream stream = zipFile.getInputStream(xmlEntry)) {
|
||||
return parseXmlSecurely(stream);
|
||||
}
|
||||
}
|
||||
return createEmptyComicInfoXml();
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up temporary directory if it was created
|
||||
if (tempDir != null) {
|
||||
deleteDirectoryRecursively(tempDir);
|
||||
private Document loadXmlFrom7z(File file) throws Exception {
|
||||
try (SevenZFile archive = SevenZFile.builder().setFile(file).get()) {
|
||||
SevenZArchiveEntry xmlEntry = findComicInfoIn7z(archive);
|
||||
if (xmlEntry != null) {
|
||||
try (InputStream stream = archive.getInputStream(xmlEntry)) {
|
||||
return parseXmlSecurely(stream);
|
||||
}
|
||||
}
|
||||
return createEmptyComicInfoXml();
|
||||
}
|
||||
}
|
||||
|
||||
private SevenZArchiveEntry findComicInfoIn7z(SevenZFile archive) {
|
||||
for (SevenZArchiveEntry entry : archive.getEntries()) {
|
||||
if (entry != null && !entry.isDirectory() && isComicInfoXml(entry.getName())) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Document loadXmlFromRar(File file) throws Exception {
|
||||
try (Archive archive = new Archive(file)) {
|
||||
FileHeader xmlHeader = findComicInfoInRar(archive);
|
||||
if (xmlHeader != null) {
|
||||
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
|
||||
extractRarEntry(archive, xmlHeader, buffer);
|
||||
try (InputStream stream = new ByteArrayInputStream(buffer.toByteArray())) {
|
||||
return parseXmlSecurely(stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
return createEmptyComicInfoXml();
|
||||
}
|
||||
}
|
||||
|
||||
private void applyMetadataChanges(Document xmlDoc, BookMetadataEntity metadata, MetadataClearFlags clearFlags) {
|
||||
Element rootElement = xmlDoc.getDocumentElement();
|
||||
MetadataCopyHelper helper = new MetadataCopyHelper(metadata);
|
||||
|
||||
helper.copyTitle(clearFlags != null && clearFlags.isTitle(), val -> updateXmlElement(xmlDoc, rootElement, "Title", val));
|
||||
helper.copyDescription(clearFlags != null && clearFlags.isDescription(), val -> {
|
||||
updateXmlElement(xmlDoc, rootElement, "Summary", val);
|
||||
removeXmlElement(rootElement, "Description");
|
||||
});
|
||||
helper.copyPublisher(clearFlags != null && clearFlags.isPublisher(), val -> updateXmlElement(xmlDoc, rootElement, "Publisher", val));
|
||||
helper.copySeriesName(clearFlags != null && clearFlags.isSeriesName(), val -> updateXmlElement(xmlDoc, rootElement, "Series", val));
|
||||
helper.copySeriesNumber(clearFlags != null && clearFlags.isSeriesNumber(), val -> updateXmlElement(xmlDoc, rootElement, "Number", formatFloatValue(val)));
|
||||
helper.copySeriesTotal(clearFlags != null && clearFlags.isSeriesTotal(), val -> updateXmlElement(xmlDoc, rootElement, "Count", val != null ? val.toString() : null));
|
||||
helper.copyPublishedDate(clearFlags != null && clearFlags.isPublishedDate(), date -> updateDateElements(xmlDoc, rootElement, date));
|
||||
helper.copyPageCount(clearFlags != null && clearFlags.isPageCount(), val -> updateXmlElement(xmlDoc, rootElement, "PageCount", val != null ? val.toString() : null));
|
||||
helper.copyLanguage(clearFlags != null && clearFlags.isLanguage(), val -> updateXmlElement(xmlDoc, rootElement, "LanguageISO", val));
|
||||
helper.copyAuthors(clearFlags != null && clearFlags.isAuthors(), set -> {
|
||||
updateXmlElement(xmlDoc, rootElement, "Writer", joinStrings(set));
|
||||
removeXmlElement(rootElement, "Penciller");
|
||||
removeXmlElement(rootElement, "Inker");
|
||||
removeXmlElement(rootElement, "Colorist");
|
||||
removeXmlElement(rootElement, "Letterer");
|
||||
removeXmlElement(rootElement, "CoverArtist");
|
||||
});
|
||||
helper.copyCategories(clearFlags != null && clearFlags.isCategories(), set -> {
|
||||
updateXmlElement(xmlDoc, rootElement, "Genre", joinStrings(set));
|
||||
removeXmlElement(rootElement, "Tags");
|
||||
});
|
||||
}
|
||||
|
||||
private byte[] convertDocumentToBytes(Document xmlDoc) throws Exception {
|
||||
Transformer transformer = TransformerFactory.newInstance().newTransformer();
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
transformer.transform(new DOMSource(xmlDoc), new StreamResult(outputStream));
|
||||
return outputStream.toByteArray();
|
||||
}
|
||||
|
||||
private Path updateZipArchive(File originalFile, byte[] xmlContent) throws Exception {
|
||||
Path tempArchive = Files.createTempFile("cbx_edit", ".cbz");
|
||||
rebuildZipWithNewXml(originalFile.toPath(), tempArchive, xmlContent);
|
||||
replaceFileAtomic(tempArchive, originalFile.toPath());
|
||||
return null; // temp file already moved
|
||||
}
|
||||
|
||||
private Path convert7zToZip(File original7z, byte[] xmlContent) throws Exception {
|
||||
Path tempZip = Files.createTempFile("cbx_edit", ".cbz");
|
||||
repack7zToZipWithXml(original7z, tempZip, xmlContent);
|
||||
|
||||
Path targetPath = original7z.toPath().resolveSibling(removeFileExtension(original7z.getName()) + ".cbz");
|
||||
replaceFileAtomic(tempZip, targetPath);
|
||||
|
||||
try {
|
||||
Files.deleteIfExists(original7z.toPath());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void repack7zToZipWithXml(File source7z, Path targetZip, byte[] xmlContent) throws Exception {
|
||||
try (SevenZFile archive = SevenZFile.builder().setFile(source7z).get();
|
||||
ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(targetZip))) {
|
||||
|
||||
for (SevenZArchiveEntry entry : archive.getEntries()) {
|
||||
if (entry.isDirectory()) continue;
|
||||
String entryName = entry.getName();
|
||||
if (isComicInfoXml(entryName)) continue;
|
||||
if (!isPathSafe(entryName)) {
|
||||
log.warn("Skipping unsafe 7z entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
|
||||
zipOutput.putNextEntry(new ZipEntry(entryName));
|
||||
try (InputStream entryStream = archive.getInputStream(entry)) {
|
||||
if (entryStream != null) copyStream(entryStream, zipOutput);
|
||||
}
|
||||
zipOutput.closeEntry();
|
||||
}
|
||||
|
||||
// Clean up backup file if write succeeded
|
||||
if (writeSucceeded && backup != null) {
|
||||
try {
|
||||
Files.deleteIfExists(backup);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to delete backup file: {}", backup, e);
|
||||
zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml"));
|
||||
zipOutput.write(xmlContent);
|
||||
zipOutput.closeEntry();
|
||||
}
|
||||
}
|
||||
|
||||
private Path updateRarArchive(File originalRar, byte[] xmlContent, Path extractDir) throws Exception {
|
||||
String rarCommand = System.getenv().getOrDefault("BOOKLORE_RAR_BIN", "rar");
|
||||
boolean rarAvailable = checkRarAvailability(rarCommand);
|
||||
|
||||
if (rarAvailable) {
|
||||
return updateRarWithCommand(originalRar, xmlContent, rarCommand, extractDir);
|
||||
} else {
|
||||
log.warn("`rar` binary not found. Falling back to CBZ conversion for {}", originalRar.getName());
|
||||
return convertRarToZipArchive(originalRar, xmlContent);
|
||||
}
|
||||
}
|
||||
|
||||
private Path updateRarWithCommand(File originalRar, byte[] xmlContent, String rarCommand, Path extractDir) throws Exception {
|
||||
extractDir = Files.createTempDirectory("cbx_rar_");
|
||||
extractRarContents(originalRar, extractDir);
|
||||
|
||||
Path xmlPath = extractDir.resolve("ComicInfo.xml");
|
||||
Files.write(xmlPath, xmlContent);
|
||||
|
||||
Path targetRar = originalRar.toPath().toAbsolutePath().normalize();
|
||||
String safeCommand = isExecutableSafe(rarCommand) ? rarCommand : "rar";
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(safeCommand, "a", "-idq", "-ep1", "-ma5", targetRar.toString(), ".");
|
||||
processBuilder.directory(extractDir.toFile());
|
||||
Process process = processBuilder.start();
|
||||
int exitCode = process.waitFor();
|
||||
|
||||
if (exitCode == 0) {
|
||||
return null;
|
||||
} else {
|
||||
log.warn("RAR creation failed with exit code {}. Falling back to CBZ conversion for {}", exitCode, originalRar.getName());
|
||||
return convertRarToZipArchive(originalRar, xmlContent);
|
||||
}
|
||||
}
|
||||
|
||||
private void extractRarContents(File rarFile, Path targetDir) throws Exception {
|
||||
try (Archive archive = new Archive(rarFile)) {
|
||||
for (FileHeader header : archive.getFileHeaders()) {
|
||||
String entryName = header.getFileName();
|
||||
if (entryName == null || entryName.isBlank()) continue;
|
||||
if (!isPathSafe(entryName)) {
|
||||
log.warn("Skipping unsafe RAR entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
|
||||
Path outputPath = targetDir.resolve(entryName).normalize();
|
||||
if (!outputPath.startsWith(targetDir)) {
|
||||
log.warn("Skipping traversal entry outside tempDir: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (header.isDirectory()) {
|
||||
Files.createDirectories(outputPath);
|
||||
} else {
|
||||
Files.createDirectories(outputPath.getParent());
|
||||
try (OutputStream fileOutput = Files.newOutputStream(outputPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
|
||||
extractRarEntry(archive, header, fileOutput);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------- helpers -----------------------
|
||||
private Path convertRarToZipArchive(File rarFile, byte[] xmlContent) throws Exception {
|
||||
Path tempZip = Files.createTempFile("cbx_edit", ".cbz");
|
||||
|
||||
try (Archive rarArchive = new Archive(rarFile);
|
||||
ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(tempZip))) {
|
||||
|
||||
for (FileHeader header : rarArchive.getFileHeaders()) {
|
||||
if (header.isDirectory()) continue;
|
||||
String entryName = header.getFileName();
|
||||
if (isComicInfoXml(entryName)) continue;
|
||||
if (!isPathSafe(entryName)) {
|
||||
log.warn("Skipping unsafe RAR entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
|
||||
zipOutput.putNextEntry(new ZipEntry(entryName));
|
||||
extractRarEntry(rarArchive, header, zipOutput);
|
||||
zipOutput.closeEntry();
|
||||
}
|
||||
|
||||
zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml"));
|
||||
zipOutput.write(xmlContent);
|
||||
zipOutput.closeEntry();
|
||||
}
|
||||
|
||||
Path targetPath = rarFile.toPath().resolveSibling(removeFileExtension(rarFile.getName()) + ".cbz");
|
||||
replaceFileAtomic(tempZip, targetPath);
|
||||
|
||||
try {
|
||||
Files.deleteIfExists(rarFile.toPath());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void restoreOriginalFile(Path backupPath, File targetFile) {
|
||||
try {
|
||||
if (backupPath != null) {
|
||||
Files.copy(backupPath, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
log.info("Restored original file from backup after failure: {}", targetFile.getAbsolutePath());
|
||||
}
|
||||
} catch (Exception restoreException) {
|
||||
log.warn("Failed to restore original file from backup: {} -> {}", backupPath, targetFile.getAbsolutePath(), restoreException);
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupTempFiles(Path tempArchive, Path extractDir, Path backupPath, boolean writeSucceeded) {
|
||||
if (tempArchive != null) {
|
||||
try {
|
||||
Files.deleteIfExists(tempArchive);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to delete temp file: {}", tempArchive, e);
|
||||
}
|
||||
}
|
||||
|
||||
if (extractDir != null) {
|
||||
deleteDirectoryRecursively(extractDir);
|
||||
}
|
||||
|
||||
if (writeSucceeded && backupPath != null) {
|
||||
try {
|
||||
Files.deleteIfExists(backupPath);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to delete backup file: {}", backupPath, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ZipEntry findComicInfoEntry(ZipFile zipFile) {
|
||||
Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
String n = entry.getName();
|
||||
if (isComicInfoName(n)) return entry;
|
||||
String entryName = entry.getName();
|
||||
if (isComicInfoXml(entryName)) return entry;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private FileHeader findComicInfoHeader(Archive archive) {
|
||||
for (FileHeader fh : archive.getFileHeaders()) {
|
||||
String name = fh.getFileName();
|
||||
if (name != null && isComicInfoName(name)) return fh;
|
||||
private FileHeader findComicInfoInRar(Archive archive) {
|
||||
for (FileHeader header : archive.getFileHeaders()) {
|
||||
String entryName = header.getFileName();
|
||||
if (entryName != null && isComicInfoXml(entryName)) return header;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Document buildSecureDocument(InputStream is) throws Exception {
|
||||
private Document parseXmlSecurely(InputStream xmlStream) throws Exception {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
factory.setExpandEntityReferences(false);
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
return builder.parse(is);
|
||||
return builder.parse(xmlStream);
|
||||
}
|
||||
|
||||
private Document newEmptyComicInfo() throws Exception {
|
||||
private Document createEmptyComicInfoXml() throws Exception {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
Document doc = builder.newDocument();
|
||||
doc.appendChild(doc.createElement("ComicInfo"));
|
||||
return doc;
|
||||
Document xmlDoc = builder.newDocument();
|
||||
xmlDoc.appendChild(xmlDoc.createElement("ComicInfo"));
|
||||
return xmlDoc;
|
||||
}
|
||||
|
||||
private void setElement(Document doc, Element root, String tag, String value) {
|
||||
removeElement(root, tag);
|
||||
private void updateXmlElement(Document xmlDoc, Element rootElement, String tagName, String value) {
|
||||
removeXmlElement(rootElement, tagName);
|
||||
if (value != null && !value.isBlank()) {
|
||||
Element el = doc.createElement(tag);
|
||||
el.setTextContent(value);
|
||||
root.appendChild(el);
|
||||
Element element = xmlDoc.createElement(tagName);
|
||||
element.setTextContent(value);
|
||||
rootElement.appendChild(element);
|
||||
}
|
||||
}
|
||||
|
||||
private void removeElement(Element root, String tag) {
|
||||
NodeList nodes = root.getElementsByTagName(tag);
|
||||
private void removeXmlElement(Element rootElement, String tagName) {
|
||||
NodeList nodes = rootElement.getElementsByTagName(tagName);
|
||||
for (int i = nodes.getLength() - 1; i >= 0; i--) {
|
||||
root.removeChild(nodes.item(i));
|
||||
rootElement.removeChild(nodes.item(i));
|
||||
}
|
||||
}
|
||||
|
||||
private void setDateElements(Document doc, Element root, LocalDate date) {
|
||||
private void updateDateElements(Document xmlDoc, Element rootElement, LocalDate date) {
|
||||
if (date == null) {
|
||||
removeElement(root, "Year");
|
||||
removeElement(root, "Month");
|
||||
removeElement(root, "Day");
|
||||
removeXmlElement(rootElement, "Year");
|
||||
removeXmlElement(rootElement, "Month");
|
||||
removeXmlElement(rootElement, "Day");
|
||||
return;
|
||||
}
|
||||
setElement(doc, root, "Year", Integer.toString(date.getYear()));
|
||||
setElement(doc, root, "Month", Integer.toString(date.getMonthValue()));
|
||||
setElement(doc, root, "Day", Integer.toString(date.getDayOfMonth()));
|
||||
updateXmlElement(xmlDoc, rootElement, "Year", Integer.toString(date.getYear()));
|
||||
updateXmlElement(xmlDoc, rootElement, "Month", Integer.toString(date.getMonthValue()));
|
||||
updateXmlElement(xmlDoc, rootElement, "Day", Integer.toString(date.getDayOfMonth()));
|
||||
}
|
||||
|
||||
private String join(Set<String> set) {
|
||||
return (set == null || set.isEmpty()) ? null : String.join(", ", set);
|
||||
private String joinStrings(Set<String> values) {
|
||||
return (values == null || values.isEmpty()) ? null : String.join(", ", values);
|
||||
}
|
||||
|
||||
private String formatFloat(Float val) {
|
||||
if (val == null) return null;
|
||||
if (val % 1 == 0) return Integer.toString(val.intValue());
|
||||
return val.toString();
|
||||
private String formatFloatValue(Float value) {
|
||||
if (value == null) return null;
|
||||
if (value % 1 == 0) return Integer.toString(value.intValue());
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
private static boolean isComicInfoName(String name) {
|
||||
if (name == null) return false;
|
||||
String n = name.replace('\\', '/');
|
||||
if (n.endsWith("/")) return false;
|
||||
String lower = n.toLowerCase(Locale.ROOT);
|
||||
return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml");
|
||||
private static boolean isComicInfoXml(String entryName) {
|
||||
if (entryName == null) return false;
|
||||
String normalized = entryName.replace('\\', '/');
|
||||
if (normalized.endsWith("/")) return false;
|
||||
String lowerCase = normalized.toLowerCase(Locale.ROOT);
|
||||
return "comicinfo.xml".equals(lowerCase) || lowerCase.endsWith("/comicinfo.xml");
|
||||
}
|
||||
|
||||
private static boolean isSafeEntryName(String name) {
|
||||
if (name == null || name.isBlank()) return false;
|
||||
String n = name.replace('\\', '/');
|
||||
if (n.startsWith("/")) return false; // absolute
|
||||
if (n.contains("../")) return false; // traversal
|
||||
if (n.contains("\0")) return false; // NUL
|
||||
private static boolean isPathSafe(String entryName) {
|
||||
if (entryName == null || entryName.isBlank()) return false;
|
||||
String normalized = entryName.replace('\\', '/');
|
||||
if (normalized.startsWith("/")) return false;
|
||||
if (normalized.contains("../")) return false;
|
||||
if (normalized.contains("\0")) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void repackZipReplacingComicInfo(Path sourceZip, Path targetZip, byte[] xmlBytes) throws Exception {
|
||||
private void rebuildZipWithNewXml(Path sourceZip, Path targetZip, byte[] xmlContent) throws Exception {
|
||||
try (ZipFile zipFile = new ZipFile(sourceZip.toFile());
|
||||
ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(targetZip))) {
|
||||
ZipEntry existing = findComicInfoEntry(zipFile);
|
||||
ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(targetZip))) {
|
||||
ZipEntry existingXml = findComicInfoEntry(zipFile);
|
||||
Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
String entryName = entry.getName();
|
||||
if (existing != null && entryName.equals(existing.getName())) {
|
||||
continue; // skip old ComicInfo.xml
|
||||
if (existingXml != null && entryName.equals(existingXml.getName())) {
|
||||
continue;
|
||||
}
|
||||
if (!isSafeEntryName(entryName)) {
|
||||
if (!isPathSafe(entryName)) {
|
||||
log.warn("Skipping unsafe ZIP entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry(entryName));
|
||||
try (InputStream is = zipFile.getInputStream(entry)) {
|
||||
is.transferTo(zos);
|
||||
zipOutput.putNextEntry(new ZipEntry(entryName));
|
||||
try (InputStream entryStream = zipFile.getInputStream(entry)) {
|
||||
copyStream(entryStream, zipOutput);
|
||||
}
|
||||
zos.closeEntry();
|
||||
zipOutput.closeEntry();
|
||||
}
|
||||
String entryName = (existing != null ? existing.getName() : "ComicInfo.xml");
|
||||
zos.putNextEntry(new ZipEntry(entryName));
|
||||
zos.write(xmlBytes);
|
||||
zos.closeEntry();
|
||||
String xmlEntryName = (existingXml != null ? existingXml.getName() : "ComicInfo.xml");
|
||||
zipOutput.putNextEntry(new ZipEntry(xmlEntryName));
|
||||
zipOutput.write(xmlContent);
|
||||
zipOutput.closeEntry();
|
||||
}
|
||||
}
|
||||
|
||||
private static void atomicReplace(Path temp, Path target) throws Exception {
|
||||
private void copyStream(InputStream input, OutputStream output) throws IOException {
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
int bytesRead;
|
||||
while ((bytesRead = input.read(buffer)) != -1) {
|
||||
output.write(buffer, 0, bytesRead);
|
||||
}
|
||||
}
|
||||
|
||||
private void extractRarEntry(Archive archive, FileHeader fileHeader, OutputStream output) throws Exception {
|
||||
try (InputStream entryStream = archive.getInputStream(fileHeader)) {
|
||||
copyStream(entryStream, output);
|
||||
}
|
||||
}
|
||||
|
||||
private static void replaceFileAtomic(Path source, Path target) throws Exception {
|
||||
try {
|
||||
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (Exception e) {
|
||||
// Fallback if filesystem doesn't support ATOMIC_MOVE
|
||||
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isRarAvailable(String rarBin) {
|
||||
private boolean checkRarAvailability(String rarCommand) {
|
||||
try {
|
||||
String exec = isSafeExecutable(rarBin) ? rarBin : "rar";
|
||||
Process check = new ProcessBuilder(exec, "--help").redirectErrorStream(true).start();
|
||||
String safeCommand = isExecutableSafe(rarCommand) ? rarCommand : "rar";
|
||||
Process check = new ProcessBuilder(safeCommand, "--help").redirectErrorStream(true).start();
|
||||
int exitCode = check.waitFor();
|
||||
return (exitCode == 0);
|
||||
} catch (Exception ex) {
|
||||
@@ -454,19 +552,14 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the provided executable reference is a simple name or sanitized absolute/relative path.
|
||||
* No spaces or shell meta chars; passed as argv to ProcessBuilder (no shell).
|
||||
*/
|
||||
private boolean isSafeExecutable(String exec) {
|
||||
if (exec == null || exec.isBlank()) return false;
|
||||
// allow word chars, dot, slash, backslash, dash and underscore (no spaces or shell metas)
|
||||
return VALID_FILENAME_PATTERN.matcher(exec).matches();
|
||||
private boolean isExecutableSafe(String command) {
|
||||
if (command == null || command.isBlank()) return false;
|
||||
return VALID_FILENAME_PATTERN.matcher(command).matches();
|
||||
}
|
||||
|
||||
private static String stripExtension(String filename) {
|
||||
int i = filename.lastIndexOf('.');
|
||||
if (i > 0) return filename.substring(0, i);
|
||||
private static String removeFileExtension(String filename) {
|
||||
int lastDot = filename.lastIndexOf('.');
|
||||
if (lastDot > 0) return filename.substring(0, lastDot);
|
||||
return filename;
|
||||
}
|
||||
|
||||
@@ -475,8 +568,8 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
return BookFileType.CBX;
|
||||
}
|
||||
|
||||
private void deleteDirectoryRecursively(Path dir) {
|
||||
try (var pathStream = Files.walk(dir)) {
|
||||
private void deleteDirectoryRecursively(Path directory) {
|
||||
try (var pathStream = Files.walk(directory)) {
|
||||
pathStream
|
||||
.sorted(Comparator.reverseOrder())
|
||||
.forEach(path -> {
|
||||
@@ -487,7 +580,7 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to clean up temporary directory: {}", dir, e);
|
||||
log.warn("Failed to clean up temporary directory: {}", directory, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+71
-56
@@ -1,9 +1,12 @@
|
||||
package com.adityachandel.booklore.service.metadata.writer;
|
||||
|
||||
import com.adityachandel.booklore.model.MetadataClearFlags;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
import net.lingala.zip4j.model.ZipParameters;
|
||||
@@ -41,12 +44,18 @@ import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class EpubMetadataWriter implements MetadataWriter {
|
||||
|
||||
private static final String OPF_NS = "http://www.idpf.org/2007/opf";
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
@Override
|
||||
public void writeMetadataToFile(File epubFile, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clear) {
|
||||
public void saveMetadataToFile(File epubFile, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clear) {
|
||||
if (!shouldSaveMetadataToFile(epubFile)) {
|
||||
return;
|
||||
}
|
||||
|
||||
File backupFile = new File(epubFile.getParentFile(), epubFile.getName() + ".bak");
|
||||
try {
|
||||
Files.copy(epubFile.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
@@ -237,68 +246,61 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
return changed;
|
||||
}
|
||||
|
||||
|
||||
public void replaceCoverImageFromBytes(BookEntity bookEntity, byte[] file) {
|
||||
if (!shouldSaveMetadataToFile(bookEntity.getFullFilePath().toFile())) {
|
||||
return;
|
||||
}
|
||||
if (file == null || file.length == 0) {
|
||||
log.warn("Cover update failed: empty or null byte array.");
|
||||
return;
|
||||
}
|
||||
|
||||
replaceCoverImageInternal(bookEntity, file, "byte array");
|
||||
}
|
||||
|
||||
public void replaceCoverImageFromUpload(BookEntity bookEntity, MultipartFile multipartFile) {
|
||||
if (!shouldSaveMetadataToFile(bookEntity.getFullFilePath().toFile())) {
|
||||
return;
|
||||
}
|
||||
if (multipartFile == null || multipartFile.isEmpty()) {
|
||||
log.warn("Cover upload failed: empty or null file.");
|
||||
return;
|
||||
}
|
||||
|
||||
Path tempDir = null;
|
||||
try {
|
||||
File epubFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
tempDir = Files.createTempDirectory("epub_cover_" + UUID.randomUUID());
|
||||
try (ZipFile zipFile = new ZipFile(epubFile)) {
|
||||
zipFile.extractAll(tempDir.toString());
|
||||
}
|
||||
|
||||
File opfFile = findOpfFile(tempDir.toFile());
|
||||
if (opfFile == null) {
|
||||
log.warn("OPF file not found in EPUB: {}", epubFile.getName());
|
||||
return;
|
||||
}
|
||||
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
dbf.setNamespaceAware(true);
|
||||
DocumentBuilder builder = dbf.newDocumentBuilder();
|
||||
Document opfDoc = builder.parse(opfFile);
|
||||
|
||||
byte[] coverData = multipartFile.getBytes();
|
||||
applyCoverImageToEpub(tempDir, opfDoc, coverData);
|
||||
|
||||
Transformer transformer = TransformerFactory.newInstance().newTransformer();
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||
transformer.transform(new DOMSource(opfDoc), new StreamResult(opfFile));
|
||||
|
||||
File tempEpub = new File(epubFile.getParentFile(), epubFile.getName() + ".tmp");
|
||||
try (ZipFile tempZipFile = new ZipFile(tempEpub)) {
|
||||
addFolderContentsToZip(tempZipFile, tempDir.toFile(), tempDir.toFile());
|
||||
}
|
||||
|
||||
if (!epubFile.delete()) throw new IOException("Could not delete original EPUB");
|
||||
if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB");
|
||||
|
||||
log.info("Cover image updated in EPUB: {}", epubFile.getName());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to update EPUB with uploaded cover image: {}", e.getMessage(), e);
|
||||
} finally {
|
||||
if (tempDir != null) {
|
||||
deleteDirectoryRecursively(tempDir);
|
||||
}
|
||||
replaceCoverImageInternal(bookEntity, coverData, "upload");
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to read uploaded cover image: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replaceCoverImageFromUrl(BookEntity bookEntity, String url) {
|
||||
if (!shouldSaveMetadataToFile(bookEntity.getFullFilePath().toFile())) {
|
||||
return;
|
||||
}
|
||||
if (url == null || url.isBlank()) {
|
||||
log.warn("Cover update via URL failed: empty or null URL.");
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] coverData = loadImage(url);
|
||||
if (coverData == null) {
|
||||
log.warn("Failed to load image from URL: {}", url);
|
||||
return;
|
||||
}
|
||||
|
||||
replaceCoverImageInternal(bookEntity, coverData, "URL");
|
||||
}
|
||||
|
||||
private void replaceCoverImageInternal(BookEntity bookEntity, byte[] coverData, String source) {
|
||||
Path tempDir = null;
|
||||
try {
|
||||
File epubFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
tempDir = Files.createTempDirectory("epub_cover_url_" + UUID.randomUUID());
|
||||
tempDir = Files.createTempDirectory("epub_cover_" + UUID.randomUUID());
|
||||
|
||||
try (ZipFile zipFile = new ZipFile(epubFile)) {
|
||||
zipFile.extractAll(tempDir.toString());
|
||||
}
|
||||
@@ -314,12 +316,6 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
DocumentBuilder builder = dbf.newDocumentBuilder();
|
||||
Document opfDoc = builder.parse(opfFile);
|
||||
|
||||
byte[] coverData = loadImage(url);
|
||||
if (coverData == null) {
|
||||
log.warn("Failed to load image from URL: {}", url);
|
||||
return;
|
||||
}
|
||||
|
||||
applyCoverImageToEpub(tempDir, opfDoc, coverData);
|
||||
|
||||
Transformer transformer = TransformerFactory.newInstance().newTransformer();
|
||||
@@ -335,9 +331,10 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
if (!epubFile.delete()) throw new IOException("Could not delete original EPUB");
|
||||
if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB");
|
||||
|
||||
log.info("Cover image updated in EPUB via URL: {}", epubFile.getName());
|
||||
log.info("Cover image updated in EPUB from {}: {}", source, epubFile.getName());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to update EPUB with cover from URL: {}", e.getMessage(), e);
|
||||
log.warn("Failed to update EPUB cover image from {}: {}", source, e.getMessage(), e);
|
||||
} finally {
|
||||
if (tempDir != null) {
|
||||
deleteDirectoryRecursively(tempDir);
|
||||
@@ -543,13 +540,13 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
if (StringUtils.isNotBlank(id) && StringUtils.isBlank(creatorRole)) {
|
||||
// Finds any matching role meta tags for this creator ID
|
||||
Element meta = getMetaElementByFilter(metadataElement, el -> ("role".equals(el.getAttribute("property")) && "#".concat(id).equals(el.getAttribute("refines"))));
|
||||
if ( meta != null ) {
|
||||
creatorRole = meta.hasAttribute("content") ? meta.getAttribute("content").trim() : meta.getTextContent().trim();
|
||||
if (meta != null) {
|
||||
creatorRole = meta.hasAttribute("content") ? meta.getAttribute("content").trim() : meta.getTextContent().trim();
|
||||
}
|
||||
}
|
||||
if (role.equalsIgnoreCase(creatorRole)) {
|
||||
metadataElement.removeChild(creatorElement);
|
||||
if (StringUtils.isNotBlank(id)){
|
||||
if (StringUtils.isNotBlank(id)) {
|
||||
removeMetaByRefines(metadataElement, "#".concat(id));
|
||||
}
|
||||
}
|
||||
@@ -588,9 +585,9 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
}
|
||||
|
||||
private String getMetaContentByName(Element metadataElement, String name) {
|
||||
Element meta = getMetaElementByFilter( metadataElement, el -> name.equals(el.getAttribute("name")) );
|
||||
Element meta = getMetaElementByFilter(metadataElement, el -> name.equals(el.getAttribute("name")));
|
||||
if (meta != null) {
|
||||
return meta.getAttribute("content");
|
||||
return meta.getAttribute("content");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -610,4 +607,22 @@ public class EpubMetadataWriter implements MetadataWriter {
|
||||
log.warn("Failed to clean up temporary directory: {}", dir, e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean shouldSaveMetadataToFile(File epubFile) {
|
||||
MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings().getMetadataPersistenceSettings().getSaveToOriginalFile();
|
||||
|
||||
MetadataPersistenceSettings.FormatSettings epubSettings = settings.getEpub();
|
||||
if (epubSettings == null || !epubSettings.isEnabled()) {
|
||||
log.debug("EPUB metadata writing is disabled. Skipping: {}", epubFile.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
long fileSizeInMb = epubFile.length() / (1024 * 1024);
|
||||
if (fileSizeInMb > epubSettings.getMaxFileSizeInMb()) {
|
||||
log.info("EPUB file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", epubFile.getName(), fileSizeInMb, epubSettings.getMaxFileSizeInMb());
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
+6
-1
@@ -10,11 +10,16 @@ import java.io.File;
|
||||
|
||||
public interface MetadataWriter {
|
||||
|
||||
void writeMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags);
|
||||
void saveMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags);
|
||||
|
||||
boolean shouldSaveMetadataToFile(File file);
|
||||
|
||||
default void replaceCoverImageFromUpload(BookEntity bookEntity, MultipartFile file) {
|
||||
}
|
||||
|
||||
default void replaceCoverImageFromBytes(BookEntity bookEntity, byte[] file) {
|
||||
}
|
||||
|
||||
default void replaceCoverImageFromUrl(BookEntity bookEntity, String url) {
|
||||
}
|
||||
|
||||
|
||||
+30
-2
@@ -3,6 +3,9 @@ package com.adityachandel.booklore.service.metadata.writer;
|
||||
import com.adityachandel.booklore.model.MetadataClearFlags;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.pdfbox.Loader;
|
||||
@@ -41,10 +44,17 @@ import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PdfMetadataWriter implements MetadataWriter {
|
||||
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
@Override
|
||||
public void writeMetadataToFile(File file, BookMetadataEntity metadataEntity, String thumbnailUrl, MetadataClearFlags clear) {
|
||||
public void saveMetadataToFile(File file, BookMetadataEntity metadataEntity, String thumbnailUrl, MetadataClearFlags clear) {
|
||||
if (!shouldSaveMetadataToFile(file)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!file.exists() || !file.getName().toLowerCase().endsWith(".pdf")) {
|
||||
log.warn("Invalid PDF file: {}", file.getAbsolutePath());
|
||||
return;
|
||||
@@ -102,6 +112,24 @@ public class PdfMetadataWriter implements MetadataWriter {
|
||||
return BookFileType.PDF;
|
||||
}
|
||||
|
||||
public boolean shouldSaveMetadataToFile(File pdfFile) {
|
||||
MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings().getMetadataPersistenceSettings().getSaveToOriginalFile();
|
||||
|
||||
MetadataPersistenceSettings.FormatSettings pdfSettings = settings.getPdf();
|
||||
if (pdfSettings == null || !pdfSettings.isEnabled()) {
|
||||
log.debug("PDF metadata writing is disabled. Skipping: {}", pdfFile.getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
long fileSizeInMb = pdfFile.length() / (1024 * 1024);
|
||||
if (fileSizeInMb > pdfSettings.getMaxFileSizeInMb()) {
|
||||
log.info("PDF file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", pdfFile.getName(), fileSizeInMb, pdfSettings.getMaxFileSizeInMb());
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void applyMetadataToDocument(PDDocument pdf, BookMetadataEntity entity, MetadataClearFlags clear) {
|
||||
PDDocumentInformation info = pdf.getDocumentInformation();
|
||||
MetadataCopyHelper helper = new MetadataCopyHelper(entity);
|
||||
@@ -122,7 +150,7 @@ public class PdfMetadataWriter implements MetadataWriter {
|
||||
helper.copyPublishedDate(clear != null && clear.isPublishedDate(), date -> {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTimeInMillis((date != null ? date : ZonedDateTime.now().toLocalDate())
|
||||
.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli());
|
||||
.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli());
|
||||
dc.addDate(cal);
|
||||
});
|
||||
|
||||
|
||||
+13
-6
@@ -40,7 +40,7 @@ public class CbxReaderService {
|
||||
private static final String CBZ_EXTENSION = ".cbz";
|
||||
private static final String CBR_EXTENSION = ".cbr";
|
||||
private static final String CB7_EXTENSION = ".cb7";
|
||||
private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"};
|
||||
private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".avif", ".heic"};
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
@@ -57,7 +57,14 @@ public class CbxReaderService {
|
||||
try {
|
||||
long maxCacheSizeBytes = mbToBytes(appSettingService.getAppSettings().getCbxCacheSizeInMb());
|
||||
long estimatedSize = estimateArchiveSize(cbzPath);
|
||||
if (estimatedSize > maxCacheSizeBytes) {
|
||||
|
||||
if (estimatedSize == -1) {
|
||||
long fileSize = Files.size(cbzPath);
|
||||
if (fileSize > maxCacheSizeBytes) {
|
||||
log.warn("Cache skipped: Physical file size {} exceeds max cache size {} (Estimation failed)", fileSize, maxCacheSizeBytes);
|
||||
throw ApiError.CACHE_TOO_LARGE.createException();
|
||||
}
|
||||
} else if (estimatedSize > maxCacheSizeBytes) {
|
||||
log.warn("Cache skipped: Estimated archive size {} exceeds max cache size {}", estimatedSize, maxCacheSizeBytes);
|
||||
throw ApiError.CACHE_TOO_LARGE.createException();
|
||||
}
|
||||
@@ -78,7 +85,7 @@ public class CbxReaderService {
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to cache CBZ for book {}", bookId, e);
|
||||
return List.of();
|
||||
throw ApiError.FILE_READ_ERROR.createException("Failed to read archive: " + e.getMessage());
|
||||
}
|
||||
|
||||
try (var stream = Files.list(cacheDir)) {
|
||||
@@ -360,7 +367,7 @@ public class CbxReaderService {
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to estimate archive size for {}", cbxPath, e);
|
||||
}
|
||||
return Long.MAX_VALUE;
|
||||
return -1;
|
||||
}
|
||||
|
||||
private long estimateCbzArchiveSize(Path cbxPath) throws IOException {
|
||||
@@ -384,7 +391,7 @@ public class CbxReaderService {
|
||||
}
|
||||
|
||||
log.warn("Unable to estimate archive size for {} with any supported encoding", cbxPath);
|
||||
return Long.MAX_VALUE;
|
||||
return -1;
|
||||
}
|
||||
|
||||
private long estimateCbzWithEncoding(Path cbxPath, Charset charset, boolean useFastPath) throws IOException {
|
||||
@@ -405,7 +412,7 @@ public class CbxReaderService {
|
||||
total += (size >= 0) ? size : entry.getCompressedSize();
|
||||
}
|
||||
}
|
||||
return total > 0 ? total : Long.MAX_VALUE;
|
||||
return total > 0 ? total : -1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
@@ -64,6 +64,7 @@ public class UserProvisioningService {
|
||||
perms.setPermissionAccessTaskManager(true);
|
||||
perms.setPermissionManageGlobalPreferences(true);
|
||||
perms.setPermissionManageIcons(true);
|
||||
perms.setPermissionManageFonts(true);
|
||||
perms.setPermissionBulkAutoFetchMetadata(true);
|
||||
perms.setPermissionBulkCustomFetchMetadata(true);
|
||||
perms.setPermissionBulkEditMetadata(true);
|
||||
@@ -112,6 +113,7 @@ public class UserProvisioningService {
|
||||
permissions.setPermissionAccessTaskManager(request.isPermissionAccessTaskManager());
|
||||
permissions.setPermissionManageGlobalPreferences(request.isPermissionManageGlobalPreferences());
|
||||
permissions.setPermissionManageIcons(request.isPermissionManageIcons());
|
||||
permissions.setPermissionManageFonts(request.isPermissionManageFonts());
|
||||
permissions.setPermissionBulkAutoFetchMetadata(request.isPermissionBulkAutoFetchMetadata());
|
||||
permissions.setPermissionBulkCustomFetchMetadata(request.isPermissionBulkCustomFetchMetadata());
|
||||
permissions.setPermissionBulkEditMetadata(request.isPermissionBulkEditMetadata());
|
||||
@@ -160,6 +162,7 @@ public class UserProvisioningService {
|
||||
perms.setPermissionAccessTaskManager(defaultPermissions.contains("permissionAccessTaskManager"));
|
||||
perms.setPermissionManageGlobalPreferences(defaultPermissions.contains("permissionManageGlobalPreferences"));
|
||||
perms.setPermissionManageIcons(defaultPermissions.contains("permissionManageIcons"));
|
||||
perms.setPermissionManageFonts(defaultPermissions.contains("permissionManageFonts"));
|
||||
}
|
||||
user.setPermissions(perms);
|
||||
|
||||
@@ -222,6 +225,7 @@ public class UserProvisioningService {
|
||||
permissions.setPermissionAccessTaskManager(defaultPermissions.contains("permissionAccessTaskManager"));
|
||||
permissions.setPermissionManageGlobalPreferences(defaultPermissions.contains("permissionManageGlobalPreferences"));
|
||||
permissions.setPermissionManageIcons(defaultPermissions.contains("permissionManageIcons"));
|
||||
permissions.setPermissionManageFonts(defaultPermissions.contains("permissionManageFonts"));
|
||||
} else {
|
||||
permissions.setPermissionUpload(false);
|
||||
permissions.setPermissionDownload(false);
|
||||
@@ -239,6 +243,7 @@ public class UserProvisioningService {
|
||||
permissions.setPermissionAccessTaskManager(false);
|
||||
permissions.setPermissionManageGlobalPreferences(false);
|
||||
permissions.setPermissionManageIcons(false);
|
||||
permissions.setPermissionManageFonts(false);
|
||||
}
|
||||
|
||||
permissions.setPermissionAdmin(isAdmin);
|
||||
|
||||
@@ -144,6 +144,28 @@ public class FileService {
|
||||
// IMAGE OPERATIONS
|
||||
// ========================================
|
||||
|
||||
public static BufferedImage readImage(InputStream inputStream) throws IOException {
|
||||
return readImage(inputStream.readAllBytes());
|
||||
}
|
||||
|
||||
public static BufferedImage readImage(byte[] imageData) throws IOException {
|
||||
if (imageData == null || imageData.length == 0) {
|
||||
throw new IOException("Image data is null or empty");
|
||||
}
|
||||
try (InputStream is = new ByteArrayInputStream(imageData)) {
|
||||
BufferedImage image = ImageIO.read(is);
|
||||
if (image != null) {
|
||||
return image;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("ImageIO/TwelveMonkeys decode failed (possibly unsupported format like AVIF/HEIC): {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
|
||||
log.warn("Unable to decode image - likely unsupported format (AVIF, HEIC, or SVG)");
|
||||
return null;
|
||||
}
|
||||
|
||||
public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
|
||||
Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
|
||||
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
@@ -156,9 +178,10 @@ public class FileService {
|
||||
public static void saveImage(byte[] imageData, String filePath) throws IOException {
|
||||
BufferedImage originalImage = null;
|
||||
try {
|
||||
originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
|
||||
originalImage = readImage(imageData);
|
||||
if (originalImage == null) {
|
||||
throw new IOException("Invalid image data: unable to decode image");
|
||||
log.warn("Skipping saveImage for {}: decoded image is null", filePath);
|
||||
return;
|
||||
}
|
||||
File outputFile = new File(filePath);
|
||||
File parentDir = outputFile.getParentFile();
|
||||
@@ -191,13 +214,7 @@ public class FileService {
|
||||
|
||||
// Validate and convert
|
||||
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
|
||||
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(response.getBody())) {
|
||||
BufferedImage image = ImageIO.read(inputStream);
|
||||
if (image == null) {
|
||||
throw new IOException("Downloaded content is not a supported image format.");
|
||||
}
|
||||
return image;
|
||||
}
|
||||
return readImage(response.getBody());
|
||||
} else {
|
||||
throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode());
|
||||
}
|
||||
@@ -216,10 +233,11 @@ public class FileService {
|
||||
validateCoverFile(file);
|
||||
BufferedImage originalImage;
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
originalImage = ImageIO.read(inputStream);
|
||||
originalImage = readImage(inputStream);
|
||||
}
|
||||
if (originalImage == null) {
|
||||
throw ApiError.IMAGE_NOT_FOUND.createException();
|
||||
log.warn("Could not decode image from file, skipping thumbnail creation for book: {}", bookId);
|
||||
return;
|
||||
}
|
||||
boolean success = saveCoverImages(originalImage, bookId);
|
||||
if (!success) {
|
||||
@@ -235,12 +253,10 @@ public class FileService {
|
||||
|
||||
public void createThumbnailFromBytes(long bookId, byte[] imageBytes) {
|
||||
try {
|
||||
BufferedImage originalImage;
|
||||
try (InputStream inputStream = new java.io.ByteArrayInputStream(imageBytes)) {
|
||||
originalImage = ImageIO.read(inputStream);
|
||||
}
|
||||
BufferedImage originalImage = readImage(imageBytes);
|
||||
if (originalImage == null) {
|
||||
throw ApiError.IMAGE_NOT_FOUND.createException();
|
||||
log.warn("Skipping thumbnail creation for book {}: image decode failed", bookId);
|
||||
return;
|
||||
}
|
||||
boolean success = saveCoverImages(originalImage, bookId);
|
||||
if (!success) {
|
||||
@@ -257,11 +273,15 @@ public class FileService {
|
||||
public void createThumbnailFromUrl(long bookId, String imageUrl) {
|
||||
try {
|
||||
BufferedImage originalImage = downloadImageFromUrl(imageUrl);
|
||||
if (originalImage == null) {
|
||||
log.warn("Skipping thumbnail creation for book {}: download/decode failed", bookId);
|
||||
return;
|
||||
}
|
||||
boolean success = saveCoverImages(originalImage, bookId);
|
||||
if (!success) {
|
||||
throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images");
|
||||
}
|
||||
originalImage.flush(); // Release resources after processing
|
||||
originalImage.flush();
|
||||
log.info("Cover images created and saved from URL for book ID: {}", bookId);
|
||||
} catch (Exception e) {
|
||||
log.error("An error occurred while creating thumbnail from URL: {}", e.getMessage(), e);
|
||||
@@ -469,87 +489,6 @@ public class FileService {
|
||||
log.info("Deleted {} book covers", bookIds.size());
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// BACKGROUND OPERATIONS
|
||||
// ========================================
|
||||
|
||||
public void saveBackgroundImage(BufferedImage image, String filename, Long userId) throws IOException {
|
||||
String backgroundsFolder = getBackgroundsFolder(userId);
|
||||
File folder = new File(backgroundsFolder);
|
||||
if (!folder.exists() && !folder.mkdirs()) {
|
||||
throw new IOException("Failed to create backgrounds directory: " + folder.getAbsolutePath());
|
||||
}
|
||||
|
||||
File outputFile = new File(folder, filename);
|
||||
boolean saved = ImageIO.write(image, IMAGE_FORMAT, outputFile);
|
||||
if (!saved) {
|
||||
throw new IOException("Failed to save background image: " + filename);
|
||||
}
|
||||
|
||||
log.info("Background image saved successfully for user {}: {}", userId, filename);
|
||||
// Note: input image is not flushed here - caller is responsible for its lifecycle
|
||||
} public void deleteBackgroundFile(String filename, Long userId) {
|
||||
try {
|
||||
String backgroundsFolder = getBackgroundsFolder(userId);
|
||||
File file = new File(backgroundsFolder, filename);
|
||||
if (file.exists() && file.isFile()) {
|
||||
boolean deleted = file.delete();
|
||||
if (deleted) {
|
||||
if (userId != null) {
|
||||
deleteEmptyUserBackgroundFolder(userId);
|
||||
}
|
||||
} else {
|
||||
log.warn("Failed to delete background file for user {}: {}", userId, filename);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Error deleting background file {} for user {}: {}", filename, userId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteEmptyUserBackgroundFolder(Long userId) {
|
||||
try {
|
||||
String userBackgroundsFolder = getBackgroundsFolder(userId);
|
||||
File folder = new File(userBackgroundsFolder);
|
||||
|
||||
if (folder.exists() && folder.isDirectory()) {
|
||||
File[] files = folder.listFiles();
|
||||
if (files != null && files.length == 0) {
|
||||
boolean deleted = folder.delete();
|
||||
if (deleted) {
|
||||
log.info("Deleted empty background folder for user: {}", userId);
|
||||
} else {
|
||||
log.warn("Failed to delete empty background folder for user: {}", userId);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Error checking/deleting empty background folder for user {}: {}", userId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public Resource getBackgroundResource(Long userId) {
|
||||
String[] possibleFiles = {"1.jpg", "1.jpeg", "1.png"};
|
||||
|
||||
if (userId != null) {
|
||||
String userBackgroundsFolder = getBackgroundsFolder(userId);
|
||||
for (String filename : possibleFiles) {
|
||||
File customFile = new File(userBackgroundsFolder, filename);
|
||||
if (customFile.exists() && customFile.isFile()) {
|
||||
return new FileSystemResource(customFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
String globalBackgroundsFolder = getBackgroundsFolder();
|
||||
for (String filename : possibleFiles) {
|
||||
File customFile = new File(globalBackgroundsFolder, filename);
|
||||
if (customFile.exists() && customFile.isFile()) {
|
||||
return new FileSystemResource(customFile);
|
||||
}
|
||||
}
|
||||
return new ClassPathResource("static/images/background.jpg");
|
||||
}
|
||||
|
||||
public String getIconsSvgFolder() {
|
||||
return Paths.get(appProperties.getPathConfig(), ICONS_DIR, SVG_DIR).toString();
|
||||
}
|
||||
|
||||
@@ -63,13 +63,25 @@ public class FileUtils {
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> systemDirs = Arrays.asList(
|
||||
public String getExtension(String fileName) {
|
||||
if (fileName == null) {
|
||||
return "";
|
||||
}
|
||||
int i = fileName.lastIndexOf('.');
|
||||
if (i >= 0 && i < fileName.length() - 1) {
|
||||
return fileName.substring(i + 1);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
final private List<String> systemDirs = Arrays.asList(
|
||||
// synology
|
||||
"#recycle",
|
||||
"@eaDir",
|
||||
// calibre
|
||||
".caltrash"
|
||||
);
|
||||
|
||||
public boolean shouldIgnore(Path path) {
|
||||
if (!path.getFileName().toString().isEmpty() && path.getFileName().toString().charAt(0) == '.') {
|
||||
return true;
|
||||
|
||||
@@ -26,6 +26,7 @@ public class UserPermissionUtils {
|
||||
case ACCESS_USER_STATS -> perms.isPermissionAccessUserStats();
|
||||
case ACCESS_TASK_MANAGER -> perms.isPermissionAccessTaskManager();
|
||||
case MANAGE_ICONS -> perms.isPermissionManageIcons();
|
||||
case MANAGE_FONTS -> perms.isPermissionManageFonts();
|
||||
case MANAGE_GLOBAL_PREFERENCES -> perms.isPermissionManageGlobalPreferences();
|
||||
case DEMO_USER -> perms.isPermissionDemoUser();
|
||||
};
|
||||
@@ -49,6 +50,7 @@ public class UserPermissionUtils {
|
||||
case ACCESS_USER_STATS -> perms.isCanAccessUserStats();
|
||||
case ACCESS_TASK_MANAGER -> perms.isCanAccessTaskManager();
|
||||
case MANAGE_ICONS -> perms.isCanManageIcons();
|
||||
case MANAGE_FONTS -> perms.isCanManageFonts();
|
||||
case MANAGE_GLOBAL_PREFERENCES -> perms.isCanManageGlobalPreferences();
|
||||
case DEMO_USER -> perms.isDemoUser();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
CREATE TABLE IF NOT EXISTS custom_font (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
font_name VARCHAR(255) NOT NULL,
|
||||
file_name VARCHAR(255) NOT NULL UNIQUE,
|
||||
original_file_name VARCHAR(255) NOT NULL,
|
||||
format VARCHAR(10) NOT NULL,
|
||||
file_size BIGINT NOT NULL,
|
||||
uploaded_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
INDEX idx_user_id (user_id)
|
||||
);
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE epub_viewer_preference ADD COLUMN IF NOT EXISTS custom_font_id BIGINT NULL;
|
||||
ALTER TABLE epub_viewer_preference ADD FOREIGN KEY (custom_font_id) REFERENCES custom_font(id) ON DELETE SET NULL;
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
-- Migrate MetadataPersistenceSettings from old structure to new nested structure
|
||||
-- Old: {"saveToOriginalFile":boolean,...}
|
||||
-- New: {"saveToOriginalFile":{"epub":{...},"pdf":{...}},...}
|
||||
-- Creates metadata_persistence_settings_v2 instead of overwriting the original
|
||||
|
||||
INSERT INTO app_settings (name, val)
|
||||
SELECT
|
||||
'metadata_persistence_settings_v2',
|
||||
CASE
|
||||
-- If saveToOriginalFile is true, enable all formats
|
||||
WHEN JSON_EXTRACT(val, '$.saveToOriginalFile') = true THEN
|
||||
JSON_SET(
|
||||
val,
|
||||
'$.saveToOriginalFile',
|
||||
JSON_OBJECT(
|
||||
'epub', JSON_OBJECT('enabled', true, 'maxFileSizeInMb', 250),
|
||||
'pdf', JSON_OBJECT('enabled', true, 'maxFileSizeInMb', 250),
|
||||
'cbx', JSON_OBJECT('enabled', true, 'maxFileSizeInMb', 250)
|
||||
)
|
||||
)
|
||||
-- If saveToOriginalFile is false, disable all formats
|
||||
WHEN JSON_EXTRACT(val, '$.saveToOriginalFile') = false THEN
|
||||
JSON_SET(
|
||||
val,
|
||||
'$.saveToOriginalFile',
|
||||
JSON_OBJECT(
|
||||
'epub', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250),
|
||||
'pdf', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250),
|
||||
'cbx', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250)
|
||||
)
|
||||
)
|
||||
-- If null or missing, default to disabled
|
||||
ELSE
|
||||
JSON_SET(
|
||||
COALESCE(val, '{}'),
|
||||
'$.saveToOriginalFile',
|
||||
JSON_OBJECT(
|
||||
'epub', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250),
|
||||
'pdf', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250),
|
||||
'cbx', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250)
|
||||
)
|
||||
)
|
||||
END
|
||||
FROM app_settings
|
||||
WHERE name = 'metadata_persistence_settings'
|
||||
AND val IS NOT NULL
|
||||
AND val != ''
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM app_settings WHERE name = 'metadata_persistence_settings_v2'
|
||||
);
|
||||
@@ -0,0 +1,8 @@
|
||||
ALTER TABLE user_permissions
|
||||
ADD COLUMN IF NOT EXISTS permission_manage_fonts BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
-- Set all new permissions to TRUE for admin users
|
||||
|
||||
UPDATE user_permissions up
|
||||
SET up.permission_manage_fonts = TRUE
|
||||
WHERE up.permission_admin = TRUE;
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.service.book.BookService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BookMediaControllerTest {
|
||||
|
||||
@Mock
|
||||
private BookService bookService;
|
||||
|
||||
@InjectMocks
|
||||
private BookMediaController bookMediaController;
|
||||
|
||||
@Test
|
||||
void getBackgroundImage_shouldReturnBadRequestWhenFilenameIsNull() {
|
||||
Resource resource = mock(Resource.class);
|
||||
when(bookService.getBackgroundImage()).thenReturn(resource);
|
||||
when(resource.exists()).thenReturn(true);
|
||||
when(resource.getFilename()).thenReturn(null);
|
||||
|
||||
ResponseEntity<Resource> response = bookMediaController.getBackgroundImage();
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
|
||||
}
|
||||
}
|
||||
+15
@@ -13,6 +13,7 @@ import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.repository.KoreaderUserRepository;
|
||||
import com.adityachandel.booklore.service.hardcover.HardcoverSyncService;
|
||||
import com.adityachandel.booklore.service.koreader.KoreaderService;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -24,6 +25,7 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -40,6 +42,8 @@ class KoreaderServiceTest {
|
||||
UserRepository userRepo;
|
||||
@Mock
|
||||
KoreaderUserRepository koreaderUserRepo;
|
||||
@Mock
|
||||
HardcoverSyncService hardcoverSyncService;
|
||||
|
||||
@InjectMocks
|
||||
KoreaderService service;
|
||||
@@ -232,4 +236,15 @@ class KoreaderServiceTest {
|
||||
var dto = KoreaderProgress.builder().document("h").build();
|
||||
assertThrows(APIException.class, () -> service.saveProgress("h", dto));
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeProgressPercent_handlesNullAndRanges() throws Exception {
|
||||
Method method = KoreaderService.class.getDeclaredMethod("normalizeProgressPercent", Float.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertNull(method.invoke(service, new Object[]{null}));
|
||||
assertEquals(50.0f, (Float) method.invoke(service, 0.5f));
|
||||
assertEquals(100.0f, (Float) method.invoke(service, 1.0f));
|
||||
assertEquals(42.0f, (Float) method.invoke(service, 42.0f));
|
||||
}
|
||||
}
|
||||
|
||||
+28
-26
@@ -41,20 +41,34 @@ import static org.mockito.Mockito.*;
|
||||
@ExtendWith(org.mockito.junit.jupiter.MockitoExtension.class)
|
||||
class BookServiceTest {
|
||||
|
||||
@Mock private BookRepository bookRepository;
|
||||
@Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
@Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
@Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
@Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||
@Mock private FileService fileService;
|
||||
@Mock private BookMapper bookMapper;
|
||||
@Mock private UserBookProgressRepository userBookProgressRepository;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private BookQueryService bookQueryService;
|
||||
@Mock private UserProgressService userProgressService;
|
||||
@Mock private BookDownloadService bookDownloadService;
|
||||
@Mock private MonitoringRegistrationService monitoringRegistrationService;
|
||||
@Mock private BookUpdateService bookUpdateService;
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
@Mock
|
||||
private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
@Mock
|
||||
private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
@Mock
|
||||
private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
@Mock
|
||||
private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||
@Mock
|
||||
private FileService fileService;
|
||||
@Mock
|
||||
private BookMapper bookMapper;
|
||||
@Mock
|
||||
private UserBookProgressRepository userBookProgressRepository;
|
||||
@Mock
|
||||
private AuthenticationService authenticationService;
|
||||
@Mock
|
||||
private BookQueryService bookQueryService;
|
||||
@Mock
|
||||
private UserProgressService userProgressService;
|
||||
@Mock
|
||||
private BookDownloadService bookDownloadService;
|
||||
@Mock
|
||||
private MonitoringRegistrationService monitoringRegistrationService;
|
||||
@Mock
|
||||
private BookUpdateService bookUpdateService;
|
||||
|
||||
@InjectMocks
|
||||
private BookService bookService;
|
||||
@@ -258,18 +272,6 @@ class BookServiceTest {
|
||||
assertThrows(RuntimeException.class, () -> bookService.getBookCover(123L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getBackgroundImage_returnsResource() {
|
||||
Resource mockResource = mock(Resource.class);
|
||||
when(fileService.getBackgroundResource(testUser.getId())).thenReturn(mockResource);
|
||||
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
|
||||
Resource res = bookService.getBackgroundImage();
|
||||
|
||||
assertEquals(mockResource, res);
|
||||
}
|
||||
|
||||
@Test
|
||||
void downloadBook_delegatesToDownloadService() {
|
||||
ResponseEntity<Resource> response = ResponseEntity.ok(mock(Resource.class));
|
||||
|
||||
+452
@@ -0,0 +1,452 @@
|
||||
package com.adityachandel.booklore.service.customfont;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.mapper.CustomFontMapper;
|
||||
import com.adityachandel.booklore.model.dto.CustomFontDto;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.CustomFontEntity;
|
||||
import com.adityachandel.booklore.model.enums.FontFormat;
|
||||
import com.adityachandel.booklore.repository.CustomFontRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class CustomFontServiceTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Mock
|
||||
CustomFontRepository customFontRepository;
|
||||
@Mock
|
||||
UserRepository userRepository;
|
||||
@Mock
|
||||
CustomFontMapper customFontMapper;
|
||||
|
||||
AppProperties appProperties;
|
||||
CustomFontService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
appProperties = new AppProperties();
|
||||
appProperties.setPathConfig(tempDir.toString());
|
||||
service = new CustomFontService(customFontRepository, userRepository, customFontMapper, appProperties);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("uploadFont_withValidFile_shouldSaveSuccessfully")
|
||||
void uploadFont_withValidFile_shouldSaveSuccessfully() throws IOException {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
String fontName = "My Custom Font";
|
||||
// Create valid TTF magic bytes: 0x00 0x01 0x00 0x00
|
||||
byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||
MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", fontContent);
|
||||
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setId(userId);
|
||||
|
||||
CustomFontEntity savedEntity = CustomFontEntity.builder()
|
||||
.id(1L)
|
||||
.user(user)
|
||||
.fontName(fontName)
|
||||
.fileName("user_1_font_123.ttf")
|
||||
.originalFileName("font.ttf")
|
||||
.format(FontFormat.TTF)
|
||||
.fileSize((long) fontContent.length)
|
||||
.build();
|
||||
|
||||
CustomFontDto expectedDto = new CustomFontDto();
|
||||
expectedDto.setId(1L);
|
||||
expectedDto.setFontName(fontName);
|
||||
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.of(user));
|
||||
when(customFontRepository.countByUserId(userId)).thenReturn(0);
|
||||
when(customFontRepository.save(any(CustomFontEntity.class))).thenReturn(savedEntity);
|
||||
when(customFontMapper.toDto(savedEntity)).thenReturn(expectedDto);
|
||||
|
||||
// Act
|
||||
CustomFontDto result = service.uploadFont(file, fontName, userId);
|
||||
|
||||
// Assert
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.getFontName()).isEqualTo(fontName);
|
||||
verify(customFontRepository).save(any(CustomFontEntity.class));
|
||||
|
||||
// Verify file was saved
|
||||
Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId));
|
||||
assertThat(Files.exists(userFontDir)).isTrue();
|
||||
assertThat(Files.list(userFontDir).count()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("uploadFont_whenQuotaExceeded_shouldThrowException")
|
||||
void uploadFont_whenQuotaExceeded_shouldThrowException() {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", "content".getBytes());
|
||||
|
||||
when(customFontRepository.countByUserId(userId)).thenReturn(10); // Max quota
|
||||
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> service.uploadFont(file, "Font", userId))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Font limit exceeded");
|
||||
|
||||
verify(customFontRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("uploadFont_withOversizedFile_shouldThrowException")
|
||||
void uploadFont_withOversizedFile_shouldThrowException() {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
byte[] largeContent = new byte[6 * 1024 * 1024]; // 6MB (exceeds 5MB limit)
|
||||
MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", largeContent);
|
||||
|
||||
when(customFontRepository.countByUserId(userId)).thenReturn(0);
|
||||
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> service.uploadFont(file, "Font", userId))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("File size exceeds maximum limit");
|
||||
|
||||
verify(customFontRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("uploadFont_withInvalidExtension_shouldThrowException")
|
||||
void uploadFont_withInvalidExtension_shouldThrowException() {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
MultipartFile file = new MockMultipartFile("font.exe", "font.exe", "application/octet-stream", "content".getBytes());
|
||||
|
||||
when(customFontRepository.countByUserId(userId)).thenReturn(0);
|
||||
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> service.uploadFont(file, "Font", userId))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Unsupported font format");
|
||||
|
||||
verify(customFontRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("uploadFont_withInvalidMagicBytes_shouldThrowException")
|
||||
void uploadFont_withInvalidMagicBytes_shouldThrowException() throws IOException {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
// File has .ttf extension but contains malicious content (not TTF magic bytes)
|
||||
byte[] maliciousContent = "This is not a font file".getBytes();
|
||||
MultipartFile file = new MockMultipartFile("malicious.ttf", "malicious.ttf", "font/ttf", maliciousContent);
|
||||
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setId(userId);
|
||||
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.of(user));
|
||||
when(customFontRepository.countByUserId(userId)).thenReturn(0);
|
||||
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> service.uploadFont(file, "Font", userId))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Invalid font file format");
|
||||
|
||||
verify(customFontRepository, never()).save(any());
|
||||
|
||||
// Verify file was cleaned up
|
||||
Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId));
|
||||
if (Files.exists(userFontDir)) {
|
||||
assertThat(Files.list(userFontDir).count()).isEqualTo(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("uploadFont_whenDatabaseSaveFails_shouldCleanupFile")
|
||||
void uploadFont_whenDatabaseSaveFails_shouldCleanupFile() throws IOException {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
// Create valid TTF magic bytes
|
||||
byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||
MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", fontContent);
|
||||
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setId(userId);
|
||||
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.of(user));
|
||||
when(customFontRepository.countByUserId(userId)).thenReturn(0);
|
||||
when(customFontRepository.save(any(CustomFontEntity.class)))
|
||||
.thenThrow(new RuntimeException("Database error"));
|
||||
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> service.uploadFont(file, "Font", userId))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("Database error");
|
||||
|
||||
// Verify file was cleaned up
|
||||
Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId));
|
||||
if (Files.exists(userFontDir)) {
|
||||
assertThat(Files.list(userFontDir).count()).isEqualTo(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("deleteFont_withValidId_shouldDeleteFileAndRecord")
|
||||
void deleteFont_withValidId_shouldDeleteFileAndRecord() throws IOException {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
Long fontId = 1L;
|
||||
String fileName = "user_1_font_123.ttf";
|
||||
|
||||
// Create actual font file
|
||||
Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId));
|
||||
Files.createDirectories(userFontDir);
|
||||
Path fontFile = userFontDir.resolve(fileName);
|
||||
Files.writeString(fontFile, "font content");
|
||||
|
||||
CustomFontEntity font = CustomFontEntity.builder()
|
||||
.id(fontId)
|
||||
.fontName("Test Font")
|
||||
.fileName(fileName)
|
||||
.build();
|
||||
|
||||
when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font));
|
||||
|
||||
// Act
|
||||
service.deleteFont(fontId, userId);
|
||||
|
||||
// Assert
|
||||
verify(customFontRepository).delete(font);
|
||||
assertThat(Files.exists(fontFile)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("deleteFont_whenFileDeletionFails_shouldStillDeleteRecord")
|
||||
void deleteFont_whenFileDeletionFails_shouldStillDeleteRecord() {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
Long fontId = 1L;
|
||||
String fileName = "non_existent_font.ttf";
|
||||
|
||||
CustomFontEntity font = CustomFontEntity.builder()
|
||||
.id(fontId)
|
||||
.fontName("Test Font")
|
||||
.fileName(fileName)
|
||||
.build();
|
||||
|
||||
when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font));
|
||||
|
||||
// Act
|
||||
// Files.deleteIfExists doesn't throw when file doesn't exist, so this should succeed
|
||||
assertThatCode(() -> service.deleteFont(fontId, userId))
|
||||
.doesNotThrowAnyException();
|
||||
|
||||
// Database record should be deleted
|
||||
verify(customFontRepository, times(1)).delete(font);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("deleteFont_withInvalidId_shouldThrowException")
|
||||
void deleteFont_withInvalidId_shouldThrowException() {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
Long fontId = 999L;
|
||||
|
||||
when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.empty());
|
||||
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> service.deleteFont(fontId, userId))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Font not found or access denied");
|
||||
|
||||
verify(customFontRepository, never()).delete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("getFontFile_withValidId_shouldReturnResource")
|
||||
void getFontFile_withValidId_shouldReturnResource() throws IOException {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
Long fontId = 1L;
|
||||
String fileName = "user_1_font_123.ttf";
|
||||
|
||||
// Create actual font file
|
||||
Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId));
|
||||
Files.createDirectories(userFontDir);
|
||||
Path fontFile = userFontDir.resolve(fileName);
|
||||
Files.writeString(fontFile, "font content");
|
||||
|
||||
CustomFontEntity font = CustomFontEntity.builder()
|
||||
.id(fontId)
|
||||
.fontName("Test Font")
|
||||
.fileName(fileName)
|
||||
.build();
|
||||
|
||||
when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font));
|
||||
|
||||
// Act
|
||||
Resource result = service.getFontFile(fontId, userId);
|
||||
|
||||
// Assert
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.exists()).isTrue();
|
||||
assertThat(result.getFile().toPath()).isEqualTo(fontFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("getFontFile_whenUserNotOwner_shouldThrowException")
|
||||
void getFontFile_whenUserNotOwner_shouldThrowException() {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
Long otherUserId = 2L;
|
||||
Long fontId = 1L;
|
||||
|
||||
when(customFontRepository.findByIdAndUserId(fontId, otherUserId)).thenReturn(Optional.empty());
|
||||
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> service.getFontFile(fontId, otherUserId))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Font not found or access denied");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("getFontFile_withNonExistentFile_shouldThrowException")
|
||||
void getFontFile_withNonExistentFile_shouldThrowException() {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
Long fontId = 1L;
|
||||
String fileName = "non_existent.ttf";
|
||||
|
||||
CustomFontEntity font = CustomFontEntity.builder()
|
||||
.id(fontId)
|
||||
.fontName("Test Font")
|
||||
.fileName(fileName)
|
||||
.build();
|
||||
|
||||
when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font));
|
||||
|
||||
// Act & Assert
|
||||
assertThatThrownBy(() -> service.getFontFile(fontId, userId))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Font file not found on disk");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("validatePath_withPathTraversal_shouldThrowException")
|
||||
void validatePath_withPathTraversal_shouldThrowException() throws IOException {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
// Use valid font extension to pass extension validation
|
||||
String maliciousFileName = "../../../etc/passwd.ttf";
|
||||
// Create valid TTF magic bytes to pass magic byte validation
|
||||
byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||
MultipartFile file = new MockMultipartFile(
|
||||
maliciousFileName,
|
||||
maliciousFileName,
|
||||
"font/ttf",
|
||||
fontContent
|
||||
);
|
||||
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setId(userId);
|
||||
|
||||
when(userRepository.findById(userId)).thenReturn(Optional.of(user));
|
||||
when(customFontRepository.countByUserId(userId)).thenReturn(0);
|
||||
|
||||
// Mock repository save to complete the upload
|
||||
when(customFontRepository.save(any(CustomFontEntity.class))).thenAnswer(invocation -> {
|
||||
CustomFontEntity entity = invocation.getArgument(0);
|
||||
entity.setId(1L);
|
||||
return entity;
|
||||
});
|
||||
|
||||
CustomFontDto mockDto = new CustomFontDto();
|
||||
mockDto.setId(1L);
|
||||
when(customFontMapper.toDto(any(CustomFontEntity.class))).thenReturn(mockDto);
|
||||
|
||||
// Act & Assert
|
||||
// The service generates safe filenames, so even with malicious input, the path is safe
|
||||
assertThatCode(() -> service.uploadFont(file, "Test", userId))
|
||||
.doesNotThrowAnyException(); // Safe because service generates safe filename
|
||||
|
||||
// Verify no files were created outside the expected directory
|
||||
Path expectedDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId));
|
||||
Path parentDir = tempDir.resolve("custom-fonts");
|
||||
|
||||
// Count files in user directory
|
||||
long userDirFiles = Files.exists(expectedDir) ? Files.list(expectedDir).count() : 0;
|
||||
|
||||
// Count files in parent directory (should only be the user directory)
|
||||
long parentDirEntries = Files.list(parentDir).count();
|
||||
|
||||
assertThat(userDirFiles).isGreaterThanOrEqualTo(0);
|
||||
assertThat(parentDirEntries).isEqualTo(1); // Only user directory, no escaped files
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("getUserFonts_shouldReturnAllUserFonts")
|
||||
void getUserFonts_shouldReturnAllUserFonts() {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
List<CustomFontEntity> entities = List.of(
|
||||
CustomFontEntity.builder().id(1L).fontName("Font 1").build(),
|
||||
CustomFontEntity.builder().id(2L).fontName("Font 2").build()
|
||||
);
|
||||
|
||||
CustomFontDto dto1 = new CustomFontDto();
|
||||
dto1.setId(1L);
|
||||
CustomFontDto dto2 = new CustomFontDto();
|
||||
dto2.setId(2L);
|
||||
|
||||
when(customFontRepository.findByUserId(userId)).thenReturn(entities);
|
||||
when(customFontMapper.toDto(entities.get(0))).thenReturn(dto1);
|
||||
when(customFontMapper.toDto(entities.get(1))).thenReturn(dto2);
|
||||
|
||||
// Act
|
||||
List<CustomFontDto> result = service.getUserFonts(userId);
|
||||
|
||||
// Assert
|
||||
assertThat(result).hasSize(2);
|
||||
assertThat(result.get(0).getId()).isEqualTo(1L);
|
||||
assertThat(result.get(1).getId()).isEqualTo(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("getFontFormat_shouldReturnCorrectFormat")
|
||||
void getFontFormat_shouldReturnCorrectFormat() {
|
||||
// Arrange
|
||||
Long userId = 1L;
|
||||
Long fontId = 1L;
|
||||
|
||||
CustomFontEntity font = CustomFontEntity.builder()
|
||||
.id(fontId)
|
||||
.fontName("Test Font")
|
||||
.format(FontFormat.WOFF2)
|
||||
.build();
|
||||
|
||||
when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font));
|
||||
|
||||
// Act
|
||||
FontFormat result = service.getFontFormat(fontId, userId);
|
||||
|
||||
// Assert
|
||||
assertThat(result).isEqualTo(FontFormat.WOFF2);
|
||||
}
|
||||
}
|
||||
+105
-15
@@ -1,10 +1,9 @@
|
||||
package com.adityachandel.booklore.service.hardcover;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.KoboSyncSettings;
|
||||
import com.adityachandel.booklore.model.dto.HardcoverSyncSettings;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.kobo.KoboSettingsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -14,8 +13,10 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.web.client.RestClient;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -29,7 +30,7 @@ import static org.mockito.Mockito.*;
|
||||
class HardcoverSyncServiceTest {
|
||||
|
||||
@Mock
|
||||
private KoboSettingsService koboSettingsService;
|
||||
private HardcoverSyncSettingsService hardcoverSyncSettingsService;
|
||||
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
@@ -50,7 +51,7 @@ class HardcoverSyncServiceTest {
|
||||
|
||||
private BookEntity testBook;
|
||||
private BookMetadataEntity testMetadata;
|
||||
private KoboSyncSettings koboSyncSettings;
|
||||
private HardcoverSyncSettings hardcoverSyncSettings;
|
||||
|
||||
private static final Long TEST_BOOK_ID = 100L;
|
||||
private static final Long TEST_USER_ID = 1L;
|
||||
@@ -58,7 +59,7 @@ class HardcoverSyncServiceTest {
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
// Create service with mocked dependencies
|
||||
service = new HardcoverSyncService(koboSettingsService, bookRepository);
|
||||
service = new HardcoverSyncService(hardcoverSyncSettingsService, bookRepository);
|
||||
|
||||
// Inject our mocked restClient using reflection
|
||||
Field restClientField = HardcoverSyncService.class.getDeclaredField("restClient");
|
||||
@@ -73,19 +74,19 @@ class HardcoverSyncServiceTest {
|
||||
testMetadata.setPageCount(300);
|
||||
testBook.setMetadata(testMetadata);
|
||||
|
||||
// Setup Kobo sync settings with Hardcover enabled
|
||||
koboSyncSettings = new KoboSyncSettings();
|
||||
koboSyncSettings.setHardcoverSyncEnabled(true);
|
||||
koboSyncSettings.setHardcoverApiKey("test-api-key");
|
||||
// Setup Hardcover sync settings
|
||||
hardcoverSyncSettings = new HardcoverSyncSettings();
|
||||
hardcoverSyncSettings.setHardcoverSyncEnabled(true);
|
||||
hardcoverSyncSettings.setHardcoverApiKey("test-api-key");
|
||||
|
||||
when(koboSettingsService.getSettingsByUserId(TEST_USER_ID)).thenReturn(koboSyncSettings);
|
||||
when(hardcoverSyncSettingsService.getSettingsForUserId(TEST_USER_ID)).thenReturn(hardcoverSyncSettings);
|
||||
when(bookRepository.findById(TEST_BOOK_ID)).thenReturn(Optional.of(testBook));
|
||||
|
||||
// Setup RestClient mock chain - handles multiple calls
|
||||
when(restClient.post()).thenReturn(requestBodyUriSpec);
|
||||
when(requestBodyUriSpec.uri(anyString())).thenReturn(requestBodySpec);
|
||||
when(requestBodySpec.header(anyString(), anyString())).thenReturn(requestBodySpec);
|
||||
when(requestBodySpec.body(any())).thenReturn(requestBodySpec);
|
||||
doReturn(requestBodySpec).when(requestBodySpec).body(ArgumentMatchers.any(Object.class));
|
||||
when(requestBodySpec.retrieve()).thenReturn(responseSpec);
|
||||
}
|
||||
|
||||
@@ -94,7 +95,7 @@ class HardcoverSyncServiceTest {
|
||||
@Test
|
||||
@DisplayName("Should skip sync when Hardcover sync is not enabled for user")
|
||||
void syncProgressToHardcover_whenHardcoverDisabled_shouldSkip() {
|
||||
koboSyncSettings.setHardcoverSyncEnabled(false);
|
||||
hardcoverSyncSettings.setHardcoverSyncEnabled(false);
|
||||
|
||||
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
|
||||
|
||||
@@ -104,7 +105,7 @@ class HardcoverSyncServiceTest {
|
||||
@Test
|
||||
@DisplayName("Should skip sync when API key is missing")
|
||||
void syncProgressToHardcover_whenApiKeyMissing_shouldSkip() {
|
||||
koboSyncSettings.setHardcoverApiKey(null);
|
||||
hardcoverSyncSettings.setHardcoverApiKey(null);
|
||||
|
||||
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
|
||||
|
||||
@@ -114,7 +115,7 @@ class HardcoverSyncServiceTest {
|
||||
@Test
|
||||
@DisplayName("Should skip sync when API key is blank")
|
||||
void syncProgressToHardcover_whenApiKeyBlank_shouldSkip() {
|
||||
koboSyncSettings.setHardcoverApiKey(" ");
|
||||
hardcoverSyncSettings.setHardcoverApiKey(" ");
|
||||
|
||||
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
|
||||
|
||||
@@ -244,6 +245,7 @@ class HardcoverSyncServiceTest {
|
||||
@DisplayName("Should handle existing user_book gracefully")
|
||||
void syncProgressToHardcover_whenUserBookExists_shouldFindExisting() {
|
||||
testMetadata.setHardcoverBookId(12345);
|
||||
testMetadata.setPageCount(300);
|
||||
|
||||
// Mock: insert_user_book returns error, then find existing, then create progress
|
||||
when(responseSpec.body(Map.class))
|
||||
@@ -261,6 +263,7 @@ class HardcoverSyncServiceTest {
|
||||
@DisplayName("Should update existing reading progress")
|
||||
void syncProgressToHardcover_whenProgressExists_shouldUpdate() {
|
||||
testMetadata.setHardcoverBookId(12345);
|
||||
testMetadata.setPageCount(300);
|
||||
|
||||
// Mock: insert_user_book -> find existing read -> update read
|
||||
when(responseSpec.body(Map.class))
|
||||
@@ -296,6 +299,7 @@ class HardcoverSyncServiceTest {
|
||||
@DisplayName("Should handle API errors gracefully")
|
||||
void syncProgressToHardcover_whenApiError_shouldNotThrow() {
|
||||
testMetadata.setHardcoverBookId(12345);
|
||||
testMetadata.setPageCount(300);
|
||||
|
||||
when(responseSpec.body(Map.class)).thenReturn(Map.of("errors", List.of(Map.of("message", "Unauthorized"))));
|
||||
|
||||
@@ -306,6 +310,7 @@ class HardcoverSyncServiceTest {
|
||||
@DisplayName("Should handle null response gracefully")
|
||||
void syncProgressToHardcover_whenResponseNull_shouldNotThrow() {
|
||||
testMetadata.setHardcoverBookId(12345);
|
||||
testMetadata.setPageCount(300);
|
||||
|
||||
when(responseSpec.body(Map.class)).thenReturn(null);
|
||||
|
||||
@@ -315,7 +320,7 @@ class HardcoverSyncServiceTest {
|
||||
@Test
|
||||
@DisplayName("Should skip sync when user settings not found")
|
||||
void syncProgressToHardcover_whenUserSettingsNotFound_shouldSkip() {
|
||||
when(koboSettingsService.getSettingsByUserId(TEST_USER_ID)).thenReturn(null);
|
||||
when(hardcoverSyncSettingsService.getSettingsForUserId(TEST_USER_ID)).thenReturn(null);
|
||||
|
||||
service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID);
|
||||
|
||||
@@ -441,4 +446,89 @@ class HardcoverSyncServiceTest {
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("findEditionById should return null on null response")
|
||||
void findEditionById_nullResponse_shouldReturnNull() throws Exception {
|
||||
when(responseSpec.body(ArgumentMatchers.<Class<Map>>eq(Map.class))).thenReturn(null);
|
||||
|
||||
Method method = HardcoverSyncService.class.getDeclaredMethod("findEditionById", Integer.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
Object result = method.invoke(service, 123);
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("findEditionById should parse edition info when present")
|
||||
void findEditionById_withData_shouldParse() throws Exception {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
Map<String, Object> edition = new HashMap<>();
|
||||
edition.put("id", 77);
|
||||
edition.put("pages", 250);
|
||||
data.put("editions", List.of(edition));
|
||||
response.put("data", data);
|
||||
|
||||
when(responseSpec.body(ArgumentMatchers.<Class<Map>>eq(Map.class))).thenReturn(response);
|
||||
|
||||
Method method = HardcoverSyncService.class.getDeclaredMethod("findEditionById", Integer.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
Object result = method.invoke(service, 77);
|
||||
assertNotNull(result);
|
||||
assertEquals(77, readPrivateField(result, "id"));
|
||||
assertEquals(250, readPrivateField(result, "pages"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("findHardcoverBookById should return null on empty response")
|
||||
void findHardcoverBookById_emptyResponse_shouldReturnNull() throws Exception {
|
||||
when(responseSpec.body(ArgumentMatchers.<Class<Map>>eq(Map.class)))
|
||||
.thenReturn(Map.of("data", Map.of("books", List.of())));
|
||||
|
||||
Method method = HardcoverSyncService.class.getDeclaredMethod("findHardcoverBookById", Integer.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
Object result = method.invoke(service, 123);
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("findHardcoverBookById should use default edition and edition pages")
|
||||
void findHardcoverBookById_withDefaultEdition_shouldUseEditionPages() throws Exception {
|
||||
Map<String, Object> bookResponse = new HashMap<>();
|
||||
Map<String, Object> bookData = new HashMap<>();
|
||||
Map<String, Object> book = new HashMap<>();
|
||||
book.put("default_edition_id", "88");
|
||||
bookData.put("books", List.of(book));
|
||||
bookResponse.put("data", bookData);
|
||||
|
||||
Map<String, Object> editionResponse = new HashMap<>();
|
||||
Map<String, Object> editionData = new HashMap<>();
|
||||
Map<String, Object> edition = new HashMap<>();
|
||||
edition.put("id", 88);
|
||||
edition.put("pages", 320);
|
||||
editionData.put("editions", List.of(edition));
|
||||
editionResponse.put("data", editionData);
|
||||
|
||||
when(responseSpec.body(ArgumentMatchers.<Class<Map>>eq(Map.class)))
|
||||
.thenReturn(bookResponse)
|
||||
.thenReturn(editionResponse);
|
||||
|
||||
Method method = HardcoverSyncService.class.getDeclaredMethod("findHardcoverBookById", Integer.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
Object result = method.invoke(service, 123);
|
||||
assertNotNull(result);
|
||||
assertEquals(123, readPrivateField(result, "bookId"));
|
||||
assertEquals(88, readPrivateField(result, "editionId"));
|
||||
assertEquals(320, readPrivateField(result, "pages"));
|
||||
}
|
||||
|
||||
private Integer readPrivateField(Object target, String fieldName) throws Exception {
|
||||
Field field = target.getClass().getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
return (Integer) field.get(target);
|
||||
}
|
||||
}
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.adityachandel.booklore.service.hardcover;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.model.dto.HardcoverSyncSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserSettingEntity;
|
||||
import com.adityachandel.booklore.repository.KoboUserSettingsRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class HardcoverSyncSettingsServiceTest {
|
||||
|
||||
@Mock
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Mock
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
@Mock
|
||||
private KoboUserSettingsRepository koboUserSettingsRepository;
|
||||
|
||||
private HardcoverSyncSettingsService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new HardcoverSyncSettingsService(userRepository, authenticationService, koboUserSettingsRepository);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should fallback to legacy Kobo settings and persist user settings")
|
||||
void getSettingsForUserId_whenLegacyPresent_shouldPersistUserSettings() {
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setId(1L);
|
||||
user.setSettings(new HashSet<>());
|
||||
|
||||
KoboUserSettingsEntity legacy = KoboUserSettingsEntity.builder()
|
||||
.userId(1L)
|
||||
.hardcoverApiKey("legacy-key")
|
||||
.hardcoverSyncEnabled(true)
|
||||
.build();
|
||||
|
||||
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
|
||||
when(koboUserSettingsRepository.findByUserId(1L)).thenReturn(Optional.of(legacy));
|
||||
|
||||
HardcoverSyncSettings settings = service.getSettingsForUserId(1L);
|
||||
|
||||
assertEquals("legacy-key", settings.getHardcoverApiKey());
|
||||
assertTrue(settings.isHardcoverSyncEnabled());
|
||||
assertTrue(user.getSettings().stream()
|
||||
.anyMatch(setting -> UserSettingKey.HARDCOVER_API_KEY.getDbKey().equals(setting.getSettingKey())));
|
||||
assertTrue(user.getSettings().stream()
|
||||
.anyMatch(setting -> UserSettingKey.HARDCOVER_SYNC_ENABLED.getDbKey().equals(setting.getSettingKey())));
|
||||
verify(userRepository).save(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should trim API key when updating settings")
|
||||
void updateSettingsForUserId_shouldTrimApiKey() {
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setId(1L);
|
||||
user.setSettings(new HashSet<>());
|
||||
user.getSettings().add(UserSettingEntity.builder()
|
||||
.user(user)
|
||||
.settingKey(UserSettingKey.HARDCOVER_API_KEY.getDbKey())
|
||||
.settingValue("old")
|
||||
.build());
|
||||
|
||||
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
|
||||
|
||||
HardcoverSyncSettings update = new HardcoverSyncSettings();
|
||||
update.setHardcoverApiKey(" new-key ");
|
||||
update.setHardcoverSyncEnabled(false);
|
||||
|
||||
HardcoverSyncSettings result = service.updateSettingsForUserId(1L, update);
|
||||
|
||||
assertEquals("new-key", result.getHardcoverApiKey());
|
||||
assertTrue(user.getSettings().stream()
|
||||
.anyMatch(setting -> UserSettingKey.HARDCOVER_API_KEY.getDbKey().equals(setting.getSettingKey())
|
||||
&& "new-key".equals(setting.getSettingValue())));
|
||||
verify(userRepository).save(user);
|
||||
}
|
||||
}
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
package com.adityachandel.booklore.service.kobo;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookloreSyncToken;
|
||||
import com.adityachandel.booklore.model.dto.kobo.KoboHeaders;
|
||||
import com.adityachandel.booklore.util.kobo.BookloreSyncTokenGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KoboServerProxyTest {
|
||||
|
||||
@Mock
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Mock
|
||||
private BookloreSyncTokenGenerator bookloreSyncTokenGenerator;
|
||||
|
||||
@Mock
|
||||
private HttpClient httpClient;
|
||||
|
||||
@Mock
|
||||
private HttpResponse<String> httpResponse;
|
||||
|
||||
@Mock
|
||||
private HttpResponse<byte[]> httpResponseBytes;
|
||||
|
||||
@InjectMocks
|
||||
private KoboServerProxy koboServerProxy;
|
||||
|
||||
private MockHttpServletRequest mockRequest;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
mockRequest = new MockHttpServletRequest();
|
||||
mockRequest.setMethod("GET");
|
||||
mockRequest.setRequestURI("/api/kobo/v1/library/sync");
|
||||
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(mockRequest));
|
||||
|
||||
Field httpClientField = KoboServerProxy.class.getDeclaredField("httpClient");
|
||||
httpClientField.setAccessible(true);
|
||||
httpClientField.set(koboServerProxy, httpClient);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
}
|
||||
|
||||
private void setupSuccessfulProxyResponse() throws Exception {
|
||||
when(httpResponse.statusCode()).thenReturn(200);
|
||||
when(httpResponse.body()).thenReturn("{}");
|
||||
when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of(
|
||||
Collections.emptyMap(),
|
||||
(k, v) -> true
|
||||
));
|
||||
when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class));
|
||||
when(httpClient.<String>send(any(HttpRequest.class), any()))
|
||||
.thenReturn(httpResponse);
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyCurrentRequest_withSquareBracketsInQueryParams_shouldHandleSuccessfully() throws Exception {
|
||||
// Validates fix for: IllegalArgumentException: Invalid character '[' for QUERY_PARAM
|
||||
String problematicQuery = "Filters=[%7BKey:TestKey,ETag:W/TestEtagValue123%7D]";
|
||||
mockRequest.setQueryString(problematicQuery);
|
||||
mockRequest.addHeader("User-Agent", "Kobo/1.0");
|
||||
setupSuccessfulProxyResponse();
|
||||
|
||||
ResponseEntity<JsonNode> response = koboServerProxy.proxyCurrentRequest(null, false);
|
||||
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
verify(httpClient).<String>send(any(HttpRequest.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyCurrentRequest_withVariousEncodedQueryParams_shouldHandleSuccessfully() throws Exception {
|
||||
String[] testQueries = {
|
||||
"Filters=%5B%7BKey:TestKey%7D%5D", // Properly encoded brackets
|
||||
"Filter=ALL&DownloadUrlFilter=Generic,Android&PrioritizeRecentReads=true", // Real Kobo params
|
||||
"page_index=0&page_size=50&Filters=%7B%7D" // URL-encoded JSON
|
||||
};
|
||||
|
||||
for (String query : testQueries) {
|
||||
mockRequest.setQueryString(query);
|
||||
setupSuccessfulProxyResponse();
|
||||
|
||||
ResponseEntity<JsonNode> response = koboServerProxy.proxyCurrentRequest(null, false);
|
||||
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
verify(httpClient, times(testQueries.length)).<String>send(any(HttpRequest.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyCurrentRequest_withSyncToken_shouldPreserveAndUpdateToken() throws Exception {
|
||||
mockRequest.setQueryString("Filter=ALL");
|
||||
mockRequest.addHeader(KoboHeaders.X_KOBO_SYNCTOKEN, "original-token");
|
||||
|
||||
BookloreSyncToken mockSyncToken = BookloreSyncToken.builder()
|
||||
.rawKoboSyncToken("kobo-sync-token")
|
||||
.ongoingSyncPointId("1")
|
||||
.lastSuccessfulSyncPointId("0")
|
||||
.build();
|
||||
|
||||
when(bookloreSyncTokenGenerator.fromRequestHeaders(any())).thenReturn(mockSyncToken);
|
||||
when(httpResponse.statusCode()).thenReturn(200);
|
||||
when(httpResponse.body()).thenReturn("{}");
|
||||
when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of(
|
||||
Map.of(KoboHeaders.X_KOBO_SYNCTOKEN, java.util.List.of("new-kobo-token")),
|
||||
(k, v) -> true
|
||||
));
|
||||
when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class));
|
||||
when(bookloreSyncTokenGenerator.toBase64(any())).thenReturn("encoded-sync-token");
|
||||
when(httpClient.<String>send(any(HttpRequest.class), any()))
|
||||
.thenReturn(httpResponse);
|
||||
|
||||
ResponseEntity<JsonNode> response = koboServerProxy.proxyCurrentRequest(null, true);
|
||||
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
verify(bookloreSyncTokenGenerator).toBase64(any(BookloreSyncToken.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyCurrentRequest_shouldPreserveKoboHeaders() throws Exception {
|
||||
mockRequest.addHeader("X-Kobo-DeviceId", "device123");
|
||||
mockRequest.addHeader("X-Kobo-UserKey", "user456");
|
||||
|
||||
when(httpResponse.statusCode()).thenReturn(200);
|
||||
when(httpResponse.body()).thenReturn("{}");
|
||||
when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of(
|
||||
Map.of("X-Kobo-Response", java.util.List.of("test")),
|
||||
(k, v) -> true
|
||||
));
|
||||
when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class));
|
||||
when(httpClient.<String>send(any(HttpRequest.class), any()))
|
||||
.thenReturn(httpResponse);
|
||||
|
||||
ResponseEntity<JsonNode> response = koboServerProxy.proxyCurrentRequest(null, false);
|
||||
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getHeaders()).containsKey("X-Kobo-Response");
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyCurrentRequest_withPostBody_shouldSerializeBody() throws Exception {
|
||||
mockRequest.setMethod("POST");
|
||||
Object requestBody = new Object();
|
||||
|
||||
when(objectMapper.writeValueAsString(requestBody)).thenReturn("{\"test\":\"value\"}");
|
||||
setupSuccessfulProxyResponse();
|
||||
|
||||
ResponseEntity<JsonNode> response = koboServerProxy.proxyCurrentRequest(requestBody, false);
|
||||
|
||||
assertThat(response).isNotNull();
|
||||
verify(objectMapper).writeValueAsString(requestBody);
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyCurrentRequest_with400Response_shouldPreserveStatusCode() throws Exception {
|
||||
mockRequest.setQueryString("ExcludeOwned=false&PageSize=100");
|
||||
|
||||
when(httpResponse.statusCode()).thenReturn(400);
|
||||
when(httpResponse.body()).thenReturn("{\"error\":\"Bad Request\"}");
|
||||
when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of(
|
||||
Collections.emptyMap(),
|
||||
(k, v) -> true
|
||||
));
|
||||
when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class));
|
||||
when(httpClient.<String>send(any(HttpRequest.class), any()))
|
||||
.thenReturn(httpResponse);
|
||||
|
||||
ResponseEntity<JsonNode> response = koboServerProxy.proxyCurrentRequest(null, false);
|
||||
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyCurrentRequest_withMaliciousQueryParams_shouldHandleSafely() throws Exception {
|
||||
String[] maliciousQueries = {
|
||||
"param1=value1%0D%0AHost:evil.com", // CRLF injection attempt
|
||||
"text=%3Cscript%3Ealert('xss')%3C/script%3E&other=%22quotes%22" // XSS attempt
|
||||
};
|
||||
|
||||
for (String query : maliciousQueries) {
|
||||
mockRequest.setQueryString(query);
|
||||
setupSuccessfulProxyResponse();
|
||||
|
||||
ResponseEntity<JsonNode> response = koboServerProxy.proxyCurrentRequest(null, false);
|
||||
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyExternalUrl_shouldFetchAndReturnImage() throws Exception {
|
||||
String testUrl = "https://cdn.kobo.com/image123.jpg";
|
||||
byte[] imageData = {1, 2, 3, 4, 5};
|
||||
|
||||
when(httpResponseBytes.statusCode()).thenReturn(200);
|
||||
when(httpResponseBytes.body()).thenReturn(imageData);
|
||||
when(httpClient.<byte[]>send(any(HttpRequest.class), any()))
|
||||
.thenReturn(httpResponseBytes);
|
||||
|
||||
ResponseEntity<Resource> response = koboServerProxy.proxyExternalUrl(testUrl);
|
||||
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull();
|
||||
assertThat(response.getBody().contentLength()).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyExternalUrl_withException_shouldThrowResponseStatusException() throws Exception {
|
||||
String testUrl = "https://cdn.kobo.com/image123.jpg";
|
||||
|
||||
when(httpClient.<byte[]>send(any(HttpRequest.class), any()))
|
||||
.thenThrow(new java.io.IOException("Network error"));
|
||||
|
||||
assertThatThrownBy(() -> koboServerProxy.proxyExternalUrl(testUrl))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.hasMessageContaining("Failed to fetch image");
|
||||
}
|
||||
}
|
||||
+3
@@ -10,6 +10,7 @@ import com.adityachandel.booklore.model.entity.ShelfEntity;
|
||||
import com.adityachandel.booklore.model.enums.ShelfType;
|
||||
import com.adityachandel.booklore.repository.KoboUserSettingsRepository;
|
||||
import com.adityachandel.booklore.service.ShelfService;
|
||||
import com.adityachandel.booklore.service.hardcover.HardcoverSyncSettingsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
@@ -30,6 +31,8 @@ class KoboSettingsServiceTest {
|
||||
private AuthenticationService authenticationService;
|
||||
@Mock
|
||||
private ShelfService shelfService;
|
||||
@Mock
|
||||
private HardcoverSyncSettingsService hardcoverSyncSettingsService;
|
||||
|
||||
@InjectMocks
|
||||
private KoboSettingsService service;
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.LibraryPath;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.FileAttribute;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class LibraryFileHelperTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Mock
|
||||
private LibraryFileProcessor processor;
|
||||
|
||||
@Test
|
||||
void testGetLibraryFiles_HandlesInaccessibleDirectories() throws IOException {
|
||||
LibraryFileHelper libraryFileHelper = new LibraryFileHelper();
|
||||
|
||||
Files.createFile(tempDir.resolve("happy.epub"));
|
||||
Files.createDirectory(tempDir.resolve("some_other_random_named_dir"), PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("---------")));
|
||||
Files.createFile(tempDir.resolve("zzzz_happ.epub"));
|
||||
|
||||
LibraryPathEntity libraryPath = new LibraryPathEntity();
|
||||
libraryPath.setId(10L);
|
||||
libraryPath.setPath(tempDir.toString());
|
||||
|
||||
LibraryEntity testLibrary = LibraryEntity.builder()
|
||||
.name("Test Library")
|
||||
.icon("book")
|
||||
.scanMode(LibraryScanMode.FILE_AS_BOOK)
|
||||
.watch(false)
|
||||
.libraryPaths(List.of(libraryPath))
|
||||
.build();
|
||||
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(testLibrary, processor);
|
||||
assertEquals(libraryFiles.stream().map(LibraryFile::getFileName).sorted().toList(), List.of("happy.epub", "zzzz_happ.epub"));
|
||||
}
|
||||
}
|
||||
+102
-72
@@ -2,14 +2,14 @@ package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.projection.BookCoverUpdateProjection;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.book.BookQueryService;
|
||||
@@ -26,11 +26,13 @@ import org.mockito.*;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class BookCoverServiceTest {
|
||||
@@ -67,94 +69,115 @@ class BookCoverServiceTest {
|
||||
return book;
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateCustomCover_success() {
|
||||
BookEntity book = mockBookEntity(1L, false);
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
|
||||
when(coverImageGenerator.generateCover(any(), any())).thenReturn(new byte[]{1,2,3});
|
||||
doNothing().when(fileService).createThumbnailFromBytes(eq(1L), any());
|
||||
when(bookRepository.save(any())).thenReturn(book);
|
||||
|
||||
bookCoverService.generateCustomCover(1L);
|
||||
|
||||
verify(fileService).createThumbnailFromBytes(eq(1L), any());
|
||||
verify(bookRepository).save(book);
|
||||
verify(notificationService).sendMessage(eq(Topic.BOOKS_COVER_UPDATE), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateCustomCover_coverLocked_throws() {
|
||||
BookEntity book = mockBookEntity(2L, true);
|
||||
when(bookRepository.findById(2L)).thenReturn(Optional.of(book));
|
||||
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||
when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false));
|
||||
assertThatThrownBy(() -> bookCoverService.generateCustomCover(2L))
|
||||
.isInstanceOf(ApiError.METADATA_LOCKED.createException().getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateCoverImageFromFile_success() {
|
||||
void updateCoverFromFile_success() {
|
||||
MultipartFile file = mock(MultipartFile.class);
|
||||
BookEntity book = mockBookEntity(3L, false);
|
||||
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||
BookEntity book = spy(mockBookEntity(3L, false));
|
||||
doReturn(Path.of("/dummy/path")).when(book).getFullFilePath();
|
||||
when(bookRepository.findById(3L)).thenReturn(Optional.of(book));
|
||||
when(bookRepository.save(any())).thenReturn(book);
|
||||
when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false));
|
||||
when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata());
|
||||
|
||||
BookMetadata result = bookCoverService.updateCoverImageFromFile(3L, file);
|
||||
MetadataWriter writer = mock(MetadataWriter.class);
|
||||
when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer));
|
||||
|
||||
verify(fileService).createThumbnailFromFile(3L, file);
|
||||
assertThat(result).isNotNull();
|
||||
BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class);
|
||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection));
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash");
|
||||
bookCoverService.updateCoverFromFile(3L, file);
|
||||
|
||||
verify(fileService).createThumbnailFromFile(3L, file);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateCoverImageFromUrl_success() {
|
||||
void updateCoverFromUrl_success() {
|
||||
String url = "http://test.com/cover.jpg";
|
||||
BookEntity book = mockBookEntity(4L, false);
|
||||
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||
BookEntity book = spy(mockBookEntity(4L, false));
|
||||
doReturn(Path.of("/dummy/path")).when(book).getFullFilePath();
|
||||
when(bookRepository.findById(4L)).thenReturn(Optional.of(book));
|
||||
when(bookRepository.save(any())).thenReturn(book);
|
||||
when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false));
|
||||
when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata());
|
||||
|
||||
BookMetadata result = bookCoverService.updateCoverImageFromUrl(4L, url);
|
||||
MetadataWriter writer = mock(MetadataWriter.class);
|
||||
when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer));
|
||||
|
||||
verify(fileService).createThumbnailFromUrl(4L, url);
|
||||
assertThat(result).isNotNull();
|
||||
BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class);
|
||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection));
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash");
|
||||
bookCoverService.updateCoverFromUrl(4L, url);
|
||||
|
||||
verify(fileService).createThumbnailFromUrl(4L, url);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateCoverImageFromFileForBooks_success() throws Exception {
|
||||
void updateCoverFromFileForBooks_success() throws Exception {
|
||||
try (MockedStatic<SecurityContextVirtualThread> ignored = mockStatic(SecurityContextVirtualThread.class)) {
|
||||
MultipartFile file = mock(MultipartFile.class);
|
||||
when(file.isEmpty()).thenReturn(false);
|
||||
when(file.getContentType()).thenReturn("image/jpeg");
|
||||
doReturn(new byte[]{1,2,3}).when(file).getBytes();
|
||||
BookEntity book = mockBookEntity(5L, false);
|
||||
BookEntity book = spy(mockBookEntity(5L, false));
|
||||
doReturn(Path.of("/dummy/path")).when(book).getFullFilePath();
|
||||
when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||
when(bookRepository.findById(5L)).thenReturn(Optional.of(book));
|
||||
when(bookRepository.save(any())).thenReturn(book);
|
||||
|
||||
when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false));
|
||||
doNothing().when(fileService).createThumbnailFromBytes(eq(5L), any());
|
||||
doNothing().when(notificationService).sendMessage(any(), any());
|
||||
|
||||
ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
Runnable runnable = invocation.getArgument(0);
|
||||
runnable.run();
|
||||
return null;
|
||||
});
|
||||
MetadataWriter writer = mock(MetadataWriter.class);
|
||||
when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer));
|
||||
|
||||
bookCoverService.updateCoverImageFromFileForBooks(Set.of(5L), file);
|
||||
BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class);
|
||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection));
|
||||
|
||||
ArgumentCaptor<Long> idCaptor = ArgumentCaptor.forClass(Long.class);
|
||||
verify(fileService).createThumbnailFromBytes(idCaptor.capture(), any());
|
||||
assertThat(idCaptor.getValue()).isEqualTo(5L);
|
||||
verify(bookRepository).save(any(BookEntity.class));
|
||||
when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
|
||||
org.springframework.transaction.support.TransactionCallback<?> callback = invocation.getArgument(0);
|
||||
return callback.doInTransaction(null);
|
||||
});
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash");
|
||||
|
||||
ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
Runnable runnable = invocation.getArgument(0);
|
||||
runnable.run();
|
||||
return null;
|
||||
});
|
||||
|
||||
bookCoverService.updateCoverFromFileForBooks(Set.of(5L), file);
|
||||
|
||||
ArgumentCaptor<Long> idCaptor = ArgumentCaptor.forClass(Long.class);
|
||||
verify(fileService).createThumbnailFromBytes(idCaptor.capture(), any());
|
||||
assertThat(idCaptor.getValue()).isEqualTo(5L);
|
||||
verify(bookRepository).save(any(BookEntity.class));
|
||||
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateCoverImageFromFileForBooks_invalidFile_throws() {
|
||||
void updateCoverFromFileForBooks_invalidFile_throws() {
|
||||
MultipartFile file = mock(MultipartFile.class);
|
||||
when(file.isEmpty()).thenReturn(true);
|
||||
assertThatThrownBy(() -> bookCoverService.updateCoverImageFromFileForBooks(Set.of(6L), file))
|
||||
assertThatThrownBy(() -> bookCoverService.updateCoverFromFileForBooks(Set.of(6L), file))
|
||||
.isInstanceOf(ApiError.INVALID_INPUT.createException("dummy").getClass());
|
||||
}
|
||||
|
||||
@@ -162,6 +185,7 @@ class BookCoverServiceTest {
|
||||
void regenerateCover_success() {
|
||||
BookEntity book = mockBookEntity(7L, false);
|
||||
when(bookRepository.findById(7L)).thenReturn(Optional.of(book));
|
||||
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||
BookFileProcessor processor = mock(BookFileProcessor.class);
|
||||
when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor);
|
||||
when(processor.generateCover(any())).thenReturn(true);
|
||||
@@ -177,6 +201,7 @@ class BookCoverServiceTest {
|
||||
void regenerateCover_coverLocked_throws() {
|
||||
BookEntity book = mockBookEntity(8L, true);
|
||||
when(bookRepository.findById(8L)).thenReturn(Optional.of(book));
|
||||
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||
assertThatThrownBy(() -> bookCoverService.regenerateCover(8L))
|
||||
.isInstanceOf(ApiError.METADATA_LOCKED.createException().getClass());
|
||||
}
|
||||
@@ -186,11 +211,21 @@ class BookCoverServiceTest {
|
||||
try (MockedStatic<SecurityContextVirtualThread> ignored = mockStatic(SecurityContextVirtualThread.class)) {
|
||||
BookEntity book = mockBookEntity(9L, false);
|
||||
when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||
when(bookRepository.findById(9L)).thenReturn(Optional.of(book));
|
||||
when(bookRepository.save(any())).thenReturn(book);
|
||||
|
||||
BookFileProcessor processor = mock(BookFileProcessor.class);
|
||||
when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor);
|
||||
when(processor.generateCover(any())).thenReturn(true);
|
||||
when(bookRepository.findById(9L)).thenReturn(Optional.of(book));
|
||||
when(bookRepository.save(any())).thenReturn(book);
|
||||
|
||||
BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class);
|
||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection));
|
||||
doNothing().when(notificationService).sendMessage(any(), any());
|
||||
|
||||
when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
|
||||
org.springframework.transaction.support.TransactionCallback<?> callback = invocation.getArgument(0);
|
||||
return callback.doInTransaction(null);
|
||||
});
|
||||
|
||||
ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
|
||||
.thenAnswer(invocation -> {
|
||||
@@ -204,6 +239,7 @@ class BookCoverServiceTest {
|
||||
ArgumentCaptor<BookEntity> bookCaptor = ArgumentCaptor.forClass(BookEntity.class);
|
||||
verify(processor).generateCover(bookCaptor.capture());
|
||||
assertThat(bookCaptor.getValue().getId()).isEqualTo(9L);
|
||||
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,40 +248,34 @@ class BookCoverServiceTest {
|
||||
MultipartFile file = mock(MultipartFile.class);
|
||||
BookEntity book = spy(mockBookEntity(10L, false));
|
||||
doReturn(Path.of("/dummy/path")).when(book).getFullFilePath();
|
||||
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||
when(bookRepository.findById(10L)).thenReturn(Optional.of(book));
|
||||
when(bookRepository.save(any())).thenReturn(book);
|
||||
when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false));
|
||||
|
||||
MetadataWriter writer = mock(MetadataWriter.class);
|
||||
when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer));
|
||||
when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata());
|
||||
|
||||
BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class);
|
||||
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection));
|
||||
|
||||
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
|
||||
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash");
|
||||
BookMetadata result = bookCoverService.updateCoverImageFromFile(10L, file);
|
||||
bookCoverService.updateCoverFromFile(10L, file);
|
||||
|
||||
verify(writer).replaceCoverImageFromUpload(book, file);
|
||||
assertThat(result).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateCover_metadataPersistenceSettings_noSaveToOriginalFile() {
|
||||
MultipartFile file = mock(MultipartFile.class);
|
||||
BookEntity book = mockBookEntity(11L, false);
|
||||
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
|
||||
when(bookRepository.save(any())).thenReturn(book);
|
||||
when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(false, false));
|
||||
when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata());
|
||||
private AppSettings mockAppSettings(boolean saveToOriginalFile, boolean convertCbrCb7ToCbz) {
|
||||
MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFileObj =
|
||||
MetadataPersistenceSettings.SaveToOriginalFile.builder()
|
||||
.epub(MetadataPersistenceSettings.FormatSettings.builder().enabled(saveToOriginalFile).build())
|
||||
.pdf(MetadataPersistenceSettings.FormatSettings.builder().enabled(saveToOriginalFile).build())
|
||||
.cbx(MetadataPersistenceSettings.FormatSettings.builder().enabled(saveToOriginalFile).build())
|
||||
.build();
|
||||
|
||||
BookMetadata result = bookCoverService.updateCoverImageFromFile(11L, file);
|
||||
|
||||
verify(metadataWriterFactory, never()).getWriter(any());
|
||||
assertThat(result).isNotNull();
|
||||
}
|
||||
|
||||
private com.adityachandel.booklore.model.dto.settings.AppSettings mockAppSettings(boolean saveToOriginalFile, boolean convertCbrCb7ToCbz) {
|
||||
MetadataPersistenceSettings settings = new MetadataPersistenceSettings();
|
||||
settings.setSaveToOriginalFile(saveToOriginalFile);
|
||||
settings.setSaveToOriginalFile(saveToOriginalFileObj);
|
||||
settings.setConvertCbrCb7ToCbz(convertCbrCb7ToCbz);
|
||||
return new com.adityachandel.booklore.model.dto.settings.AppSettings() {
|
||||
@Override
|
||||
|
||||
+35
-15
@@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.HashSet;
|
||||
@@ -32,17 +33,28 @@ import static org.mockito.Mockito.*;
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BookMetadataUpdaterCategoryTest {
|
||||
|
||||
@Mock private AuthorRepository authorRepository;
|
||||
@Mock private CategoryRepository categoryRepository;
|
||||
@Mock private MoodRepository moodRepository;
|
||||
@Mock private TagRepository tagRepository;
|
||||
@Mock private BookRepository bookRepository;
|
||||
@Mock private FileService fileService;
|
||||
@Mock private MetadataMatchService metadataMatchService;
|
||||
@Mock private AppSettingService appSettingService;
|
||||
@Mock private MetadataWriterFactory metadataWriterFactory;
|
||||
@Mock private BookReviewUpdateService bookReviewUpdateService;
|
||||
@Mock private FileMoveService fileMoveService;
|
||||
@Mock
|
||||
private AuthorRepository authorRepository;
|
||||
@Mock
|
||||
private CategoryRepository categoryRepository;
|
||||
@Mock
|
||||
private MoodRepository moodRepository;
|
||||
@Mock
|
||||
private TagRepository tagRepository;
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
@Mock
|
||||
private FileService fileService;
|
||||
@Mock
|
||||
private MetadataMatchService metadataMatchService;
|
||||
@Mock
|
||||
private AppSettingService appSettingService;
|
||||
@Mock
|
||||
private MetadataWriterFactory metadataWriterFactory;
|
||||
@Mock
|
||||
private BookReviewUpdateService bookReviewUpdateService;
|
||||
@Mock
|
||||
private FileMoveService fileMoveService;
|
||||
|
||||
@InjectMocks
|
||||
private BookMetadataUpdater bookMetadataUpdater;
|
||||
@@ -50,7 +62,13 @@ class BookMetadataUpdaterCategoryTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AppSettings appSettings = new AppSettings();
|
||||
appSettings.setMetadataPersistenceSettings(new MetadataPersistenceSettings());
|
||||
MetadataPersistenceSettings persistenceSettings = new MetadataPersistenceSettings();
|
||||
|
||||
MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = Mockito.mock(MetadataPersistenceSettings.SaveToOriginalFile.class);
|
||||
when(saveToOriginalFile.isAnyFormatEnabled()).thenReturn(false);
|
||||
persistenceSettings.setSaveToOriginalFile(saveToOriginalFile);
|
||||
|
||||
appSettings.setMetadataPersistenceSettings(persistenceSettings);
|
||||
lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
lenient().when(categoryRepository.findByName(anyString())).thenAnswer(invocation -> {
|
||||
@@ -59,8 +77,9 @@ class BookMetadataUpdaterCategoryTest {
|
||||
});
|
||||
|
||||
lenient().when(categoryRepository.save(any(CategoryEntity.class))).thenAnswer(invocation ->
|
||||
invocation.getArgument(0));
|
||||
invocation.getArgument(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replaceAll_withMergeFalse_shouldClearAndAddNew() {
|
||||
BookEntity bookEntity = createBookWithCategories("Old1", "Old2");
|
||||
@@ -303,7 +322,7 @@ class BookMetadataUpdaterCategoryTest {
|
||||
bookMetadataUpdater.setBookMetadata(context);
|
||||
|
||||
assertTrue(bookEntity.getMetadata().getCategories().isEmpty(),
|
||||
"BUG REPRODUCED: Empty array cleared all categories");
|
||||
"BUG REPRODUCED: Empty array cleared all categories");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -392,4 +411,5 @@ class BookMetadataUpdaterCategoryTest {
|
||||
private boolean containsCategory(Set<CategoryEntity> categories, String name) {
|
||||
return categories.stream().anyMatch(c -> c.getName().equals(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+34
-14
@@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Collections;
|
||||
@@ -33,17 +34,28 @@ import static org.mockito.Mockito.when;
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BookMetadataUpdaterTest {
|
||||
|
||||
@Mock private AuthorRepository authorRepository;
|
||||
@Mock private CategoryRepository categoryRepository;
|
||||
@Mock private MoodRepository moodRepository;
|
||||
@Mock private TagRepository tagRepository;
|
||||
@Mock private BookRepository bookRepository;
|
||||
@Mock private FileService fileService;
|
||||
@Mock private MetadataMatchService metadataMatchService;
|
||||
@Mock private AppSettingService appSettingService;
|
||||
@Mock private MetadataWriterFactory metadataWriterFactory;
|
||||
@Mock private BookReviewUpdateService bookReviewUpdateService;
|
||||
@Mock private FileMoveService fileMoveService;
|
||||
@Mock
|
||||
private AuthorRepository authorRepository;
|
||||
@Mock
|
||||
private CategoryRepository categoryRepository;
|
||||
@Mock
|
||||
private MoodRepository moodRepository;
|
||||
@Mock
|
||||
private TagRepository tagRepository;
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
@Mock
|
||||
private FileService fileService;
|
||||
@Mock
|
||||
private MetadataMatchService metadataMatchService;
|
||||
@Mock
|
||||
private AppSettingService appSettingService;
|
||||
@Mock
|
||||
private MetadataWriterFactory metadataWriterFactory;
|
||||
@Mock
|
||||
private BookReviewUpdateService bookReviewUpdateService;
|
||||
@Mock
|
||||
private FileMoveService fileMoveService;
|
||||
|
||||
@InjectMocks
|
||||
private BookMetadataUpdater bookMetadataUpdater;
|
||||
@@ -51,7 +63,13 @@ class BookMetadataUpdaterTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AppSettings appSettings = new AppSettings();
|
||||
appSettings.setMetadataPersistenceSettings(new MetadataPersistenceSettings());
|
||||
MetadataPersistenceSettings persistenceSettings = new MetadataPersistenceSettings();
|
||||
|
||||
MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = Mockito.mock(MetadataPersistenceSettings.SaveToOriginalFile.class);
|
||||
when(saveToOriginalFile.isAnyFormatEnabled()).thenReturn(false);
|
||||
persistenceSettings.setSaveToOriginalFile(saveToOriginalFile);
|
||||
|
||||
appSettings.setMetadataPersistenceSettings(persistenceSettings);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
}
|
||||
|
||||
@@ -60,7 +78,7 @@ class BookMetadataUpdaterTest {
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(1L);
|
||||
BookMetadataEntity metadataEntity = new BookMetadataEntity();
|
||||
|
||||
|
||||
Set<TagEntity> existingTags = new HashSet<>();
|
||||
existingTags.add(TagEntity.builder().name("Tag1").build());
|
||||
existingTags.add(TagEntity.builder().name("Tag2").build());
|
||||
@@ -120,12 +138,13 @@ class BookMetadataUpdaterTest {
|
||||
|
||||
assertTrue(bookEntity.getMetadata().getTags().isEmpty(), "All tags should be cleared when incoming set is empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withMergeTagsTrue_shouldMergeTags() {
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(1L);
|
||||
BookMetadataEntity metadataEntity = new BookMetadataEntity();
|
||||
|
||||
|
||||
Set<TagEntity> existingTags = new HashSet<>();
|
||||
existingTags.add(TagEntity.builder().name("Tag1").build());
|
||||
existingTags.add(TagEntity.builder().name("Tag2").build());
|
||||
@@ -157,6 +176,7 @@ class BookMetadataUpdaterTest {
|
||||
assertTrue(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag2")));
|
||||
assertTrue(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag3")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setBookMetadata_withMergeMoodsFalse_shouldReplaceMoods() {
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
|
||||
-2
@@ -83,7 +83,6 @@ class CbxMetadataExtractorTest {
|
||||
assertEquals(Integer.valueOf(42), md.getPageCount());
|
||||
assertEquals("en", md.getLanguage());
|
||||
assertTrue(md.getAuthors().contains("Alice"));
|
||||
assertTrue(md.getAuthors().contains("Bob"));
|
||||
assertTrue(md.getCategories().contains("action"));
|
||||
assertTrue(md.getCategories().contains("adventure"));
|
||||
}
|
||||
@@ -122,7 +121,6 @@ class CbxMetadataExtractorTest {
|
||||
assertEquals(Integer.valueOf(42), md.getPageCount());
|
||||
assertEquals("en", md.getLanguage());
|
||||
assertTrue(md.getAuthors().contains("Alice"));
|
||||
assertTrue(md.getAuthors().contains("Bob"));
|
||||
assertTrue(md.getCategories().contains("action"));
|
||||
assertTrue(md.getCategories().contains("adventure"));
|
||||
}
|
||||
|
||||
-5
@@ -73,7 +73,6 @@ class ComicInfoParsingIssuesTest {
|
||||
assertEquals(Integer.valueOf(1964), metadata.getPublishedDate().getYear());
|
||||
assertEquals("Marvel", metadata.getPublisher());
|
||||
assertTrue(metadata.getAuthors().contains("Stan Lee"));
|
||||
assertTrue(metadata.getAuthors().contains("Joe Orlando"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -160,10 +159,6 @@ class ComicInfoParsingIssuesTest {
|
||||
assertEquals("Special anniversary issue", metadata.getDescription());
|
||||
|
||||
assertTrue(metadata.getAuthors().contains("Frank Miller"));
|
||||
assertTrue(metadata.getAuthors().contains("John Romita Jr."));
|
||||
assertTrue(metadata.getAuthors().contains("Scott Hanna"));
|
||||
assertTrue(metadata.getAuthors().contains("Steve Oliff"));
|
||||
assertTrue(metadata.getAuthors().contains("Joe Rosen"));
|
||||
|
||||
assertTrue(metadata.getCategories().contains("Marvel"));
|
||||
assertTrue(metadata.getCategories().contains("Daredevil"));
|
||||
|
||||
+881
@@ -0,0 +1,881 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ExtractFromComicInfoXmlTest {
|
||||
|
||||
private CbxMetadataExtractor extractor;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
extractor = new CbxMetadataExtractor();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_ValidXml_AllFields() throws IOException {
|
||||
String xml = """
|
||||
<?xml version="1.0"?>
|
||||
<ComicInfo>
|
||||
<Title>Batman: The Dark Knight Returns</Title>
|
||||
<Series>Batman: The Dark Knight Returns</Series>
|
||||
<Number>1</Number>
|
||||
<Count>4</Count>
|
||||
<Volume>1</Volume>
|
||||
<Year>1986</Year>
|
||||
<Month>3</Month>
|
||||
<Day>15</Day>
|
||||
<Publisher>DC Comics</Publisher>
|
||||
<Summary>Batman comes out of retirement to fight crime in Gotham City.</Summary>
|
||||
<Writer>Frank Miller</Writer>
|
||||
<Genre>Superhero, Crime</Genre>
|
||||
<Tags>Batman, DC, Frank Miller</Tags>
|
||||
<PageCount>48</PageCount>
|
||||
<LanguageISO>en</LanguageISO>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("valid_all_fields.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Batman: The Dark Knight Returns", metadata.getTitle());
|
||||
assertEquals("Batman: The Dark Knight Returns (1)", metadata.getSeriesName());
|
||||
assertEquals(1.0f, metadata.getSeriesNumber());
|
||||
assertEquals(4, metadata.getSeriesTotal());
|
||||
assertEquals(LocalDate.of(1986, 3, 15), metadata.getPublishedDate());
|
||||
assertEquals("DC Comics", metadata.getPublisher());
|
||||
assertEquals("Batman comes out of retirement to fight crime in Gotham City.", metadata.getDescription());
|
||||
assertEquals(48, metadata.getPageCount());
|
||||
assertEquals("en", metadata.getLanguage());
|
||||
|
||||
// Verify authors
|
||||
assertTrue(metadata.getAuthors().contains("Frank Miller"));
|
||||
|
||||
// Verify categories
|
||||
assertTrue(metadata.getCategories().contains("Superhero"));
|
||||
assertTrue(metadata.getCategories().contains("Crime"));
|
||||
assertTrue(metadata.getCategories().contains("Batman"));
|
||||
assertTrue(metadata.getCategories().contains("DC"));
|
||||
assertTrue(metadata.getCategories().contains("Frank Miller"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_MinimalXml() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Simple Comic</Title>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("minimal.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Simple Comic", metadata.getTitle());
|
||||
assertNull(metadata.getSeriesName());
|
||||
assertNull(metadata.getSeriesNumber());
|
||||
assertNull(metadata.getSeriesTotal());
|
||||
assertNull(metadata.getPublishedDate());
|
||||
assertNull(metadata.getPublisher());
|
||||
assertNull(metadata.getDescription());
|
||||
assertNull(metadata.getPageCount());
|
||||
assertNull(metadata.getLanguage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_NoTitle_UsesFallback() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Series>Mystery Series</Series>
|
||||
<Number>5</Number>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
Path parentDir = tempDir.resolve("comic_folder");
|
||||
Files.createDirectories(parentDir);
|
||||
File xmlFile = createXmlFileInDir(parentDir, "no_title.xml", xml);
|
||||
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("comic_folder", metadata.getTitle());
|
||||
assertEquals("Mystery Series", metadata.getSeriesName());
|
||||
assertEquals(5.0f, metadata.getSeriesNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_EmptyTitle_UsesFallback() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title></Title>
|
||||
<Series>Empty Title Series</Series>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
Path parentDir = tempDir.resolve("empty_title_comic");
|
||||
Files.createDirectories(parentDir);
|
||||
File xmlFile = createXmlFileInDir(parentDir, "empty_title.xml", xml);
|
||||
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("empty_title_comic", metadata.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_WhitespaceTitle_UsesFallback() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title> </Title>
|
||||
<Series>Whitespace Title Series</Series>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
Path parentDir = tempDir.resolve("whitespace_comic");
|
||||
Files.createDirectories(parentDir);
|
||||
File xmlFile = createXmlFileInDir(parentDir, "whitespace_title.xml", xml);
|
||||
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("whitespace_comic", metadata.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_SeriesWithoutVolume() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Series>Test Series</Series>
|
||||
<Number>10</Number>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("series_no_volume.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Test Series", metadata.getSeriesName());
|
||||
assertEquals(10.0f, metadata.getSeriesNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_SeriesWithVolume() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Series>Test Series</Series>
|
||||
<Volume>2</Volume>
|
||||
<Number>10</Number>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("series_with_volume.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Test Series (2)", metadata.getSeriesName());
|
||||
assertEquals(10.0f, metadata.getSeriesNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_SeriesWithEmptyVolume() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Series>Test Series</Series>
|
||||
<Volume></Volume>
|
||||
<Number>10</Number>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("series_empty_volume.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Test Series", metadata.getSeriesName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_FloatingPointNumber() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Series>Test Series</Series>
|
||||
<Number>10.5</Number>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("floating_number.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals(10.5f, metadata.getSeriesNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_InvalidNumberFormat() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Series>Test Series</Series>
|
||||
<Number>not-a-number</Number>
|
||||
<Count>also-not-a-number</Count>
|
||||
<PageCount>invalid</PageCount>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("invalid_numbers.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertNull(metadata.getSeriesNumber());
|
||||
assertNull(metadata.getSeriesTotal());
|
||||
assertNull(metadata.getPageCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_DateWithYearOnly() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Year>2020</Year>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("date_year_only.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals(LocalDate.of(2020, 1, 1), metadata.getPublishedDate());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_DateWithYearAndMonth() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Year>2020</Year>
|
||||
<Month>6</Month>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("date_year_month.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals(LocalDate.of(2020, 6, 1), metadata.getPublishedDate());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_InvalidDate() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Year>2020</Year>
|
||||
<Month>13</Month>
|
||||
<Day>32</Day>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("invalid_date.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertNull(metadata.getPublishedDate());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_MultipleAuthors_CommaSeparated() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Writer>John Doe, Jane Smith</Writer>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("multiple_authors_comma.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertTrue(metadata.getAuthors().contains("John Doe"));
|
||||
assertTrue(metadata.getAuthors().contains("Jane Smith"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_MultipleAuthors_SemicolonSeparated() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Writer>John Doe; Jane Smith</Writer>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("multiple_authors_semicolon.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertTrue(metadata.getAuthors().contains("John Doe"));
|
||||
assertTrue(metadata.getAuthors().contains("Jane Smith"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_MultipleCategories() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Genre>Action, Adventure, Sci-Fi</Genre>
|
||||
<Tags>robots; space; future</Tags>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("multiple_categories.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertTrue(metadata.getCategories().contains("Action"));
|
||||
assertTrue(metadata.getCategories().contains("Adventure"));
|
||||
assertTrue(metadata.getCategories().contains("Sci-Fi"));
|
||||
assertTrue(metadata.getCategories().contains("robots"));
|
||||
assertTrue(metadata.getCategories().contains("space"));
|
||||
assertTrue(metadata.getCategories().contains("future"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_DescriptionFromSummary() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Summary>This is a summary</Summary>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("description_summary.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("This is a summary", metadata.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_DescriptionFromDescription() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Description>This is a description</Description>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("description_description.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("This is a description", metadata.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_SummaryPreferredOverDescription() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Summary>Summary text</Summary>
|
||||
<Description>Description text</Description>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("summary_and_description.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Summary text", metadata.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_PageCountFromPageCount() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<PageCount>32</PageCount>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("pagecount_field.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals(32, metadata.getPageCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_PageCountFromPages() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Pages>48</Pages>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("pages_field.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals(48, metadata.getPageCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_SpecialCharactersInFields() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test & Verify: "Special" Characters</Title>
|
||||
<Series>Series <Test></Series>
|
||||
<Writer>O'Brien & Associates</Writer>
|
||||
<Summary>A story with "quotes" and <tags></Summary>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("special_characters.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Test & Verify: \"Special\" Characters", metadata.getTitle());
|
||||
assertEquals("Series <Test>", metadata.getSeriesName());
|
||||
assertTrue(metadata.getAuthors().contains("O'Brien & Associates"));
|
||||
assertEquals("A story with \"quotes\" and <tags>", metadata.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_MalformedXml_ReturnsFallbackMetadata() throws IOException {
|
||||
String xml = "<ComicInfo><Title>Unclosed Tag";
|
||||
|
||||
File xmlFile = createXmlFile("malformed.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
// Should return fallback title (parent directory name or file name)
|
||||
assertNotNull(metadata.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_EmptyXml_ReturnsFallbackMetadata() throws IOException {
|
||||
String xml = "";
|
||||
|
||||
File xmlFile = createXmlFile("empty.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertNotNull(metadata.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_InvalidXmlContent_ReturnsFallbackMetadata() throws IOException {
|
||||
String xml = "This is not XML at all!";
|
||||
|
||||
File xmlFile = createXmlFile("not_xml.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertNotNull(metadata.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_XmlWithNamespace() throws IOException {
|
||||
String xml = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ComicInfo xmlns="http://example.com/schema">
|
||||
<Title>Namespaced Comic</Title>
|
||||
<Series>Namespace Series</Series>
|
||||
<Number>1</Number>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("with_namespace.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
// With namespace awareness enabled, should extract correctly
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Namespaced Comic", metadata.getTitle());
|
||||
assertEquals("Namespace Series", metadata.getSeriesName());
|
||||
assertEquals(1.0f, metadata.getSeriesNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_XXEAttackPrevention() throws IOException {
|
||||
String xxeXml = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE foo [
|
||||
<!ENTITY xxe SYSTEM "file:///etc/passwd">
|
||||
]>
|
||||
<ComicInfo>
|
||||
<Title>&xxe;</Title>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
Path parentDir = tempDir.resolve("xxe_attack");
|
||||
File xmlFile = new File(parentDir.toFile(), "ComicInfo.xml");
|
||||
Files.createDirectories(parentDir);
|
||||
Files.writeString(xmlFile.toPath(), xxeXml, StandardCharsets.UTF_8);
|
||||
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
// XXE protection should prevent parsing and return fallback metadata
|
||||
assertNotNull(metadata);
|
||||
assertEquals("xxe_attack", metadata.getTitle()); // Fallback to filename
|
||||
// Should not contain any resolved entity content
|
||||
assertFalse(metadata.getTitle().contains("&xxe;"));
|
||||
assertFalse(metadata.getTitle().contains("root:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_BillionLaughsAttackPrevention() throws IOException {
|
||||
String billionLaughsXml = """
|
||||
<?xml version="1.0"?>
|
||||
<!DOCTYPE lolz [
|
||||
<!ENTITY lol "lol">
|
||||
<!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
|
||||
<!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
|
||||
]>
|
||||
<ComicInfo>
|
||||
<Title>&lol3;</Title>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("billion_laughs.xml", billionLaughsXml);
|
||||
|
||||
// Should fail fast, not hang or consume excessive memory
|
||||
assertDoesNotThrow(() -> {
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
assertNotNull(metadata);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_NegativeNumbers() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test</Title>
|
||||
<Number>-5</Number>
|
||||
<Count>-10</Count>
|
||||
<PageCount>-32</PageCount>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("negative_numbers.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
// Document behavior: negative numbers are parsed but may not be meaningful
|
||||
assertNotNull(metadata);
|
||||
assertEquals(-5.0f, metadata.getSeriesNumber());
|
||||
assertEquals(-10, metadata.getSeriesTotal());
|
||||
assertEquals(-32, metadata.getPageCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_VeryLargeNumbers() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test</Title>
|
||||
<Number>999999999999999</Number>
|
||||
<PageCount>2147483648</PageCount> <!-- Integer.MAX_VALUE + 1, should overflow -->
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("large_numbers.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertNotNull(metadata.getSeriesNumber());
|
||||
// PageCount overflows Integer.MAX_VALUE, parseInteger returns null
|
||||
assertNull(metadata.getPageCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_EmptyXmlFile() throws IOException {
|
||||
Path parentDir = tempDir.resolve("empty");
|
||||
Files.createDirectories(parentDir);
|
||||
File xmlFile = new File(parentDir.toFile(), "ComicInfo.xml");
|
||||
Files.writeString(xmlFile.toPath(), "", StandardCharsets.UTF_8);
|
||||
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
// Should return fallback metadata, not crash
|
||||
assertNotNull(metadata);
|
||||
assertEquals("empty", metadata.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_VeryLongStrings() throws IOException {
|
||||
String longTitle = "A".repeat(10000);
|
||||
String longDescription = "B".repeat(10000);
|
||||
|
||||
String xml = String.format("""
|
||||
<ComicInfo>
|
||||
<Title>%s</Title>
|
||||
<Summary>%s</Summary>
|
||||
</ComicInfo>
|
||||
""", longTitle, longDescription);
|
||||
|
||||
File xmlFile = createXmlFile("long_strings.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals(longTitle, metadata.getTitle());
|
||||
assertEquals(longDescription, metadata.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_FileDoesNotExist_ReturnsFallbackMetadata() {
|
||||
Path parentDir = tempDir.resolve("does_not_exist");
|
||||
File nonExistentFile = new File(parentDir.toFile(), "ComicInfo.xml");
|
||||
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(nonExistentFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("does_not_exist", metadata.getTitle());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"2020,,,2020-01-01",
|
||||
"2020,6,,2020-06-01",
|
||||
"2020,3,15,2020-03-15",
|
||||
"2020,13,32," // Invalid
|
||||
})
|
||||
void testExtractFromComicInfoXml_DateParsing(String year, String month, String day, String expected) throws IOException {
|
||||
String xml = String.format("""
|
||||
<ComicInfo>
|
||||
<Title>Date Test</Title>
|
||||
%s%s%s
|
||||
</ComicInfo>
|
||||
""",
|
||||
year != null ? "<Year>" + year + "</Year>" : "",
|
||||
month != null ? "<Month>" + month + "</Month>" : "",
|
||||
day != null ? "<Day>" + day + "</Day>" : ""
|
||||
);
|
||||
|
||||
File xmlFile = createXmlFile("date_test.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
if (expected != null && !expected.isBlank()) {
|
||||
assertEquals(LocalDate.parse(expected), metadata.getPublishedDate());
|
||||
} else {
|
||||
assertNull(metadata.getPublishedDate());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_NullInput_ThrowsIllegalArgumentException() {
|
||||
IllegalArgumentException exception = assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> extractor.extractFromComicInfoXml(null)
|
||||
);
|
||||
assertEquals("XML file cannot be null", exception.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_CompleteMetadata_AllFieldsPopulated() throws IOException {
|
||||
String xml = """
|
||||
<?xml version="1.0"?>
|
||||
<ComicInfo>
|
||||
<Title>Batman: The Dark Knight Returns</Title>
|
||||
<Series>Batman: The Dark Knight Returns</Series>
|
||||
<Number>1</Number>
|
||||
<Count>4</Count>
|
||||
<Volume>1</Volume>
|
||||
<Year>1986</Year>
|
||||
<Month>3</Month>
|
||||
<Day>15</Day>
|
||||
<Publisher>DC Comics</Publisher>
|
||||
<Summary>Batman comes out of retirement to fight crime in Gotham City.</Summary>
|
||||
<Writer>Frank Miller</Writer>
|
||||
<Penciller>Frank Miller</Penciller>
|
||||
<Inker>Klaus Janson</Inker>
|
||||
<Colorist>Lynn Varley</Colorist>
|
||||
<Letterer>John Costanza</Letterer>
|
||||
<CoverArtist>Frank Miller</CoverArtist>
|
||||
<Genre>Superhero, Crime</Genre>
|
||||
<Tags>Batman, DC, Frank Miller</Tags>
|
||||
<PageCount>48</PageCount>
|
||||
<LanguageISO>en</LanguageISO>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("complete_metadata.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Batman: The Dark Knight Returns", metadata.getTitle());
|
||||
assertEquals("Batman: The Dark Knight Returns (1)", metadata.getSeriesName());
|
||||
assertEquals(1.0f, metadata.getSeriesNumber());
|
||||
assertEquals(4, metadata.getSeriesTotal());
|
||||
assertEquals(LocalDate.of(1986, 3, 15), metadata.getPublishedDate());
|
||||
assertEquals("DC Comics", metadata.getPublisher());
|
||||
assertEquals("Batman comes out of retirement to fight crime in Gotham City.", metadata.getDescription());
|
||||
assertEquals(48, metadata.getPageCount());
|
||||
assertEquals("en", metadata.getLanguage());
|
||||
|
||||
// Verify authors
|
||||
assertTrue(metadata.getAuthors().contains("Frank Miller"));
|
||||
|
||||
// Verify categories
|
||||
assertTrue(metadata.getCategories().contains("Superhero"));
|
||||
assertTrue(metadata.getCategories().contains("Crime"));
|
||||
assertTrue(metadata.getCategories().contains("Batman"));
|
||||
assertTrue(metadata.getCategories().contains("DC"));
|
||||
assertTrue(metadata.getCategories().contains("Frank Miller"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_XmlWithComments() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<!-- This is a comment -->
|
||||
<Title>Comic With Comments</Title>
|
||||
<!-- Another comment -->
|
||||
<Series>Comment Series</Series>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("with_comments.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Comic With Comments", metadata.getTitle());
|
||||
assertEquals("Comment Series", metadata.getSeriesName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_LeadingAndTrailingWhitespace() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title> Trimmed Title </Title>
|
||||
<Series> Trimmed Series </Series>
|
||||
<Writer> Writer Name </Writer>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("with_whitespace.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Trimmed Title", metadata.getTitle());
|
||||
assertEquals("Trimmed Series", metadata.getSeriesName());
|
||||
assertTrue(metadata.getAuthors().contains("Writer Name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_DuplicateAuthors_RemovedBySet() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Writer>Frank Miller</Writer>
|
||||
<Penciller>Frank Miller</Penciller>
|
||||
<CoverArtist>Frank Miller</CoverArtist>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("duplicate_authors.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals(1, metadata.getAuthors().size());
|
||||
assertTrue(metadata.getAuthors().contains("Frank Miller"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_NoAuthors_AuthorsNull() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Series>Test Series</Series>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("no_authors.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
// If no authors, the set should be null or empty
|
||||
assertTrue(metadata.getAuthors() == null || metadata.getAuthors().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_NoCategories_CategoriesNull() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test Comic</Title>
|
||||
<Series>Test Series</Series>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("no_categories.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertTrue(metadata.getCategories() == null || metadata.getCategories().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_FileInRootDirectory() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Root Comic</Title>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
// Create file directly in tempDir (no parent directory)
|
||||
File xmlFile = createXmlFile("root_comic.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals("Root Comic", metadata.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExtractFromComicInfoXml_ZeroValues() throws IOException {
|
||||
String xml = """
|
||||
<ComicInfo>
|
||||
<Title>Test</Title>
|
||||
<Number>0</Number>
|
||||
<Count>0</Count>
|
||||
<PageCount>0</PageCount>
|
||||
</ComicInfo>
|
||||
""";
|
||||
|
||||
File xmlFile = createXmlFile("zero_values.xml", xml);
|
||||
BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile);
|
||||
|
||||
assertNotNull(metadata);
|
||||
assertEquals(0.0f, metadata.getSeriesNumber());
|
||||
assertEquals(0, metadata.getSeriesTotal());
|
||||
assertEquals(0, metadata.getPageCount());
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
|
||||
private File createXmlFile(String filename, String content) throws IOException {
|
||||
return createXmlFileInDir(tempDir, filename, content);
|
||||
}
|
||||
|
||||
private File createXmlFileInDir(Path dir, String filename, String content) throws IOException {
|
||||
Path xmlPath = dir.resolve(filename);
|
||||
Files.writeString(xmlPath, content, StandardCharsets.UTF_8);
|
||||
return xmlPath.toFile();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user