Merge pull request #2989 from booklore-app/develop
Merge develop into master for the release
This commit is contained in:
@@ -29,10 +29,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set Up JDK 25
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
@@ -47,14 +47,14 @@ jobs:
|
||||
continue-on-error: true
|
||||
|
||||
- name: Publish Backend Test Results
|
||||
uses: EnricoMi/publish-unit-test-result-action@v2
|
||||
uses: EnricoMi/publish-unit-test-result-action@c950f6fb443cb5af20a377fd0dfaa78838901040 # v2
|
||||
if: always()
|
||||
with:
|
||||
files: booklore-api/build/test-results/**/*.xml
|
||||
check_name: Backend Test Results
|
||||
|
||||
- name: Upload Backend Test Reports
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||
if: always()
|
||||
with:
|
||||
name: backend-test-reports
|
||||
@@ -82,18 +82,27 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set Up Node.js
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: booklore-ui/package-lock.json
|
||||
|
||||
- name: Install Frontend Dependencies
|
||||
working-directory: ./booklore-ui
|
||||
run: npm ci --force
|
||||
run: npm ci
|
||||
|
||||
- name: Audit Frontend Dependencies
|
||||
working-directory: ./booklore-ui
|
||||
run: npm audit --audit-level=high
|
||||
|
||||
- name: Validate Dependency Tree
|
||||
working-directory: ./booklore-ui
|
||||
run: npm ls --depth=0
|
||||
|
||||
|
||||
- name: Execute Frontend Tests
|
||||
id: frontend_tests
|
||||
@@ -104,14 +113,14 @@ jobs:
|
||||
continue-on-error: true
|
||||
|
||||
- name: Publish Frontend Test Results
|
||||
uses: EnricoMi/publish-unit-test-result-action@v2
|
||||
uses: EnricoMi/publish-unit-test-result-action@c950f6fb443cb5af20a377fd0dfaa78838901040 # 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
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||
if: always()
|
||||
with:
|
||||
name: frontend-test-reports
|
||||
@@ -136,7 +145,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -161,15 +170,24 @@ jobs:
|
||||
# Native Angular build
|
||||
# ----------------------------------------
|
||||
- name: Set Up Node.js
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: booklore-ui/package-lock.json
|
||||
|
||||
- name: Install Frontend Dependencies
|
||||
working-directory: ./booklore-ui
|
||||
run: npm ci --force
|
||||
run: npm ci
|
||||
|
||||
- name: Audit Frontend Dependencies
|
||||
working-directory: ./booklore-ui
|
||||
run: npm audit --audit-level=high
|
||||
|
||||
- name: Validate Dependency Tree
|
||||
working-directory: ./booklore-ui
|
||||
run: npm ls --depth=0
|
||||
|
||||
|
||||
- name: Build Angular App
|
||||
working-directory: ./booklore-ui
|
||||
@@ -179,7 +197,7 @@ jobs:
|
||||
# Native Gradle build
|
||||
# ----------------------------------------
|
||||
- name: Set Up JDK 25
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
@@ -204,24 +222,24 @@ jobs:
|
||||
# Environment setup
|
||||
# ----------------------------------------
|
||||
- name: Set Up QEMU for Multi-Arch Builds
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
|
||||
|
||||
- name: Set Up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
||||
|
||||
# ----------------------------------------
|
||||
# Docker login (pushes & internal PRs only)
|
||||
# ----------------------------------------
|
||||
- name: Authenticate to Docker Hub
|
||||
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Authenticate to GitHub Container Registry
|
||||
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
@@ -232,7 +250,7 @@ jobs:
|
||||
# ----------------------------------------
|
||||
- name: Build and push Docker image
|
||||
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.ci
|
||||
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
base_ref: ${{ steps.get_base.outputs.base_ref }}
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 2
|
||||
- name: Get Base Ref
|
||||
@@ -41,10 +41,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set Up JDK 25
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
@@ -59,14 +59,14 @@ jobs:
|
||||
continue-on-error: true
|
||||
|
||||
- name: Publish Backend Test Results
|
||||
uses: EnricoMi/publish-unit-test-result-action@v2
|
||||
uses: EnricoMi/publish-unit-test-result-action@c950f6fb443cb5af20a377fd0dfaa78838901040 # v2
|
||||
if: always()
|
||||
with:
|
||||
files: booklore-api/build/test-results/**/*.xml
|
||||
check_name: Backend Test Results
|
||||
|
||||
- name: Upload Backend Test Reports
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||
if: always()
|
||||
with:
|
||||
name: backend-test-reports
|
||||
@@ -94,18 +94,27 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
|
||||
- name: Set Up Node.js
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: booklore-ui/package-lock.json
|
||||
|
||||
- name: Install Frontend Dependencies
|
||||
working-directory: ./booklore-ui
|
||||
run: npm ci --force
|
||||
run: npm ci
|
||||
|
||||
- name: Audit Frontend Dependencies
|
||||
working-directory: ./booklore-ui
|
||||
run: npm audit --audit-level=high
|
||||
|
||||
- name: Validate Dependency Tree
|
||||
working-directory: ./booklore-ui
|
||||
run: npm ls --depth=0
|
||||
|
||||
|
||||
- name: Execute Frontend Tests
|
||||
id: frontend_tests
|
||||
@@ -116,14 +125,14 @@ jobs:
|
||||
continue-on-error: true
|
||||
|
||||
- name: Publish Frontend Test Results
|
||||
uses: EnricoMi/publish-unit-test-result-action@v2
|
||||
uses: EnricoMi/publish-unit-test-result-action@c950f6fb443cb5af20a377fd0dfaa78838901040 # 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
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||
if: always()
|
||||
with:
|
||||
name: frontend-test-reports
|
||||
@@ -148,28 +157,28 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Authenticate to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Authenticate to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ github.token }}
|
||||
|
||||
- name: Set Up QEMU for Multi-Architecture Builds
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
|
||||
|
||||
- name: Set Up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
||||
|
||||
- name: Retrieve Latest Master Version Tag
|
||||
id: get_version
|
||||
@@ -238,15 +247,24 @@ jobs:
|
||||
# Native Angular build
|
||||
# ----------------------------------------
|
||||
- name: Set Up Node.js
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: booklore-ui/package-lock.json
|
||||
|
||||
- name: Install Frontend Dependencies
|
||||
working-directory: ./booklore-ui
|
||||
run: npm ci --force
|
||||
run: npm ci
|
||||
|
||||
- name: Audit Frontend Dependencies
|
||||
working-directory: ./booklore-ui
|
||||
run: npm audit --audit-level=high
|
||||
|
||||
- name: Validate Dependency Tree
|
||||
working-directory: ./booklore-ui
|
||||
run: npm ls --depth=0
|
||||
|
||||
|
||||
- name: Build Angular App
|
||||
working-directory: ./booklore-ui
|
||||
@@ -256,7 +274,7 @@ jobs:
|
||||
# Native Gradle build
|
||||
# ----------------------------------------
|
||||
- name: Set Up JDK 25
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5
|
||||
with:
|
||||
java-version: '25'
|
||||
distribution: 'temurin'
|
||||
@@ -281,7 +299,7 @@ jobs:
|
||||
# Docker build & push
|
||||
# ----------------------------------------
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.ci
|
||||
@@ -303,7 +321,7 @@ jobs:
|
||||
type=registry,ref=ghcr.io/booklore-app/booklore:buildcache,mode=max
|
||||
|
||||
- name: Update GitHub Release Draft
|
||||
uses: release-drafter/release-drafter@v6
|
||||
uses: release-drafter/release-drafter@6db134d15f3909ccc9eefd369f02bd1e9cffdf97 # v6
|
||||
with:
|
||||
tag: ${{ env.new_tag }}
|
||||
name: "Release ${{ env.new_tag }}"
|
||||
|
||||
@@ -24,7 +24,7 @@ jobs:
|
||||
has_migrations: ${{ steps.check_migrations.outputs.has_migrations }}
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -61,7 +61,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout Base Branch
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
ref: ${{ inputs.base_ref }}
|
||||
fetch-depth: 0
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
migrate
|
||||
|
||||
- name: Checkout Head Branch
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
|
||||
with:
|
||||
ref: ${{ inputs.head_ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
+6
-2
@@ -1,5 +1,5 @@
|
||||
# Stage 1: Build the Angular app
|
||||
FROM node:22-alpine AS angular-build
|
||||
FROM node:24-alpine AS angular-build
|
||||
|
||||
WORKDIR /angular-app
|
||||
|
||||
@@ -56,9 +56,13 @@ LABEL org.opencontainers.image.title="BookLore" \
|
||||
|
||||
ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+UseStringDeduplication -XX:+UseContainerSupport -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=75.0"
|
||||
|
||||
RUN apk update && apk add --no-cache su-exec && \
|
||||
ARG TARGETARCH
|
||||
RUN apk update && apk add --no-cache su-exec libstdc++ libgcc && \
|
||||
mkdir -p /bookdrop
|
||||
|
||||
COPY docker/unrar/unrar-${TARGETARCH} /usr/local/bin/unrar
|
||||
RUN chmod 755 /usr/local/bin/unrar
|
||||
|
||||
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/entrypoint.sh
|
||||
COPY --from=springboot-build /springboot-app/build/libs/booklore-api-0.0.1-SNAPSHOT.jar /app/app.jar
|
||||
|
||||
+5
-1
@@ -18,7 +18,11 @@ LABEL org.opencontainers.image.title="BookLore" \
|
||||
|
||||
ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+UseStringDeduplication -XX:+UseContainerSupport -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=75.0"
|
||||
|
||||
RUN apk update && apk add --no-cache su-exec
|
||||
ARG TARGETARCH
|
||||
RUN apk update && apk add --no-cache su-exec libstdc++ libgcc
|
||||
|
||||
COPY docker/unrar/unrar-${TARGETARCH} /usr/local/bin/unrar
|
||||
RUN chmod 755 /usr/local/bin/unrar
|
||||
|
||||
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/entrypoint.sh
|
||||
|
||||
@@ -3,21 +3,26 @@ package org.booklore.config;
|
||||
import org.booklore.config.security.interceptor.WebSocketAuthInterceptor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.messaging.simp.config.ChannelRegistration;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
|
||||
private final WebSocketAuthInterceptor webSocketAuthInterceptor;
|
||||
private final Environment env;
|
||||
|
||||
public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor) {
|
||||
public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor, Environment env) {
|
||||
this.webSocketAuthInterceptor = webSocketAuthInterceptor;
|
||||
this.env = env;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -29,8 +34,22 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
|
||||
@Override
|
||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||
registry.addEndpoint("/ws").setAllowedOrigins("*");
|
||||
log.info("WebSocket endpoint registered at /ws");
|
||||
String allowedOrigins = env.getProperty("app.cors.allowed-origins", "*").trim();
|
||||
var endpoint = registry.addEndpoint("/ws");
|
||||
if ("*".equals(allowedOrigins)) {
|
||||
endpoint.setAllowedOriginPatterns("*");
|
||||
log.warn("WebSocket endpoint is configured to allow all origins (*). " +
|
||||
"This is the default for backward compatibility, but it's recommended to set 'app.cors.allowed-origins' to an explicit list.");
|
||||
} else if (allowedOrigins.isEmpty()) {
|
||||
// No explicit origins configured: enforce same-origin check (Spring WebSocket default)
|
||||
log.info("WebSocket endpoint registered at /ws (same-origin only)");
|
||||
} else {
|
||||
String[] origins = Arrays.stream(allowedOrigins.split("\\s*,\\s*"))
|
||||
.filter(s -> !s.isEmpty())
|
||||
.toArray(String[]::new);
|
||||
endpoint.setAllowedOriginPatterns(origins);
|
||||
log.info("WebSocket endpoint registered at /ws with allowed origins: {}", Arrays.toString(origins));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -5,9 +5,11 @@ import org.booklore.config.security.service.OpdsUserDetailsService;
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.util.FileService;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
@@ -19,21 +21,41 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.SNIHostName;
|
||||
import javax.net.ssl.SSLParameters;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import java.net.InetAddress;
|
||||
import java.net.Socket;
|
||||
import java.util.Collections;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@EnableMethodSecurity
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
private static final Pattern ALLOWED = Pattern.compile("\\s*,\\s*");
|
||||
private final OpdsUserDetailsService opdsUserDetailsService;
|
||||
private final DualJwtAuthenticationFilter dualJwtAuthenticationFilter;
|
||||
private final Environment env;
|
||||
|
||||
private static final String[] COMMON_PUBLIC_ENDPOINTS = {
|
||||
"/ws/**", // WebSocket connections (auth handled in WebSocketAuthInterceptor)
|
||||
@@ -197,6 +219,10 @@ public class SecurityConfig {
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.headers(headers -> headers
|
||||
.referrerPolicy(referrer -> referrer.policy(
|
||||
ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll()
|
||||
.requestMatchers(publicEndpoints.toArray(new String[0])).permitAll()
|
||||
@@ -212,7 +238,11 @@ public class SecurityConfig {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
|
||||
.headers(headers -> headers
|
||||
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
|
||||
.referrerPolicy(referrer -> referrer.policy(
|
||||
ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
|
||||
return http.build();
|
||||
}
|
||||
@@ -224,10 +254,92 @@ public class SecurityConfig {
|
||||
return auth.build();
|
||||
}
|
||||
|
||||
@Bean("noRedirectRestTemplate")
|
||||
public RestTemplate noRedirectRestTemplate() {
|
||||
return new RestTemplate(
|
||||
new SimpleClientHttpRequestFactory() {
|
||||
@Override
|
||||
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
|
||||
super.prepareConnection(connection, httpMethod);
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
if (connection instanceof HttpsURLConnection httpsConnection) {
|
||||
String targetHost = FileService.getTargetHost();
|
||||
if (targetHost != null) {
|
||||
// Set original host for SNI (even if connecting to IP)
|
||||
SSLSocketFactory defaultFactory = httpsConnection.getSSLSocketFactory();
|
||||
httpsConnection.setSSLSocketFactory(new SniSSLSocketFactory(defaultFactory, targetHost));
|
||||
|
||||
httpsConnection.setHostnameVerifier((hostname, session) -> {
|
||||
String expectedHost = FileService.getTargetHost();
|
||||
if (expectedHost != null) {
|
||||
// Verify certificate against the original expected hostname, even if connecting via IP
|
||||
return HttpsURLConnection.getDefaultHostnameVerifier().verify(expectedHost, session);
|
||||
}
|
||||
// Fallback: use default verifier for the hostname we connected to
|
||||
return HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private static class SniSSLSocketFactory extends SSLSocketFactory {
|
||||
private final SSLSocketFactory delegate;
|
||||
private final String targetHost;
|
||||
|
||||
public SniSSLSocketFactory(SSLSocketFactory delegate, String targetHost) {
|
||||
this.delegate = delegate;
|
||||
this.targetHost = targetHost;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); }
|
||||
@Override
|
||||
public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); }
|
||||
|
||||
@Override
|
||||
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
|
||||
// Pass targetHost instead of host (which is the IP) so the internal SSLSession gets the correct peer host
|
||||
Socket socket = delegate.createSocket(s, targetHost, port, autoClose);
|
||||
if (socket instanceof SSLSocket sslSocket) {
|
||||
SNIHostName serverName = new SNIHostName(targetHost);
|
||||
SSLParameters params = sslSocket.getSSLParameters();
|
||||
params.setServerNames(Collections.singletonList(serverName));
|
||||
// Explicitly set EndpointIdentificationAlgorithm so Java verifies the certificate against targetHost
|
||||
params.setEndpointIdentificationAlgorithm("HTTPS");
|
||||
sslSocket.setSSLParameters(params);
|
||||
}
|
||||
return socket;
|
||||
}
|
||||
|
||||
@Override public Socket createSocket(String host, int port) throws IOException { return delegate.createSocket(host, port); }
|
||||
@Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { return delegate.createSocket(host, port, localHost, localPort); }
|
||||
@Override public Socket createSocket(InetAddress host, int port) throws IOException { return delegate.createSocket(host, port); }
|
||||
@Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return delegate.createSocket(address, port, localAddress, localPort); }
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowedOriginPatterns(List.of("*"));
|
||||
|
||||
String allowedOriginsStr = env.getProperty("app.cors.allowed-origins", "*").trim();
|
||||
if ("*".equals(allowedOriginsStr) || allowedOriginsStr.isEmpty()) {
|
||||
log.warn(
|
||||
"CORS is configured to allow all origins (*) because 'app.cors.allowed-origins' is '{}'. " +
|
||||
"This maintains backward compatibility, but it's recommended to set it to an explicit origin list.",
|
||||
allowedOriginsStr.isEmpty() ? "empty" : "*"
|
||||
);
|
||||
configuration.setAllowedOriginPatterns(List.of("*"));
|
||||
} else {
|
||||
List<String> origins = Arrays.stream(ALLOWED.split(allowedOriginsStr))
|
||||
.filter(s -> !s.isEmpty())
|
||||
.map(String::trim)
|
||||
.toList();
|
||||
configuration.setAllowedOriginPatterns(origins);
|
||||
}
|
||||
|
||||
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
||||
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type", "Range", "If-None-Match"));
|
||||
configuration.setExposedHeaders(List.of("Content-Disposition", "Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Date"));
|
||||
@@ -238,4 +350,4 @@ public class SecurityConfig {
|
||||
|
||||
return source;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+23
-3
@@ -23,6 +23,7 @@ public class AuthRateLimitService {
|
||||
public AuthRateLimitService(AuditService auditService) {
|
||||
this.auditService = auditService;
|
||||
this.attemptCache = Caffeine.newBuilder()
|
||||
.maximumSize(10000)
|
||||
.expireAfterWrite(Duration.ofMinutes(15))
|
||||
.build();
|
||||
}
|
||||
@@ -30,15 +31,30 @@ public class AuthRateLimitService {
|
||||
// --- Login rate limiting ---
|
||||
|
||||
public void checkLoginRateLimit(String ip) {
|
||||
checkRateLimit("login:" + ip, AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for IP: " + ip);
|
||||
checkRateLimit("login:ip:" + ip, AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for IP: " + ip);
|
||||
}
|
||||
|
||||
public void checkLoginRateLimitByUsername(String username) {
|
||||
String normalizedUsername = normalizeUsername(username);
|
||||
checkRateLimit("login:user:" + normalizedUsername, AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for username: " + normalizedUsername);
|
||||
}
|
||||
|
||||
public void recordFailedLoginAttempt(String ip) {
|
||||
recordFailedAttempt("login:" + ip);
|
||||
recordFailedAttempt("login:ip:" + ip);
|
||||
}
|
||||
|
||||
public void recordFailedLoginAttemptByUsername(String username) {
|
||||
String normalizedUsername = normalizeUsername(username);
|
||||
recordFailedAttempt("login:user:" + normalizedUsername);
|
||||
}
|
||||
|
||||
public void resetLoginAttempts(String ip) {
|
||||
resetAttempts("login:" + ip);
|
||||
resetAttempts("login:ip:" + ip);
|
||||
}
|
||||
|
||||
public void resetLoginAttemptsByUsername(String username) {
|
||||
String normalizedUsername = normalizeUsername(username);
|
||||
resetAttempts("login:user:" + normalizedUsername);
|
||||
}
|
||||
|
||||
// --- Refresh token rate limiting ---
|
||||
@@ -72,4 +88,8 @@ public class AuthRateLimitService {
|
||||
private void resetAttempts(String key) {
|
||||
attemptCache.invalidate(key);
|
||||
}
|
||||
|
||||
private String normalizeUsername(String username) {
|
||||
return username != null ? username.trim().toLowerCase() : "";
|
||||
}
|
||||
}
|
||||
|
||||
+25
-7
@@ -1,6 +1,7 @@
|
||||
package org.booklore.config.security.service;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.AppProperties;
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
@@ -31,10 +32,12 @@ import org.booklore.service.audit.AuditService;
|
||||
import org.booklore.util.RequestUtils;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class AuthenticationService {
|
||||
|
||||
private String dummyPasswordHash;
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final UserRepository userRepository;
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
@@ -45,6 +48,11 @@ public class AuthenticationService {
|
||||
private final AuditService auditService;
|
||||
private final AuthRateLimitService authRateLimitService;
|
||||
|
||||
@PostConstruct
|
||||
void initDummyHash() {
|
||||
this.dummyPasswordHash = passwordEncoder.encode("_dummy_placeholder_for_timing_equalization_");
|
||||
}
|
||||
|
||||
public BookLoreUser getAuthenticatedUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null) {
|
||||
@@ -93,21 +101,31 @@ public class AuthenticationService {
|
||||
|
||||
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
|
||||
String ip = RequestUtils.getCurrentRequest().getRemoteAddr();
|
||||
String username = loginRequest.getUsername();
|
||||
authRateLimitService.checkLoginRateLimit(ip);
|
||||
authRateLimitService.checkLoginRateLimitByUsername(username);
|
||||
|
||||
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> {
|
||||
auditService.log(AuditAction.LOGIN_FAILED, "Login failed for unknown user: " + loginRequest.getUsername());
|
||||
BookLoreUserEntity user = userRepository.findByUsername(username).orElse(null);
|
||||
|
||||
if (user == null) {
|
||||
// Constant-time dummy BCrypt check prevents timing-based user enumeration:
|
||||
// without this, unknown-user responses are ~3x faster than wrong-password responses.
|
||||
passwordEncoder.matches(loginRequest.getPassword(), dummyPasswordHash);
|
||||
auditService.log(AuditAction.LOGIN_FAILED, "Login failed for unknown user: " + username);
|
||||
authRateLimitService.recordFailedLoginAttempt(ip);
|
||||
return ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername());
|
||||
});
|
||||
authRateLimitService.recordFailedLoginAttemptByUsername(username);
|
||||
throw ApiError.INVALID_CREDENTIALS.createException();
|
||||
}
|
||||
|
||||
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
|
||||
auditService.log(AuditAction.LOGIN_FAILED, "Login failed for user: " + loginRequest.getUsername());
|
||||
auditService.log(AuditAction.LOGIN_FAILED, "Login failed for user: " + username);
|
||||
authRateLimitService.recordFailedLoginAttempt(ip);
|
||||
authRateLimitService.recordFailedLoginAttemptByUsername(username);
|
||||
throw ApiError.INVALID_CREDENTIALS.createException();
|
||||
}
|
||||
|
||||
authRateLimitService.resetLoginAttempts(ip);
|
||||
authRateLimitService.resetLoginAttemptsByUsername(username);
|
||||
return loginUser(user);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ public class OpdsUserDetailsService implements UserDetailsService {
|
||||
@Override
|
||||
public OpdsUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
OpdsUserV2Entity userV2 = opdsUserV2Repository.findByUsername(username)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
|
||||
.orElseThrow(() -> new UsernameNotFoundException("Invalid credentials"));
|
||||
OpdsUserV2 mappedCredential = opdsUserV2Mapper.toDto(userV2);
|
||||
return new OpdsUserDetails(mappedCredential);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.booklore.controller;
|
||||
|
||||
import org.booklore.service.AuthorMetadataService;
|
||||
import org.booklore.config.security.annotation.CheckBookAccess;
|
||||
import org.booklore.service.book.BookService;
|
||||
import org.booklore.service.bookdrop.BookDropService;
|
||||
import org.booklore.service.reader.CbxReaderService;
|
||||
@@ -32,6 +33,7 @@ public class BookMediaController {
|
||||
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a specific book.")
|
||||
@ApiResponse(responseCode = "200", description = "Book thumbnail returned successfully")
|
||||
@GetMapping("/book/{bookId}/thumbnail")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<Resource> getBookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookService.getBookThumbnail(bookId));
|
||||
}
|
||||
@@ -39,6 +41,7 @@ public class BookMediaController {
|
||||
@Operation(summary = "Get book cover", description = "Retrieve the cover image for a specific book.")
|
||||
@ApiResponse(responseCode = "200", description = "Book cover returned successfully")
|
||||
@GetMapping("/book/{bookId}/cover")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<Resource> getBookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookService.getBookCover(bookId));
|
||||
}
|
||||
@@ -46,6 +49,7 @@ public class BookMediaController {
|
||||
@Operation(summary = "Get audiobook thumbnail", description = "Retrieve the audiobook thumbnail image for a specific book.")
|
||||
@ApiResponse(responseCode = "200", description = "Audiobook thumbnail returned successfully")
|
||||
@GetMapping("/book/{bookId}/audiobook-thumbnail")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<Resource> getAudiobookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookService.getAudiobookThumbnail(bookId));
|
||||
}
|
||||
@@ -53,6 +57,7 @@ public class BookMediaController {
|
||||
@Operation(summary = "Get audiobook cover", description = "Retrieve the audiobook cover image for a specific book.")
|
||||
@ApiResponse(responseCode = "200", description = "Audiobook cover returned successfully")
|
||||
@GetMapping("/book/{bookId}/audiobook-cover")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<Resource> getAudiobookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookService.getAudiobookCover(bookId));
|
||||
}
|
||||
@@ -60,6 +65,7 @@ public class BookMediaController {
|
||||
@Operation(summary = "Get CBX page as image", description = "Retrieve a specific page from a CBX book as an image.")
|
||||
@ApiResponse(responseCode = "200", description = "CBX page image returned successfully")
|
||||
@GetMapping("/book/{bookId}/cbx/pages/{pageNumber}")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public void getCbxPage(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Page number to retrieve") @PathVariable int pageNumber,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.booklore.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.booklore.exception.ErrorResponse;
|
||||
import org.booklore.model.dto.request.InitialUserRequest;
|
||||
import org.booklore.model.dto.response.SuccessResponse;
|
||||
@@ -35,7 +36,7 @@ public class SetupController {
|
||||
@ApiResponse(responseCode = "200", description = "Admin user created successfully")
|
||||
@PostMapping
|
||||
public ResponseEntity<?> setupFirstUser(
|
||||
@Parameter(description = "Initial user request") @RequestBody InitialUserRequest request) {
|
||||
@Parameter(description = "Initial user request") @RequestBody @Valid InitialUserRequest request) {
|
||||
if (userProvisioningService.isInitialUserAlreadyProvisioned()) {
|
||||
return ResponseEntity.status(403).body(new ErrorResponse(403, "Setup is disabled after the first user is created."));
|
||||
}
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
package org.booklore.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
public class UserCreateRequest {
|
||||
|
||||
@NotBlank
|
||||
private String username;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 8, max = 72, message = "Password must be at least 8 characters long")
|
||||
private String password;
|
||||
|
||||
@NotBlank
|
||||
private String name;
|
||||
|
||||
@NotBlank
|
||||
@Email
|
||||
private String email;
|
||||
|
||||
private boolean permissionUpload;
|
||||
|
||||
@@ -2,6 +2,7 @@ package org.booklore.model.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@@ -17,5 +18,6 @@ public class InitialUserRequest {
|
||||
private String name;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 8, max = 72, message = "Password must be between 8 and 72 characters long")
|
||||
private String password;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package org.booklore.model.dto.settings;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSetter;
|
||||
import com.fasterxml.jackson.annotation.Nulls;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -10,10 +12,16 @@ import lombok.NoArgsConstructor;
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class KoboSettings {
|
||||
private boolean convertToKepub;
|
||||
private int conversionLimitInMb;
|
||||
private boolean convertCbxToEpub;
|
||||
private int conversionLimitInMbForCbx;
|
||||
private boolean forceEnableHyphenation;
|
||||
private int conversionImageCompressionPercentage;
|
||||
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
|
||||
private boolean convertToKepub = false;
|
||||
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
|
||||
private int conversionLimitInMb = 100;
|
||||
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
|
||||
private boolean convertCbxToEpub = false;
|
||||
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
|
||||
private int conversionLimitInMbForCbx = 100;
|
||||
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
|
||||
private boolean forceEnableHyphenation = false;
|
||||
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
|
||||
private int conversionImageCompressionPercentage = 85;
|
||||
}
|
||||
|
||||
+6
-1
@@ -60,6 +60,10 @@ public class MetadataMatchWeights {
|
||||
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
|
||||
private int ranobedbRating = 2;
|
||||
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
|
||||
private int audibleRating = 2;
|
||||
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
|
||||
private int audibleReviewCount = 1;
|
||||
@Builder.Default @JsonSetter(nulls = Nulls.SKIP)
|
||||
private int coverImage = 5;
|
||||
|
||||
public int totalWeight() {
|
||||
@@ -67,6 +71,7 @@ public class MetadataMatchWeights {
|
||||
seriesName + seriesNumber + seriesTotal + isbn13 + isbn10 + language +
|
||||
pageCount + categories + amazonRating + amazonReviewCount +
|
||||
goodreadsRating + goodreadsReviewCount + hardcoverRating +
|
||||
hardcoverReviewCount + ranobedbRating + coverImage;
|
||||
hardcoverReviewCount + doubanRating + doubanReviewCount +
|
||||
ranobedbRating + audibleRating + audibleReviewCount + coverImage;
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -22,4 +22,7 @@ public class MetadataProviderSpecificFields {
|
||||
private Boolean lubimyczytacRating;
|
||||
private Boolean ranobedbId;
|
||||
private Boolean ranobedbRating;
|
||||
private Boolean audibleId;
|
||||
private Boolean audibleRating;
|
||||
private Boolean audibleReviewCount;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import org.booklore.util.ArchiveUtils;
|
||||
import org.booklore.util.BookCoverUtils;
|
||||
import org.booklore.util.FileService;
|
||||
import org.booklore.util.FileUtils;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -210,11 +211,37 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", file.getName(), e.getMessage());
|
||||
return extractFirstImageFromRarViaCli(file);
|
||||
}
|
||||
log.error("Error extracting RAR: {}", e.getMessage());
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private Optional<BufferedImage> extractFirstImageFromRarViaCli(File file) {
|
||||
try {
|
||||
List<String> entries = UnrarHelper.listEntries(file.toPath());
|
||||
List<String> imageEntries = entries.stream()
|
||||
.filter(name -> IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN.matcher(name).matches())
|
||||
.sorted()
|
||||
.toList();
|
||||
for (String entry : imageEntries) {
|
||||
try {
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(file.toPath(), entry);
|
||||
BufferedImage image = FileService.readImage(new ByteArrayInputStream(bytes));
|
||||
if (image != null) return Optional.of(image);
|
||||
} catch (Exception ex) {
|
||||
log.warn("Error reading RAR entry via CLI {}: {}", entry, ex.getMessage());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("unrar CLI fallback also failed for {}: {}", file.getName(), e.getMessage());
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private void extractAndSetMetadata(BookEntity bookEntity) {
|
||||
try {
|
||||
BookMetadata extracted = cbxMetadataExtractor.extractMetadata(new File(FileUtils.getBookFullPath(bookEntity)));
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.booklore.model.entity.CategoryEntity;
|
||||
import org.booklore.model.entity.TagEntity;
|
||||
import org.booklore.util.ArchiveUtils;
|
||||
import org.booklore.util.FileService;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.exception.RarException;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
@@ -263,6 +264,14 @@ public class CbxConversionService {
|
||||
log.warn("Error extracting image {}: {}", fileHeader.getFileName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", cbrFile.getName(), e.getMessage());
|
||||
return extractImagesFromRarViaCli(cbrFile, extractedImagesDir);
|
||||
}
|
||||
if (e instanceof IOException ioe) throw ioe;
|
||||
if (e instanceof RarException re) throw re;
|
||||
throw new IOException("Failed to read RAR archive: " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
log.debug("Found {} image entries in CBR file", imagePaths.size());
|
||||
@@ -270,6 +279,26 @@ public class CbxConversionService {
|
||||
return imagePaths;
|
||||
}
|
||||
|
||||
private List<Path> extractImagesFromRarViaCli(File cbrFile, Path extractedImagesDir) throws IOException {
|
||||
List<Path> imagePaths = new ArrayList<>();
|
||||
List<String> entries = UnrarHelper.listEntries(cbrFile.toPath());
|
||||
for (String entryName : entries) {
|
||||
if (!isImageFile(entryName)) continue;
|
||||
try {
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(cbrFile.toPath(), entryName);
|
||||
validateImageSize(entryName, bytes.length);
|
||||
Path outputPath = extractedImagesDir.resolve(extractFileName(entryName));
|
||||
Files.write(outputPath, bytes);
|
||||
imagePaths.add(outputPath);
|
||||
} catch (Exception e) {
|
||||
log.warn("Error extracting image via CLI {}: {}", entryName, e.getMessage());
|
||||
}
|
||||
}
|
||||
log.debug("Found {} image entries in CBR file (via unrar CLI)", imagePaths.size());
|
||||
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
||||
return imagePaths;
|
||||
}
|
||||
|
||||
private List<Path> extractImagesFrom7z(File cb7File, Path extractedImagesDir) throws IOException {
|
||||
List<Path> imagePaths = new ArrayList<>();
|
||||
|
||||
|
||||
@@ -109,22 +109,25 @@ public class LibraryFileHelper {
|
||||
boolean hasNonAudioBooks = dirHasNonAudioBooks.getOrDefault(dir, false);
|
||||
|
||||
if (audioFiles != null && audioFiles.size() >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBooks) {
|
||||
// This is a folder-based audiobook: contains 2+ audio files and no ebook files
|
||||
// Don't treat library root as audiobook folder
|
||||
if (!dir.equals(libraryPath)) {
|
||||
log.info("Detected folder-based audiobook: {} ({} audio files)", dir.getFileName(), audioFiles.size());
|
||||
if (FileUtils.isSeriesFolder(audioFiles)) {
|
||||
log.info("Detected series folder: {} ({} audio files with distinct titles)", dir.getFileName(), audioFiles.size());
|
||||
addIndividualAudioFiles(audioFiles, libraryEntity, pathEntity, libraryFiles);
|
||||
} else {
|
||||
log.info("Detected folder-based audiobook: {} ({} audio files)", dir.getFileName(), audioFiles.size());
|
||||
|
||||
processedAsFolderAudiobook.add(dir);
|
||||
processedAsFolderAudiobook.add(dir);
|
||||
|
||||
// Add a single LibraryFile representing the folder
|
||||
libraryFiles.add(LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), dir))
|
||||
.fileName(dir.getFileName().toString())
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.folderBased(true)
|
||||
.build());
|
||||
libraryFiles.add(LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), dir))
|
||||
.fileName(dir.getFileName().toString())
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.folderBased(true)
|
||||
.build());
|
||||
}
|
||||
} else {
|
||||
// Library root - add individual audio files
|
||||
addIndividualAudioFiles(audioFiles, libraryEntity, pathEntity, libraryFiles);
|
||||
|
||||
+80
-2
@@ -9,6 +9,7 @@ import org.apache.commons.io.FilenameUtils;
|
||||
import org.booklore.model.dto.BookMetadata;
|
||||
import org.booklore.model.dto.ComicMetadata;
|
||||
import org.booklore.util.ArchiveUtils;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.NodeList;
|
||||
@@ -22,6 +23,7 @@ import javax.xml.parsers.ParserConfigurationException;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDate;
|
||||
import java.util.*;
|
||||
import java.util.List;
|
||||
@@ -108,7 +110,15 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
log.warn("Failed to extract metadata from CBR", e);
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
} catch (Exception ignore) {
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", file.getName(), e.getMessage());
|
||||
try {
|
||||
return extractMetadataFromRarViaCli(file.toPath(), baseName);
|
||||
} catch (Exception ex) {
|
||||
log.warn("unrar CLI fallback also failed for {}", file.getName(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
@@ -749,7 +759,16 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
log.warn("Failed to extract cover image from CBR", e);
|
||||
return generatePlaceholderCover(250, 350);
|
||||
}
|
||||
} catch (Exception ignore) {
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI for cover: {}", file.getName(), e.getMessage());
|
||||
try {
|
||||
byte[] coverBytes = extractCoverFromRarViaCli(file.toPath());
|
||||
if (coverBytes != null) return coverBytes;
|
||||
} catch (Exception ex) {
|
||||
log.warn("unrar CLI cover fallback also failed for {}", file.getName(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1127,4 +1146,63 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
String lower = n.toLowerCase();
|
||||
return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml");
|
||||
}
|
||||
|
||||
private BookMetadata extractMetadataFromRarViaCli(Path rarPath, String baseName) throws Exception {
|
||||
List<String> entries = UnrarHelper.listEntries(rarPath);
|
||||
String comicInfoEntry = entries.stream()
|
||||
.filter(CbxMetadataExtractor::isComicInfoName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (comicInfoEntry == null) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
byte[] xmlBytes = UnrarHelper.extractEntryBytes(rarPath, comicInfoEntry);
|
||||
if (xmlBytes == null || xmlBytes.length == 0) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
return mapDocumentToMetadata(document, baseName);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] extractCoverFromRarViaCli(Path rarPath) throws Exception {
|
||||
List<String> entries = UnrarHelper.listEntries(rarPath);
|
||||
|
||||
String comicInfoEntry = entries.stream()
|
||||
.filter(CbxMetadataExtractor::isComicInfoName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (comicInfoEntry != null) {
|
||||
byte[] xmlBytes = UnrarHelper.extractEntryBytes(rarPath, comicInfoEntry);
|
||||
if (xmlBytes != null && xmlBytes.length > 0) {
|
||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
String imageName = findFrontCoverImageName(document);
|
||||
if (imageName != null) {
|
||||
String match = entries.stream()
|
||||
.filter(e -> e.equalsIgnoreCase(imageName) || baseName(e).equalsIgnoreCase(baseName(imageName)))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (match != null) {
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(rarPath, match);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<String> imageEntries = entries.stream()
|
||||
.filter(this::isImageEntry)
|
||||
.sorted(this::naturalCompare)
|
||||
.toList();
|
||||
List<String> sorted = new ArrayList<>(imageEntries);
|
||||
sorted.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a)), !likelyCoverName(baseName(b))));
|
||||
for (String entry : sorted) {
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(rarPath, entry);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
+3
-7
@@ -1,6 +1,7 @@
|
||||
package org.booklore.service.metadata.extractor;
|
||||
|
||||
import org.booklore.model.dto.BookMetadata;
|
||||
import org.booklore.util.SecureXmlUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -9,7 +10,6 @@ import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import java.io.File;
|
||||
@@ -37,9 +37,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
||||
@Override
|
||||
public byte[] extractCover(File file) {
|
||||
try (InputStream inputStream = getInputStream(file)) {
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
dbf.setNamespaceAware(true);
|
||||
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
DocumentBuilderFactory dbf = SecureXmlUtils.createSecureDocumentBuilderFactory(true);
|
||||
DocumentBuilder builder = dbf.newDocumentBuilder();
|
||||
Document doc = builder.parse(inputStream);
|
||||
|
||||
@@ -93,9 +91,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
|
||||
@Override
|
||||
public BookMetadata extractMetadata(File file) {
|
||||
try (InputStream inputStream = getInputStream(file)) {
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
dbf.setNamespaceAware(true);
|
||||
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
DocumentBuilderFactory dbf = SecureXmlUtils.createSecureDocumentBuilderFactory(true);
|
||||
DocumentBuilder builder = dbf.newDocumentBuilder();
|
||||
Document doc = builder.parse(inputStream);
|
||||
|
||||
|
||||
+89
-13
@@ -5,6 +5,12 @@ import com.github.junrar.rarfile.FileHeader;
|
||||
import jakarta.xml.bind.JAXBContext;
|
||||
import jakarta.xml.bind.Marshaller;
|
||||
import jakarta.xml.bind.Unmarshaller;
|
||||
import jakarta.xml.bind.ValidationEvent;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.SAXParserFactory;
|
||||
import javax.xml.transform.sax.SAXSource;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.XMLReader;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
|
||||
@@ -16,6 +22,7 @@ import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.model.enums.ComicCreatorRole;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.util.ArchiveUtils;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.safety.Safelist;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -47,10 +54,6 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
private static final JAXBContext JAXB_CONTEXT;
|
||||
|
||||
static {
|
||||
// XXE protection: Disable external DTD and Schema access for security
|
||||
System.setProperty("javax.xml.accessExternalDTD", "");
|
||||
System.setProperty("javax.xml.accessExternalSchema", "");
|
||||
|
||||
try {
|
||||
JAXB_CONTEXT = JAXBContext.newInstance(ComicInfo.class);
|
||||
} catch (jakarta.xml.bind.JAXBException e) {
|
||||
@@ -194,9 +197,32 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
}
|
||||
}
|
||||
return new ComicInfo();
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", file.getName(), e.getMessage());
|
||||
return loadFromRarViaCli(file.toPath());
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private ComicInfo loadFromRarViaCli(Path rarPath) throws Exception {
|
||||
java.util.List<String> entries = UnrarHelper.listEntries(rarPath);
|
||||
String comicInfoEntry = entries.stream()
|
||||
.filter(CbxMetadataWriter::isComicInfoXml)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (comicInfoEntry != null) {
|
||||
byte[] xmlBytes = UnrarHelper.extractEntryBytes(rarPath, comicInfoEntry);
|
||||
if (xmlBytes != null && xmlBytes.length > 0) {
|
||||
try (InputStream stream = new ByteArrayInputStream(xmlBytes)) {
|
||||
return parseComicInfo(stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new ComicInfo();
|
||||
}
|
||||
|
||||
private void applyMetadataChanges(ComicInfo info, BookMetadataEntity metadata, MetadataClearFlags clearFlags) {
|
||||
MetadataCopyHelper helper = new MetadataCopyHelper(metadata);
|
||||
|
||||
@@ -447,20 +473,32 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
}
|
||||
|
||||
private ComicInfo parseComicInfo(InputStream xmlStream) throws Exception {
|
||||
// Use a SAXSource with an explicitly secured XMLReader to prevent XXE injection.
|
||||
// This is more robust than System.setProperty() because it is per-instance and
|
||||
// cannot be inadvertently disabled by other code running in the same JVM.
|
||||
SAXParserFactory spf = SAXParserFactory.newInstance();
|
||||
spf.setNamespaceAware(true);
|
||||
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
|
||||
SAXSource saxSource = new SAXSource(xmlReader, new InputSource(xmlStream));
|
||||
|
||||
Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
|
||||
unmarshaller.setEventHandler(event -> {
|
||||
if (event.getSeverity() == jakarta.xml.bind.ValidationEvent.WARNING ||
|
||||
event.getSeverity() == jakarta.xml.bind.ValidationEvent.ERROR) {
|
||||
log.warn("JAXB Parsing Issue: {} [Line: {}, Col: {}]",
|
||||
event.getMessage(),
|
||||
event.getLocator().getLineNumber(),
|
||||
if (event.getSeverity() == ValidationEvent.WARNING ||
|
||||
event.getSeverity() == ValidationEvent.ERROR) {
|
||||
log.warn("JAXB Parsing Issue: {} [Line: {}, Col: {}]",
|
||||
event.getMessage(),
|
||||
event.getLocator().getLineNumber(),
|
||||
event.getLocator().getColumnNumber());
|
||||
}
|
||||
return true; // Continue processing
|
||||
});
|
||||
ComicInfo result = (ComicInfo) unmarshaller.unmarshal(xmlStream);
|
||||
log.debug("CbxMetadataWriter: Parsed ComicInfo - Title: {}, Summary length: {}",
|
||||
result.getTitle(),
|
||||
ComicInfo result = (ComicInfo) unmarshaller.unmarshal(saxSource);
|
||||
log.debug("CbxMetadataWriter: Parsed ComicInfo - Title: {}, Summary length: {}",
|
||||
result.getTitle(),
|
||||
result.getSummary() != null ? result.getSummary().length() : 0);
|
||||
return result;
|
||||
}
|
||||
@@ -590,6 +628,13 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI extractAll: {}", rarFile.getName(), e.getMessage());
|
||||
UnrarHelper.extractAll(rarFile.toPath(), targetDir);
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,6 +662,13 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml"));
|
||||
zipOutput.write(xmlContent);
|
||||
zipOutput.closeEntry();
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI for RAR-to-ZIP: {}", rarFile.getName(), e.getMessage());
|
||||
convertRarToZipViaCli(rarFile.toPath(), tempZip, xmlContent);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
Path targetPath = rarFile.toPath().resolveSibling(removeFileExtension(rarFile.getName()) + ".cbz");
|
||||
@@ -630,6 +682,26 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
return null;
|
||||
}
|
||||
|
||||
private void convertRarToZipViaCli(Path rarPath, Path tempZip, byte[] xmlContent) throws Exception {
|
||||
java.util.List<String> entries = UnrarHelper.listEntries(rarPath);
|
||||
try (ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(tempZip))) {
|
||||
for (String entryName : entries) {
|
||||
if (isComicInfoXml(entryName)) continue;
|
||||
if (!isPathSafe(entryName)) {
|
||||
log.warn("Skipping unsafe RAR entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(rarPath, entryName);
|
||||
zipOutput.putNextEntry(new ZipEntry(entryName));
|
||||
zipOutput.write(bytes);
|
||||
zipOutput.closeEntry();
|
||||
}
|
||||
zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml"));
|
||||
zipOutput.write(xmlContent);
|
||||
zipOutput.closeEntry();
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreOriginalFile(Path backupPath, File targetFile) {
|
||||
try {
|
||||
if (backupPath != null) {
|
||||
@@ -703,8 +775,12 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
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;
|
||||
// Check each path component for ".." traversal. Splitting with -1 limit catches
|
||||
// trailing separators and avoids missing ".." at the end of a path (e.g. "foo/..").
|
||||
for (String component : normalized.split("/", -1)) {
|
||||
if ("..".equals(component)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
@@ -472,7 +473,7 @@ public class OpdsFeedService {
|
||||
|
||||
String queryString = request.getQueryString();
|
||||
if (queryString != null) {
|
||||
java.util.Arrays.stream(queryString.split("&"))
|
||||
Arrays.stream(queryString.split("&"))
|
||||
.filter(param -> !param.startsWith("page=") && !param.startsWith("size="))
|
||||
.forEach(param -> result.append(param).append("&"));
|
||||
}
|
||||
|
||||
+30
-21
@@ -209,36 +209,45 @@ public class ReadingProgressService {
|
||||
progress.setBook(book);
|
||||
progress.setLastReadTime(now);
|
||||
|
||||
Float percentage;
|
||||
Float percentage = null;
|
||||
|
||||
if (request.getFileProgress() != null) {
|
||||
BookFileProgress fileProgress = request.getFileProgress();
|
||||
percentage = fileProgress.progressPercent();
|
||||
boolean hasProgressData = request.getFileProgress() != null
|
||||
|| request.getEpubProgress() != null
|
||||
|| request.getPdfProgress() != null
|
||||
|| request.getCbxProgress() != null
|
||||
|| request.getAudiobookProgress() != null;
|
||||
|
||||
saveToUserBookFileProgress(userEntity, fileProgress, now);
|
||||
if (hasProgressData) {
|
||||
if (request.getFileProgress() != null) {
|
||||
BookFileProgress fileProgress = request.getFileProgress();
|
||||
percentage = fileProgress.progressPercent();
|
||||
|
||||
BookFileEntity bookFile = bookFileRepository.findById(fileProgress.bookFileId())
|
||||
.orElseThrow(() -> ApiError.GENERIC_NOT_FOUND.createException("Book file not found"));
|
||||
updateProgressFromFileProgress(progress, bookFile.getBookType(), fileProgress);
|
||||
} else {
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
|
||||
saveToUserBookFileProgress(userEntity, fileProgress, now);
|
||||
|
||||
BookFileEntity bookFile = bookFileRepository.findById(fileProgress.bookFileId())
|
||||
.orElseThrow(() -> ApiError.GENERIC_NOT_FOUND.createException("Book file not found"));
|
||||
updateProgressFromFileProgress(progress, bookFile.getBookType(), fileProgress);
|
||||
} else {
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
|
||||
}
|
||||
percentage = updateProgressByBookType(progress, primaryFile.getBookType(), request);
|
||||
|
||||
if (percentage != null) {
|
||||
saveToUserBookFileProgressFromLegacy(userEntity, primaryFile, progress, now);
|
||||
}
|
||||
}
|
||||
percentage = updateProgressByBookType(progress, primaryFile.getBookType(), request);
|
||||
|
||||
if (percentage != null) {
|
||||
saveToUserBookFileProgressFromLegacy(userEntity, primaryFile, progress, now);
|
||||
progress.setReadStatus(calculateReadStatus(percentage, progress.getReadStatus()));
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile != null) {
|
||||
setProgressPercent(progress, primaryFile.getBookType(), percentage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (percentage != null) {
|
||||
progress.setReadStatus(calculateReadStatus(percentage, progress.getReadStatus()));
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile != null) {
|
||||
setProgressPercent(progress, primaryFile.getBookType(), percentage);
|
||||
}
|
||||
}
|
||||
if (request.getDateFinished() != null) {
|
||||
progress.setDateFinished(request.getDateFinished());
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import org.booklore.model.entity.BookFileEntity;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.util.FileUtils;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
@@ -396,7 +397,14 @@ public class CbxReaderService {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Failed to read RAR archive: " + e.getMessage(), e);
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", cbxPath.getFileName(), e.getMessage());
|
||||
entries = UnrarHelper.listEntries(cbxPath).stream()
|
||||
.filter(this::isImageFile)
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
} else {
|
||||
throw new IOException("Failed to read RAR archive: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
sortNaturally(entries);
|
||||
return entries;
|
||||
@@ -411,6 +419,11 @@ public class CbxReaderService {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", cbxPath.getFileName(), e.getMessage());
|
||||
UnrarHelper.extractEntry(cbxPath, entryName, outputStream);
|
||||
return;
|
||||
}
|
||||
throw new IOException("Failed to extract from RAR archive: " + e.getMessage(), e);
|
||||
}
|
||||
throw new FileNotFoundException("Entry not found in RAR archive: " + entryName);
|
||||
@@ -437,6 +450,13 @@ public class CbxReaderService {
|
||||
if (normalized.startsWith("__MACOSX/") || normalized.contains("/__MACOSX/")) {
|
||||
return false;
|
||||
}
|
||||
// Prevent path traversal: reject any entry whose path contains ".." as a component.
|
||||
// Checks split-by-/ to catch "foo/..", ".." alone, and not just "../" (with trailing slash).
|
||||
for (String component : normalized.split("/", -1)) {
|
||||
if ("..".equals(component)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
String baseName = baseName(normalized).toLowerCase();
|
||||
if (baseName.startsWith("._") || baseName.startsWith(".")) {
|
||||
return false;
|
||||
|
||||
@@ -20,11 +20,13 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||
import org.apache.pdfbox.io.IOUtils;
|
||||
import org.booklore.util.SecureXmlUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
@@ -63,12 +65,7 @@ public class EpubReaderService {
|
||||
|
||||
private static final ThreadLocal<DocumentBuilder> DOCUMENT_BUILDER = ThreadLocal.withInitial(() -> {
|
||||
try {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
return factory.newDocumentBuilder();
|
||||
return SecureXmlUtils.createSecureDocumentBuilder(true);
|
||||
} catch (ParserConfigurationException e) {
|
||||
throw new RuntimeException("Failed to create DocumentBuilder", e);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.booklore.service.upload;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.config.AppProperties;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.mapper.AdditionalFileMapper;
|
||||
@@ -21,7 +22,7 @@ import org.booklore.service.file.FileMovingHelper;
|
||||
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import org.booklore.service.metadata.extractor.MetadataExtractorFactory;
|
||||
import org.booklore.util.PathPatternResolver;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -262,7 +263,13 @@ public class FileUploadService {
|
||||
if (originalFileName == null) {
|
||||
throw new IllegalArgumentException("File must have a name");
|
||||
}
|
||||
return originalFileName;
|
||||
// Prevent Path Traversal by extracting only the base file name
|
||||
String cleanPath = StringUtils.cleanPath(originalFileName);
|
||||
String baseFileName = StringUtils.getFilename(cleanPath);
|
||||
if (baseFileName == null || baseFileName.isEmpty() || baseFileName.equals("..")) {
|
||||
throw new IllegalArgumentException("Invalid filename");
|
||||
}
|
||||
return baseFileName;
|
||||
}
|
||||
|
||||
private BookFileExtension getFileExtension(String fileName) {
|
||||
|
||||
+10
-5
@@ -18,6 +18,8 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.*;
|
||||
@@ -252,7 +254,7 @@ public class LibraryFileEventProcessor {
|
||||
}
|
||||
|
||||
private FolderAnalysis analyzeFolderForAudiobook(Path folderPath) {
|
||||
int audioFileCount = 0;
|
||||
List<Path> audioFiles = new ArrayList<>();
|
||||
boolean hasNonAudioBook = false;
|
||||
|
||||
try (var stream = Files.walk(folderPath)) {
|
||||
@@ -263,7 +265,7 @@ public class LibraryFileEventProcessor {
|
||||
var ext = BookFileExtension.fromFileName(fileName);
|
||||
if (ext.isPresent()) {
|
||||
if (ext.get().getType() == BookFileType.AUDIOBOOK) {
|
||||
audioFileCount++;
|
||||
audioFiles.add(file);
|
||||
} else {
|
||||
hasNonAudioBook = true;
|
||||
}
|
||||
@@ -273,12 +275,15 @@ public class LibraryFileEventProcessor {
|
||||
log.warn("[ERROR] Analyzing folder '{}': {}", folderPath, e.getMessage());
|
||||
}
|
||||
|
||||
return new FolderAnalysis(audioFileCount, hasNonAudioBook);
|
||||
boolean isSeriesFolder = audioFiles.size() >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK
|
||||
&& FileUtils.isSeriesFolder(audioFiles);
|
||||
|
||||
return new FolderAnalysis(audioFiles.size(), hasNonAudioBook, isSeriesFolder);
|
||||
}
|
||||
|
||||
private record FolderAnalysis(int audioFileCount, boolean hasNonAudioBook) {
|
||||
private record FolderAnalysis(int audioFileCount, boolean hasNonAudioBook, boolean isSeriesFolder) {
|
||||
boolean isFolderBasedAudiobook() {
|
||||
return audioFileCount >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBook;
|
||||
return audioFileCount >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBook && !isSeriesFolder;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,6 +44,23 @@ public class BookFileGroupingUtils {
|
||||
"[\\s_-]?(\\d{1,3})\\s*$"
|
||||
);
|
||||
|
||||
// Part/disc indicators: "(part 1)", "[pt 2]", "- disc 1", "cd 3", etc.
|
||||
// "part" requires brackets or dash prefix to avoid conflict with series labels ("Part 1" = series entry).
|
||||
// "pt", "disc", "disk", "cd" are unambiguous and can be matched bare.
|
||||
private static final Pattern PART_INDICATOR_PATTERN = Pattern.compile(
|
||||
"\\s*(?:" +
|
||||
"[\\(\\[]\\s*(?:part|pt|dis[ck]|cd)\\s*\\d+\\s*[\\)\\]]" +
|
||||
"|-\\s*(?:part|pt|dis[ck]|cd)\\s*\\d+" +
|
||||
"|(?:pt|dis[ck]|cd)\\s*\\d+" +
|
||||
")\\s*$",
|
||||
Pattern.CASE_INSENSITIVE
|
||||
);
|
||||
|
||||
// Bare-number prefix: "1. Title", "01 - Title" (NOT "101 Dalmatians" or "1984")
|
||||
private static final Pattern BARE_NUMBER_PREFIX_PATTERN = Pattern.compile(
|
||||
"^(\\d{1,3})(?:\\.|\\s*-)\\s+(.+)$"
|
||||
);
|
||||
|
||||
// Edition/version patterns that should NOT prevent grouping
|
||||
// Includes format indicators (audiobook, ebook) and edition descriptors
|
||||
private static final Pattern EDITION_PATTERN = Pattern.compile(
|
||||
@@ -86,6 +103,9 @@ public class BookFileGroupingUtils {
|
||||
|
||||
baseName = FORMAT_INDICATOR_PATTERN.matcher(baseName).replaceAll("");
|
||||
|
||||
// Strip part/disc indicators (e.g., "(part 1)", "[cd 2]")
|
||||
baseName = PART_INDICATOR_PATTERN.matcher(baseName).replaceAll("");
|
||||
|
||||
// Strip trailing author names (after dash)
|
||||
baseName = TRAILING_AUTHOR_PATTERN.matcher(baseName).replaceAll("");
|
||||
|
||||
@@ -318,6 +338,18 @@ public class BookFileGroupingUtils {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: bare-number prefix like "1. title" or "01 - title"
|
||||
Matcher bareMatcher = BARE_NUMBER_PREFIX_PATTERN.matcher(key);
|
||||
if (bareMatcher.matches()) {
|
||||
String number = bareMatcher.group(1);
|
||||
String baseTitle = bareMatcher.group(2).trim();
|
||||
baseTitle = WHITESPACE_PATTERN.matcher(baseTitle).replaceAll(" ").trim();
|
||||
if (baseTitle.length() >= 3) {
|
||||
return new SeriesInfo(baseTitle, number);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,22 +11,30 @@ import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageReader;
|
||||
import javax.imageio.stream.ImageInputStream;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.InetAddress;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -35,9 +43,32 @@ import java.util.stream.Stream;
|
||||
@Service
|
||||
public class FileService {
|
||||
|
||||
private static final ThreadLocal<String> TARGET_HOST_THREAD_LOCAL = new ThreadLocal<>();
|
||||
|
||||
public static String getTargetHost() {
|
||||
return TARGET_HOST_THREAD_LOCAL.get();
|
||||
}
|
||||
|
||||
public static void setTargetHost(String host) {
|
||||
TARGET_HOST_THREAD_LOCAL.set(host);
|
||||
}
|
||||
|
||||
public static void clearTargetHost() {
|
||||
TARGET_HOST_THREAD_LOCAL.remove();
|
||||
}
|
||||
|
||||
static {
|
||||
// Enable restricted headers to allow 'Host' header override for DNS rebinding protection
|
||||
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
|
||||
}
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final RestTemplate restTemplate;
|
||||
private final AppSettingService appSettingService;
|
||||
private final RestTemplate noRedirectRestTemplate;
|
||||
|
||||
private static final int MAX_REDIRECTS = 5;
|
||||
|
||||
|
||||
private static final double TARGET_COVER_ASPECT_RATIO = 1.5;
|
||||
private static final int SMART_CROP_COLOR_TOLERANCE = 30;
|
||||
@@ -58,6 +89,8 @@ public class 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;
|
||||
// 20 MP covers legitimate book covers and author photos with a comfortable safety margin.
|
||||
private static final long MAX_IMAGE_PIXELS = 20_000_000L;
|
||||
private static final int THUMBNAIL_WIDTH = 250;
|
||||
private static final int THUMBNAIL_HEIGHT = 350;
|
||||
private static final int SQUARE_THUMBNAIL_SIZE = 250;
|
||||
@@ -137,6 +170,7 @@ public class FileService {
|
||||
return Paths.get(appProperties.getPathConfig(), "tools", "kepubify").toString();
|
||||
}
|
||||
|
||||
|
||||
// ========================================
|
||||
// VALIDATION
|
||||
// ========================================
|
||||
@@ -170,18 +204,34 @@ public class FileService {
|
||||
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;
|
||||
|
||||
try (ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(imageData))) {
|
||||
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
|
||||
if (readers.hasNext()) {
|
||||
ImageReader reader = readers.next();
|
||||
try {
|
||||
reader.setInput(iis);
|
||||
int width = reader.getWidth(0);
|
||||
int height = reader.getHeight(0);
|
||||
|
||||
long pixelCount = (long) width * height;
|
||||
if (pixelCount > MAX_IMAGE_PIXELS) {
|
||||
throw new IOException(String.format("Rejected image: dimensions %dx%d (%d pixels) exceed limit %d — possible decompression bomb",
|
||||
width, height, pixelCount, MAX_IMAGE_PIXELS));
|
||||
}
|
||||
|
||||
return reader.read(0);
|
||||
} finally {
|
||||
reader.dispose();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.warn("ImageIO/TwelveMonkeys decode failed (possibly unsupported format like AVIF/HEIC): {}", e.getMessage());
|
||||
return null;
|
||||
throw new IOException("ImageIO decode failed (possibly unsupported format): " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
log.warn("Unable to decode image - likely unsupported format (AVIF, HEIC, or SVG)");
|
||||
return null;
|
||||
throw new IOException("Unable to decode image, likely unsupported format");
|
||||
}
|
||||
|
||||
public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
|
||||
@@ -217,31 +267,138 @@ public class FileService {
|
||||
|
||||
public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException {
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)");
|
||||
headers.set(HttpHeaders.ACCEPT, "image/*");
|
||||
|
||||
HttpEntity<String> entity = new HttpEntity<>(headers);
|
||||
|
||||
ResponseEntity<byte[]> response = restTemplate.exchange(
|
||||
imageUrl,
|
||||
HttpMethod.GET,
|
||||
entity,
|
||||
byte[].class
|
||||
);
|
||||
|
||||
// Validate and convert
|
||||
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
|
||||
return readImage(response.getBody());
|
||||
} else {
|
||||
throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode());
|
||||
}
|
||||
return downloadImageFromUrlInternal(imageUrl);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to download image from URL: {} - {}", imageUrl, e.getMessage());
|
||||
throw new IOException("Failed to download image from URL: " + imageUrl + " - " + e.getMessage(), e);
|
||||
log.warn("Failed to download image from {}: {}", imageUrl, e.getMessage());
|
||||
if (e instanceof IOException ioException) {
|
||||
throw ioException;
|
||||
}
|
||||
throw new IOException("Failed to download image from " + imageUrl + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private BufferedImage downloadImageFromUrlInternal(String imageUrl) throws IOException {
|
||||
String currentUrl = imageUrl;
|
||||
int redirectCount = 0;
|
||||
|
||||
try {
|
||||
while (redirectCount <= MAX_REDIRECTS) {
|
||||
URI uri = URI.create(currentUrl);
|
||||
// Protocol validation
|
||||
if (!"http".equalsIgnoreCase(uri.getScheme()) && !"https".equalsIgnoreCase(uri.getScheme())) {
|
||||
throw new IOException("Only HTTP and HTTPS protocols are allowed");
|
||||
}
|
||||
|
||||
String host = uri.getHost();
|
||||
if (host == null) {
|
||||
throw new IOException("Invalid URL: no host found in " + currentUrl);
|
||||
}
|
||||
|
||||
// Resolve host to IP to prevent DNS rebinding (TOCTOU)
|
||||
InetAddress[] inetAddresses = InetAddress.getAllByName(host);
|
||||
if (inetAddresses.length == 0) {
|
||||
throw new IOException("Could not resolve host: " + host);
|
||||
}
|
||||
for (InetAddress inetAddress : inetAddresses) {
|
||||
if (isInternalAddress(inetAddress)) {
|
||||
throw new SecurityException("URL points to a local or private internal network address: " + host + " (" + inetAddress.getHostAddress() + ")");
|
||||
}
|
||||
}
|
||||
String ipAddress = inetAddresses[0].getHostAddress();
|
||||
|
||||
// Set target host for SNI / Hostname verification in RestTemplate/SSLSocketFactory
|
||||
setTargetHost(host);
|
||||
|
||||
// Build request URL with IP address to ensure we connect to the validated address.
|
||||
// We keep the original URI's path and query.
|
||||
String portSuffix = (uri.getPort() != -1) ? ":" + uri.getPort() : "";
|
||||
String path = uri.getRawPath();
|
||||
if (path == null || path.isEmpty()) path = "/";
|
||||
String query = uri.getRawQuery();
|
||||
|
||||
// Handle IPv6 address formatting in URL
|
||||
String hostInUrl = ipAddress;
|
||||
if (ipAddress.contains(":")) {
|
||||
hostInUrl = "[" + ipAddress + "]";
|
||||
}
|
||||
String requestUrl = uri.getScheme() + "://" + hostInUrl + portSuffix + path + (query != null ? "?" + query : "");
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
// Set original 'Host' header for server-side virtual hosting
|
||||
headers.set(HttpHeaders.HOST, host);
|
||||
headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)");
|
||||
headers.set(HttpHeaders.ACCEPT, "image/*");
|
||||
|
||||
HttpEntity<String> entity = new HttpEntity<>(headers);
|
||||
|
||||
log.debug("Downloading image via IP-based URL: {} (Original host: {})", requestUrl, host);
|
||||
|
||||
ResponseEntity<byte[]> response = noRedirectRestTemplate.exchange(
|
||||
requestUrl,
|
||||
HttpMethod.GET,
|
||||
entity,
|
||||
byte[].class
|
||||
);
|
||||
|
||||
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
|
||||
return readImage(response.getBody());
|
||||
} else if (response.getStatusCode().is3xxRedirection()) {
|
||||
String location = response.getHeaders().getFirst(HttpHeaders.LOCATION);
|
||||
if (location == null) {
|
||||
throw new IOException("Redirection response without Location header");
|
||||
}
|
||||
// Resolve location against CURRENT URL (which has the hostname)
|
||||
currentUrl = uri.resolve(location).toString();
|
||||
redirectCount++;
|
||||
} else {
|
||||
throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode());
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// Ensure thread-local is cleared to prevent leakage to subsequent requests (container thread reuse)
|
||||
clearTargetHost();
|
||||
}
|
||||
|
||||
throw new IOException("Too many redirects (max " + MAX_REDIRECTS + ")");
|
||||
}
|
||||
|
||||
private boolean isInternalAddress(InetAddress address) {
|
||||
if (address.isLoopbackAddress() || address.isLinkLocalAddress() ||
|
||||
address.isSiteLocalAddress() || address.isAnyLocalAddress()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
byte[] addr = address.getAddress();
|
||||
// Check for IPv6 Unique Local Address (fc00::/7)
|
||||
if (addr.length == 16) {
|
||||
if ((addr[0] & 0xFE) == (byte) 0xFC) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle IPv4-mapped IPv6 addresses (::ffff:127.0.0.1)
|
||||
if (isIpv4MappedAddress(addr)) {
|
||||
try {
|
||||
byte[] ipv4Bytes = new byte[4];
|
||||
System.arraycopy(addr, 12, ipv4Bytes, 0, 4);
|
||||
InetAddress ipv4Addr = InetAddress.getByAddress(ipv4Bytes);
|
||||
return isInternalAddress(ipv4Addr);
|
||||
} catch (java.net.UnknownHostException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isIpv4MappedAddress(byte[] addr) {
|
||||
if (addr.length != 16) return false;
|
||||
for (int i = 0; i < 10; i++) {
|
||||
if (addr[i] != 0) return false;
|
||||
}
|
||||
return (addr[10] == (byte) 0xFF) && (addr[11] == (byte) 0xFF);
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// COVER OPERATIONS
|
||||
// ========================================
|
||||
|
||||
@@ -12,8 +12,11 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@UtilityClass
|
||||
@Slf4j
|
||||
@@ -147,6 +150,43 @@ public class FileUtils {
|
||||
}
|
||||
}
|
||||
|
||||
private static final Pattern LEADING_NUMBER_PREFIX = Pattern.compile("^\\d{1,3}(?:\\.|\\s*-)\\s*");
|
||||
private static final Pattern PART_DISC_INDICATOR = Pattern.compile(
|
||||
"\\s*[\\(\\[\\-]?\\s*(?:part|pt|dis[ck]|cd)\\s*\\d+\\s*[\\)\\]]?\\s*$",
|
||||
Pattern.CASE_INSENSITIVE
|
||||
);
|
||||
private static final Pattern TRAILING_NUMBERS = Pattern.compile("\\s*\\d+\\s*$");
|
||||
private static final Set<String> GENERIC_AUDIO_TITLES = Set.of(
|
||||
"chapter", "track", "part", "disc", "disk", "cd", "side", "intro", "epilogue", "prologue", "outro"
|
||||
);
|
||||
|
||||
/**
|
||||
* Determines if a list of audio files represents a series folder (each file is a separate book)
|
||||
* rather than a multi-file audiobook (chapter files for one book).
|
||||
*
|
||||
* Extracts a "base title" from each file by stripping numbering, part indicators, and extensions,
|
||||
* then counts distinct non-generic titles. If more than one distinct title exists, it's a series folder.
|
||||
*/
|
||||
public boolean isSeriesFolder(List<Path> audioFiles) {
|
||||
Set<String> distinctTitles = new HashSet<>();
|
||||
for (Path file : audioFiles) {
|
||||
String title = extractBaseTitle(file.getFileName().toString());
|
||||
if (!title.isEmpty() && !GENERIC_AUDIO_TITLES.contains(title)) {
|
||||
distinctTitles.add(title);
|
||||
}
|
||||
}
|
||||
return distinctTitles.size() > 1;
|
||||
}
|
||||
|
||||
private String extractBaseTitle(String fileName) {
|
||||
int lastDot = fileName.lastIndexOf('.');
|
||||
String baseName = lastDot > 0 ? fileName.substring(0, lastDot) : fileName;
|
||||
baseName = LEADING_NUMBER_PREFIX.matcher(baseName).replaceFirst("");
|
||||
baseName = PART_DISC_INDICATOR.matcher(baseName).replaceAll("");
|
||||
baseName = TRAILING_NUMBERS.matcher(baseName).replaceAll("");
|
||||
return baseName.toLowerCase().trim();
|
||||
}
|
||||
|
||||
public void deleteDirectoryRecursively(Path path) throws IOException {
|
||||
if (!Files.exists(path)) return;
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import javax.xml.parsers.ParserConfigurationException;
|
||||
@UtilityClass
|
||||
public class SecureXmlUtils {
|
||||
|
||||
public static DocumentBuilderFactory createSecureDocumentBuilderFactory(boolean namespaceAware) {
|
||||
public static DocumentBuilderFactory createSecureDocumentBuilderFactory(boolean namespaceAware) throws ParserConfigurationException {
|
||||
try {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(namespaceAware);
|
||||
@@ -27,10 +27,8 @@ public class SecureXmlUtils {
|
||||
|
||||
return factory;
|
||||
} catch (ParserConfigurationException e) {
|
||||
log.warn("Failed to configure secure XML parser, using defaults: {}", e.getMessage());
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(namespaceAware);
|
||||
return factory;
|
||||
log.error("CRITICAL: Failed to configure secure XML parser: {}", e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package org.booklore.util;
|
||||
|
||||
import lombok.experimental.UtilityClass;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
@UtilityClass
|
||||
public class UnrarHelper {
|
||||
|
||||
private static final String UNRAR_BIN_ENV = "BOOKLORE_UNRAR_BIN";
|
||||
private static final String DEFAULT_UNRAR_BIN = "unrar";
|
||||
private static final int PROCESS_TIMEOUT_SECONDS = 120;
|
||||
private static volatile Boolean cachedAvailability;
|
||||
|
||||
public static boolean isAvailable() {
|
||||
if (cachedAvailability != null) {
|
||||
return cachedAvailability;
|
||||
}
|
||||
synchronized (UnrarHelper.class) {
|
||||
if (cachedAvailability != null) {
|
||||
return cachedAvailability;
|
||||
}
|
||||
try {
|
||||
Process process = new ProcessBuilder(getUnrarBin())
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
try (InputStream is = process.getInputStream()) {
|
||||
is.readAllBytes();
|
||||
}
|
||||
boolean finished = process.waitFor(5, TimeUnit.SECONDS);
|
||||
cachedAvailability = finished;
|
||||
} catch (Exception e) {
|
||||
log.debug("unrar binary not available: {}", e.getMessage());
|
||||
cachedAvailability = false;
|
||||
}
|
||||
if (cachedAvailability) {
|
||||
log.info("unrar CLI detected, RAR5 fallback enabled");
|
||||
}
|
||||
return cachedAvailability;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<String> listEntries(Path rarPath) throws IOException {
|
||||
ProcessBuilder pb = new ProcessBuilder(getUnrarBin(), "lb", rarPath.toAbsolutePath().toString());
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
String output;
|
||||
try (InputStream is = process.getInputStream()) {
|
||||
output = new String(is.readAllBytes());
|
||||
}
|
||||
try {
|
||||
if (!process.waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException("unrar list timed out for: " + rarPath);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("unrar list interrupted", e);
|
||||
}
|
||||
if (process.exitValue() != 0) {
|
||||
throw new IOException("unrar list failed (exit " + process.exitValue() + ") for: " + rarPath);
|
||||
}
|
||||
return Arrays.stream(output.split("\n"))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public static void extractEntry(Path rarPath, String entryName, OutputStream out) throws IOException {
|
||||
ProcessBuilder pb = new ProcessBuilder(
|
||||
getUnrarBin(), "p", "-inul", rarPath.toAbsolutePath().toString(), entryName
|
||||
);
|
||||
pb.redirectErrorStream(false);
|
||||
Process process = pb.start();
|
||||
try (InputStream is = process.getInputStream()) {
|
||||
is.transferTo(out);
|
||||
}
|
||||
try {
|
||||
if (!process.waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException("unrar extract timed out for entry: " + entryName);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("unrar extract interrupted", e);
|
||||
}
|
||||
if (process.exitValue() != 0) {
|
||||
throw new IOException("unrar extract failed (exit " + process.exitValue() + ") for entry: " + entryName);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] extractEntryBytes(Path rarPath, String entryName) throws IOException {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
extractEntry(rarPath, entryName, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
public static void extractAll(Path rarPath, Path targetDir) throws IOException {
|
||||
ProcessBuilder pb = new ProcessBuilder(
|
||||
getUnrarBin(), "x", "-o+", rarPath.toAbsolutePath().toString(), targetDir.toAbsolutePath() + "/"
|
||||
);
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
try (InputStream is = process.getInputStream()) {
|
||||
is.readAllBytes();
|
||||
}
|
||||
try {
|
||||
if (!process.waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException("unrar extractAll timed out for: " + rarPath);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("unrar extractAll interrupted", e);
|
||||
}
|
||||
if (process.exitValue() != 0) {
|
||||
throw new IOException("unrar extractAll failed (exit " + process.exitValue() + ") for: " + rarPath);
|
||||
}
|
||||
}
|
||||
|
||||
private static String getUnrarBin() {
|
||||
String env = System.getenv(UNRAR_BIN_ENV);
|
||||
return (env != null && !env.isBlank()) ? env : DEFAULT_UNRAR_BIN;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
package org.booklore.util.kobo;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.util.RequestUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
@Component
|
||||
@@ -17,10 +20,30 @@ public class KoboUrlBuilder {
|
||||
.replacePath("")
|
||||
.replaceQuery(null);
|
||||
|
||||
UriComponents built = builder.build();
|
||||
if (built.getPort() == -1 && !hasForwardedHeaders()) {
|
||||
int localPort = RequestUtils.getCurrentRequest().getLocalPort();
|
||||
if (!isDefaultPort(built.getScheme(), localPort)) {
|
||||
builder.port(localPort);
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("Final base URL: {}", builder.build().toUriString());
|
||||
return builder;
|
||||
}
|
||||
|
||||
private boolean hasForwardedHeaders() {
|
||||
HttpServletRequest request = RequestUtils.getCurrentRequest();
|
||||
return request.getHeader("X-Forwarded-Host") != null
|
||||
|| request.getHeader("X-Forwarded-Port") != null
|
||||
|| request.getHeader("X-Forwarded-Proto") != null
|
||||
|| request.getHeader("Forwarded") != null;
|
||||
}
|
||||
|
||||
private boolean isDefaultPort(String scheme, int port) {
|
||||
return ("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443);
|
||||
}
|
||||
|
||||
public String downloadUrl(String token, Long bookId) {
|
||||
return baseBuilder()
|
||||
.pathSegment("api", "kobo", token, "v1", "books", "{bookId}", "download")
|
||||
|
||||
@@ -2,6 +2,13 @@ app:
|
||||
path-config: '/app/data'
|
||||
bookdrop-folder: '/bookdrop'
|
||||
version: 'development'
|
||||
|
||||
cors:
|
||||
# Comma-separated list of allowed CORS origins.
|
||||
# Leave empty (default) to allow same-origin requests only.
|
||||
# Example: ALLOWED_ORIGINS=https://app.example.com,https://mobile.example.com
|
||||
allowed-origins: ${ALLOWED_ORIGINS:*}
|
||||
|
||||
remote-auth:
|
||||
enabled: ${REMOTE_AUTH_ENABLED:false}
|
||||
create-new-users: ${REMOTE_AUTH_CREATE_NEW_USERS:true}
|
||||
@@ -28,6 +35,9 @@ server:
|
||||
relaxed-query-chars: '[,],%,{,},|'
|
||||
|
||||
spring:
|
||||
jackson:
|
||||
deserialization:
|
||||
fail-on-null-for-primitives: false
|
||||
servlet:
|
||||
multipart:
|
||||
enabled: false
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package org.booklore.service;
|
||||
|
||||
import org.booklore.model.dto.BookMetadata;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookMetadataEntity;
|
||||
import org.booklore.service.kobo.CbxConversionService;
|
||||
import org.booklore.service.metadata.extractor.CbxMetadataExtractor;
|
||||
import org.booklore.service.metadata.writer.CbxMetadataWriter;
|
||||
import org.booklore.service.reader.CbxReaderService;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assumptions.assumeThat;
|
||||
|
||||
/**
|
||||
* Integration tests that feed a real RAR5 archive into the service layer
|
||||
* and verify junrar fails then the unrar CLI fallback kicks in.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class Rar5FallbackIntegrationTest {
|
||||
|
||||
private static final Path RAR5_CBR = Path.of("src/test/resources/cbx/test-rar5.cbr");
|
||||
|
||||
@BeforeAll
|
||||
static void checkUnrarAvailable() {
|
||||
assumeThat(UnrarHelper.isAvailable())
|
||||
.as("unrar binary must be on PATH to run these tests")
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
// -- CbxMetadataExtractor: extractMetadata fallback --
|
||||
|
||||
@Test
|
||||
void metadataExtractor_extractsComicInfoFromRar5(@TempDir Path tempDir) throws Exception {
|
||||
Path cbrCopy = tempDir.resolve("test.cbr");
|
||||
Files.copy(RAR5_CBR, cbrCopy);
|
||||
|
||||
CbxMetadataExtractor extractor = new CbxMetadataExtractor();
|
||||
BookMetadata metadata = extractor.extractMetadata(cbrCopy.toFile());
|
||||
|
||||
assertThat(metadata.getTitle()).isEqualTo("Test RAR5 Comic");
|
||||
assertThat(metadata.getSeriesName()).isEqualTo("RAR5 Test Series");
|
||||
assertThat(metadata.getSeriesNumber()).isEqualTo(1.0f);
|
||||
assertThat(metadata.getAuthors()).contains("Test Author");
|
||||
}
|
||||
|
||||
// -- CbxReaderService: getImageEntriesFromRar + streamEntryFromRar fallback --
|
||||
|
||||
@Test
|
||||
void readerService_listsImagePagesFromRar5(@TempDir Path tempDir) throws Exception {
|
||||
Path cbrCopy = tempDir.resolve("test.cbr");
|
||||
Files.copy(RAR5_CBR, cbrCopy);
|
||||
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(99L);
|
||||
BookRepository mockRepo = org.mockito.Mockito.mock(BookRepository.class);
|
||||
org.mockito.Mockito.when(mockRepo.findById(99L)).thenReturn(java.util.Optional.of(book));
|
||||
|
||||
try (var fileUtilsStatic = org.mockito.Mockito.mockStatic(org.booklore.util.FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> org.booklore.util.FileUtils.getBookFullPath(book))
|
||||
.thenReturn(cbrCopy.toString());
|
||||
|
||||
CbxReaderService readerService = new CbxReaderService(mockRepo);
|
||||
List<Integer> pages = readerService.getAvailablePages(99L);
|
||||
|
||||
assertThat(pages).hasSize(3);
|
||||
assertThat(pages).containsExactly(1, 2, 3);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void readerService_streamsImageFromRar5(@TempDir Path tempDir) throws Exception {
|
||||
Path cbrCopy = tempDir.resolve("test.cbr");
|
||||
Files.copy(RAR5_CBR, cbrCopy);
|
||||
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(99L);
|
||||
BookRepository mockRepo = org.mockito.Mockito.mock(BookRepository.class);
|
||||
org.mockito.Mockito.when(mockRepo.findById(99L)).thenReturn(java.util.Optional.of(book));
|
||||
|
||||
try (var fileUtilsStatic = org.mockito.Mockito.mockStatic(org.booklore.util.FileUtils.class)) {
|
||||
fileUtilsStatic.when(() -> org.booklore.util.FileUtils.getBookFullPath(book))
|
||||
.thenReturn(cbrCopy.toString());
|
||||
|
||||
CbxReaderService readerService = new CbxReaderService(mockRepo);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
readerService.streamPageImage(99L, 1, out);
|
||||
|
||||
byte[] imageBytes = out.toByteArray();
|
||||
assertThat(imageBytes).hasSizeGreaterThan(0);
|
||||
assertThat(imageBytes[0]).isEqualTo((byte) 0xFF);
|
||||
assertThat(imageBytes[1]).isEqualTo((byte) 0xD8);
|
||||
}
|
||||
}
|
||||
|
||||
// -- CbxConversionService: extractImagesFromRar fallback --
|
||||
|
||||
@Test
|
||||
void conversionService_extractsImagesFromRar5(@TempDir Path tempDir) throws Exception {
|
||||
Path cbrCopy = tempDir.resolve("test.cbr");
|
||||
Files.copy(RAR5_CBR, cbrCopy);
|
||||
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(99L);
|
||||
BookMetadataEntity meta = new BookMetadataEntity();
|
||||
meta.setTitle("Test RAR5 Comic");
|
||||
book.setMetadata(meta);
|
||||
|
||||
CbxConversionService conversionService = new CbxConversionService();
|
||||
File epub = conversionService.convertCbxToEpub(cbrCopy.toFile(), tempDir.toFile(), book, 85);
|
||||
|
||||
assertThat(epub).exists();
|
||||
assertThat(epub.length()).isGreaterThan(0);
|
||||
|
||||
try (ZipFile epubZip = new ZipFile(epub)) {
|
||||
ZipEntry mimetype = epubZip.getEntry("mimetype");
|
||||
assertThat(mimetype).isNotNull();
|
||||
|
||||
List<String> imageEntries = epubZip.stream()
|
||||
.map(ZipEntry::getName)
|
||||
.filter(name -> name.startsWith("OEBPS/Images/page-"))
|
||||
.toList();
|
||||
assertThat(imageEntries).hasSize(3);
|
||||
}
|
||||
}
|
||||
|
||||
// -- CbxMetadataWriter: loadFromRar + convertRarToZipArchive fallback --
|
||||
|
||||
@Test
|
||||
void metadataWriter_convertsRar5ToCbzViaFallback(@TempDir Path tempDir) throws Exception {
|
||||
Path cbrCopy = tempDir.resolve("test.cbr");
|
||||
Files.copy(RAR5_CBR, cbrCopy);
|
||||
|
||||
AppSettingService mockSettings = org.mockito.Mockito.mock(AppSettingService.class);
|
||||
var appSettings = new org.booklore.model.dto.settings.AppSettings();
|
||||
var persistenceSettings = new org.booklore.model.dto.settings.MetadataPersistenceSettings();
|
||||
var saveToFile = new org.booklore.model.dto.settings.MetadataPersistenceSettings.SaveToOriginalFile();
|
||||
var cbxSettings = new org.booklore.model.dto.settings.MetadataPersistenceSettings.FormatSettings();
|
||||
cbxSettings.setEnabled(true);
|
||||
cbxSettings.setMaxFileSizeInMb(500);
|
||||
saveToFile.setCbx(cbxSettings);
|
||||
persistenceSettings.setSaveToOriginalFile(saveToFile);
|
||||
appSettings.setMetadataPersistenceSettings(persistenceSettings);
|
||||
org.mockito.Mockito.when(mockSettings.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
CbxMetadataWriter writer = new CbxMetadataWriter(mockSettings);
|
||||
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Updated RAR5 Title");
|
||||
|
||||
writer.saveMetadataToFile(cbrCopy.toFile(), metadata, null, null);
|
||||
|
||||
Path cbzPath = tempDir.resolve("test.cbz");
|
||||
assertThat(cbzPath).exists();
|
||||
|
||||
try (ZipFile resultZip = new ZipFile(cbzPath.toFile())) {
|
||||
ZipEntry comicInfo = resultZip.getEntry("ComicInfo.xml");
|
||||
assertThat(comicInfo).isNotNull();
|
||||
|
||||
String xml = new String(resultZip.getInputStream(comicInfo).readAllBytes());
|
||||
assertThat(xml).contains("Updated RAR5 Title");
|
||||
|
||||
long imageCount = resultZip.stream()
|
||||
.map(ZipEntry::getName)
|
||||
.filter(name -> name.endsWith(".jpg"))
|
||||
.count();
|
||||
assertThat(imageCount).isEqualTo(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -114,6 +114,7 @@ class MetadataMatchServiceTest {
|
||||
.isbn13(0).isbn10(0).language(0).pageCount(0).categories(0)
|
||||
.amazonRating(0).amazonReviewCount(0).goodreadsRating(0)
|
||||
.goodreadsReviewCount(0).hardcoverRating(0).hardcoverReviewCount(0)
|
||||
.doubanRating(0).doubanReviewCount(0).ranobedbRating(0).coverImage(0);
|
||||
.doubanRating(0).doubanReviewCount(0).ranobedbRating(0)
|
||||
.audibleRating(0).audibleReviewCount(0).coverImage(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -510,6 +510,152 @@ class BookFileGroupingUtilsTest {
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(basic, withAuthor);
|
||||
}
|
||||
|
||||
// ========== Part Indicator Stripping Tests ==========
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldStripPartIndicators() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero (part 1).m4b")).isEqualTo("the lost hero");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero (pt 2).m4b")).isEqualTo("the lost hero");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero (disc 1).m4b")).isEqualTo("the lost hero");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero [cd 3].m4b")).isEqualTo("the lost hero");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero - part 1.m4b")).isEqualTo("the lost hero");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldPreserveNonPartParenthetical() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (Extended Edition).epub"))
|
||||
.isEqualTo("the hobbit (extended edition)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldProduceSameKeyForMultiPartFiles() {
|
||||
String key1 = BookFileGroupingUtils.extractGroupingKey("1. The Lost Hero (part 1).m4b");
|
||||
String key2 = BookFileGroupingUtils.extractGroupingKey("1. The Lost Hero (part 2).m4b");
|
||||
assertThat(key1).isEqualTo(key2);
|
||||
}
|
||||
|
||||
// ========== Bare-Number Series Detection Tests ==========
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldNotStripBarePartAsSeriesLabel() {
|
||||
// "Part 1" without brackets/dash is a series label, not a multi-file indicator
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Harry Potter Part 1.epub"))
|
||||
.isEqualTo("harry potter part 1");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Harry Potter Part 2.epub"))
|
||||
.isEqualTo("harry potter part 2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldKeepBarePartSeriesEntriesSeparate() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile part1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Harry Potter")
|
||||
.fileName("Harry Potter Part 1.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile part2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Harry Potter")
|
||||
.fileName("Harry Potter Part 2.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(part1, part2));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldSeparateBareNumberedSeriesFiles() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile file1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Percy Jackson")
|
||||
.fileName("1. The Lightning Thief.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile file2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Percy Jackson")
|
||||
.fileName("2. The Sea of Monsters.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupMultiPartFilesOfSameBook() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile part1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus")
|
||||
.fileName("1. The Lost Hero (part 1).m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile part2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus")
|
||||
.fileName("1. The Lost Hero (part 2).m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(part1, part2));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(part1, part2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldHandleMixedPartsAndSeparateBooks() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile lostHeroPt1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus")
|
||||
.fileName("1. The Lost Hero (part 1).m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile lostHeroPt2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus")
|
||||
.fileName("1. The Lost Hero (part 2).m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile sonOfNeptune = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus")
|
||||
.fileName("2. The Son of Neptune.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(lostHeroPt1, lostHeroPt2, sonOfNeptune));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
boolean foundLostHeroGroup = groups.values().stream()
|
||||
.anyMatch(list -> list.size() == 2 && list.containsAll(List.of(lostHeroPt1, lostHeroPt2)));
|
||||
assertThat(foundLostHeroGroup).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldHandleFolderBasedAudiobook() {
|
||||
// Folder-based audiobook (MP3 folder) with ebook files
|
||||
@@ -637,6 +783,453 @@ class BookFileGroupingUtilsTest {
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, audiobook1);
|
||||
}
|
||||
|
||||
// ========== Part Indicator Pattern Edge Cases ==========
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldStripBareDiscAndCdAndPt() {
|
||||
// pt, disc, disk, cd are unambiguous and stripped even without brackets/dash
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit disc 1.m4b")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit disk 2.m4b")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit cd 3.m4b")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit pt 1.m4b")).isEqualTo("the hobbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldStripPartInSquareBrackets() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [part 1].m4b")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [Part 2].m4b")).isEqualTo("the hobbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldStripPartCaseInsensitive() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (PART 1).m4b")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (Part 1).m4b")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit - PART 1.m4b")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit DISC 1.m4b")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit CD 3.m4b")).isEqualTo("the hobbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldNotStripPartWithoutNumber() {
|
||||
// "part" keyword without a trailing number should not be stripped
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Best Part.epub")).isEqualTo("the best part");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("Disc Jockey.m4b")).isEqualTo("disc jockey");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldStripAudioFormatIndicators() {
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (m4b).m4b")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (mp3).mp3")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [audiobook].m4b")).isEqualTo("the hobbit");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (audio).m4b")).isEqualTo("the hobbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldStripFormatThenPartIndicator() {
|
||||
// Both format indicator and part indicator present
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (mp3) (part 1).mp3")).isEqualTo("the hobbit");
|
||||
}
|
||||
|
||||
// ========== Bare-Number Prefix Edge Cases ==========
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldPreserveBareNumberDotPrefix() {
|
||||
// "N. Title" prefix is preserved in the grouping key (series detection handles it separately)
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("01. The Lightning Thief.m4b")).isEqualTo("01. the lightning thief");
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("100. War and Peace.epub")).isEqualTo("100. war and peace");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldStripDashPrefixViaAuthorPattern() {
|
||||
// "01 - The Lightning Thief" looks like "number - Author Name" to the trailing author pattern,
|
||||
// so the author pattern strips it. This is expected existing behavior.
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("01 - The Lightning Thief.m4b")).isEqualTo("01");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldNotTreatFourDigitNumberAsPrefix() {
|
||||
// 4-digit numbers should not be treated as series prefixes
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("1984.epub")).isEqualTo("1984");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractGroupingKey_shouldNotTreatNumberWithoutSeparatorAsPrefix() {
|
||||
// "101 Dalmatians" has no dot or dash after the number
|
||||
assertThat(BookFileGroupingUtils.extractGroupingKey("101 Dalmatians.epub")).isEqualTo("101 dalmatians");
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldSeparateFiveBookSeriesWithBareNumbers() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
List<LibraryFile> files = new java.util.ArrayList<>();
|
||||
String[] titles = {
|
||||
"1. The Lightning Thief.m4b",
|
||||
"2. The Sea of Monsters.m4b",
|
||||
"3. The Titans Curse.m4b",
|
||||
"4. The Battle of the Labyrinth.m4b",
|
||||
"5. The Last Olympian.m4b"
|
||||
};
|
||||
for (String title : titles) {
|
||||
files.add(LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Percy Jackson")
|
||||
.fileName(title)
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build());
|
||||
}
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(files);
|
||||
|
||||
assertThat(groups).hasSize(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupSameBareNumberInMultipleFormats() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile epub = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Percy Jackson")
|
||||
.fileName("1. The Lightning Thief.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile m4b = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Percy Jackson")
|
||||
.fileName("1. The Lightning Thief.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile epub2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Percy Jackson")
|
||||
.fileName("2. The Sea of Monsters.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, m4b, epub2));
|
||||
|
||||
// Book 1 in 2 formats = 1 group, Book 2 = 1 group
|
||||
assertThat(groups).hasSize(2);
|
||||
boolean foundBook1Group = groups.values().stream()
|
||||
.anyMatch(list -> list.size() == 2 && list.containsAll(List.of(epub, m4b)));
|
||||
assertThat(foundBook1Group).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldSeparateDashPrefixedSeriesFiles() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile file1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Rick Riordan")
|
||||
.fileName("01 - The Lightning Thief.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile file2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Rick Riordan")
|
||||
.fileName("02 - The Sea of Monsters.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldHandleRootLevelBareNumberedFiles() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile file1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(null)
|
||||
.fileName("1. The Lightning Thief.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile file2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(null)
|
||||
.fileName("2. The Sea of Monsters.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2));
|
||||
|
||||
// Root-level uses exact key matching, different keys = separate groups
|
||||
assertThat(groups).hasSize(2);
|
||||
}
|
||||
|
||||
// ========== Series Detection with Various Keywords ==========
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldSeparateEpisodeSeriesEntries() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile ep1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("The Podcast")
|
||||
.fileName("The Podcast Episode 1.mp3")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile ep2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("The Podcast")
|
||||
.fileName("The Podcast Episode 2.mp3")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(ep1, ep2));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldSeparateHashNumberedSeries() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile n1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Discworld")
|
||||
.fileName("Discworld #1.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile n2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Discworld")
|
||||
.fileName("Discworld #2.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(n1, n2));
|
||||
|
||||
assertThat(groups).hasSize(2);
|
||||
}
|
||||
|
||||
// ========== Multi-Part Grouping Edge Cases ==========
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupBracketedPartsAtRootLevel() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile pt1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(null)
|
||||
.fileName("The Lost Hero (part 1).m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile pt2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(null)
|
||||
.fileName("The Lost Hero (part 2).m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(pt1, pt2));
|
||||
|
||||
// Root-level exact key matching: both produce "the lost hero" → same group
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(pt1, pt2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupDiscVariantsOfSameBook() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile d1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("War and Peace")
|
||||
.fileName("War and Peace disc 1.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile d2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("War and Peace")
|
||||
.fileName("War and Peace disc 2.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile d3 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("War and Peace")
|
||||
.fileName("War and Peace disc 3.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(d1, d2, d3));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(d1, d2, d3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupCdVariantsOfSameBook() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile cd1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Moby Dick")
|
||||
.fileName("Moby Dick cd 1.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
LibraryFile cd2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Moby Dick")
|
||||
.fileName("Moby Dick cd 2.m4b")
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(cd1, cd2));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(cd1, cd2);
|
||||
}
|
||||
|
||||
// ========== Grouping Boundary / Misc Edge Cases ==========
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldHandleEmptyList() {
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of());
|
||||
assertThat(groups).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldHandleSingleFileInFolder() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile file = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Some Folder")
|
||||
.fileName("Lonely Book.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file));
|
||||
|
||||
assertThat(groups).hasSize(1);
|
||||
assertThat(groups.values().iterator().next()).containsExactly(file);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldHandleEmptySubPath() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile file1 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("")
|
||||
.fileName("Book.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile file2 = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("")
|
||||
.fileName("Book.pdf")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2));
|
||||
|
||||
// Empty subPath treated as root level
|
||||
assertThat(groups).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldSeparateCompletelyUnrelatedFilesInFolder() {
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile war = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Random")
|
||||
.fileName("War and Peace.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile moby = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Random")
|
||||
.fileName("Moby Dick.epub")
|
||||
.bookFileType(BookFileType.EPUB)
|
||||
.build();
|
||||
|
||||
LibraryFile pride = LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Random")
|
||||
.fileName("Pride and Prejudice.pdf")
|
||||
.bookFileType(BookFileType.PDF)
|
||||
.build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(war, moby, pride));
|
||||
|
||||
assertThat(groups).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldHandleFullHeroesOfOlympusScenario() {
|
||||
// Realistic 5-book series with multi-part splits for some books
|
||||
LibraryPathEntity pathEntity = new LibraryPathEntity();
|
||||
pathEntity.setId(1L);
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
LibraryFile lh1 = LibraryFile.builder().libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus").fileName("1. The Lost Hero (part 1).m4b").bookFileType(BookFileType.AUDIOBOOK).build();
|
||||
LibraryFile lh2 = LibraryFile.builder().libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus").fileName("1. The Lost Hero (part 2).m4b").bookFileType(BookFileType.AUDIOBOOK).build();
|
||||
LibraryFile son = LibraryFile.builder().libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus").fileName("2. The Son of Neptune.m4b").bookFileType(BookFileType.AUDIOBOOK).build();
|
||||
LibraryFile moa1 = LibraryFile.builder().libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus").fileName("3. The Mark of Athena (part 1).m4b").bookFileType(BookFileType.AUDIOBOOK).build();
|
||||
LibraryFile moa2 = LibraryFile.builder().libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus").fileName("3. The Mark of Athena (part 2).m4b").bookFileType(BookFileType.AUDIOBOOK).build();
|
||||
LibraryFile hoh = LibraryFile.builder().libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus").fileName("4. The House of Hades.m4b").bookFileType(BookFileType.AUDIOBOOK).build();
|
||||
LibraryFile boo = LibraryFile.builder().libraryPathEntity(pathEntity)
|
||||
.fileSubPath("Heroes of Olympus").fileName("5. The Blood of Olympus.m4b").bookFileType(BookFileType.AUDIOBOOK).build();
|
||||
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(lh1, lh2, son, moa1, moa2, hoh, boo));
|
||||
|
||||
// 5 books: Lost Hero (2 parts grouped), Son of Neptune, Mark of Athena (2 parts grouped), House of Hades, Blood of Olympus
|
||||
assertThat(groups).hasSize(5);
|
||||
boolean lhGrouped = groups.values().stream().anyMatch(l -> l.size() == 2 && l.containsAll(List.of(lh1, lh2)));
|
||||
boolean moaGrouped = groups.values().stream().anyMatch(l -> l.size() == 2 && l.containsAll(List.of(moa1, moa2)));
|
||||
assertThat(lhGrouped).isTrue();
|
||||
assertThat(moaGrouped).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupByBaseName_shouldGroupFolderWithDotInName() {
|
||||
// Folder-based audiobook with dot in name like "1. American Gods - Neil Gaiman (2011)"
|
||||
|
||||
@@ -18,6 +18,7 @@ import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
@@ -61,7 +62,9 @@ class FileServiceTest {
|
||||
.build();
|
||||
lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
fileService = new FileService(appProperties, mock(RestTemplate.class), appSettingService);
|
||||
RestTemplate mockRestTemplate = mock(RestTemplate.class);
|
||||
RestTemplate mockNoRedirectRestTemplate = mock(RestTemplate.class);
|
||||
fileService = new FileService(appProperties, mockRestTemplate, appSettingService, mockNoRedirectRestTemplate);
|
||||
}
|
||||
|
||||
@Nested
|
||||
@@ -374,9 +377,9 @@ class FileServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidData_returnsNull() throws IOException {
|
||||
void invalidData_throwsException() {
|
||||
byte[] invalidData = "not an image".getBytes();
|
||||
assertNull(FileService.readImage(invalidData));
|
||||
assertThrows(IOException.class, () -> FileService.readImage(invalidData));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -485,11 +488,11 @@ class FileServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidImageData_skipsSave() {
|
||||
void invalidImageData_throwsException() {
|
||||
byte[] invalidData = "not an image".getBytes();
|
||||
Path outputPath = tempDir.resolve("invalid.jpg");
|
||||
|
||||
assertDoesNotThrow(() ->
|
||||
assertThrows(IOException.class, () ->
|
||||
FileService.saveImage(invalidData, outputPath.toString()));
|
||||
assertFalse(Files.exists(outputPath));
|
||||
}
|
||||
@@ -913,12 +916,11 @@ class FileServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidImageBytes_skipsThumbnail() {
|
||||
void invalidImageBytes_throwsException() {
|
||||
byte[] invalidData = "not an image".getBytes();
|
||||
|
||||
assertDoesNotThrow(() ->
|
||||
assertThrows(RuntimeException.class, () ->
|
||||
fileService.createThumbnailFromBytes(16L, invalidData));
|
||||
assertFalse(Files.exists(Path.of(fileService.getCoverFile(16L))));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1031,15 +1033,14 @@ class FileServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void corruptImageData_skipsThumbnail() {
|
||||
void corruptImageData_throwsException() {
|
||||
// Valid MIME type but corrupt image data
|
||||
byte[] corruptData = ("not an image but has jpeg mime type").getBytes();
|
||||
MockMultipartFile corruptFile = new MockMultipartFile(
|
||||
"file", "corrupt.jpg", "image/jpeg", corruptData);
|
||||
|
||||
assertDoesNotThrow(() ->
|
||||
assertThrows(RuntimeException.class, () ->
|
||||
fileService.createThumbnailFromFile(12L, corruptFile));
|
||||
assertFalse(Files.exists(Path.of(fileService.getCoverFile(12L))));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1176,7 +1177,7 @@ class FileServiceTest {
|
||||
.build();
|
||||
lenient().when(appSettingServiceForNetwork.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
fileService = new FileService(appProperties, restTemplate, appSettingServiceForNetwork);
|
||||
fileService = new FileService(appProperties, restTemplate, appSettingServiceForNetwork, restTemplate);
|
||||
}
|
||||
|
||||
@Nested
|
||||
@@ -1187,17 +1188,17 @@ class FileServiceTest {
|
||||
@DisplayName("downloads and returns valid image")
|
||||
@Timeout(5)
|
||||
void downloadImageFromUrl_validImage_returnsBufferedImage() throws IOException {
|
||||
String imageUrl = "http://example.com/image.jpg";
|
||||
String imageUrl = "http://1.1.1.1/image.jpg";
|
||||
BufferedImage testImage = createTestImage(100, 100);
|
||||
byte[] imageBytes = imageToBytes(testImage);
|
||||
|
||||
RestTemplate mockRestTemplate = mock(RestTemplate.class);
|
||||
AppSettingService mockAppSettingService = mock(AppSettingService.class);
|
||||
FileService testFileService = new FileService(appProperties, mockRestTemplate, mockAppSettingService);
|
||||
FileService testFileService = new FileService(appProperties, mockRestTemplate, mockAppSettingService, mockRestTemplate);
|
||||
|
||||
ResponseEntity<byte[]> responseEntity = ResponseEntity.ok(imageBytes);
|
||||
when(mockRestTemplate.exchange(
|
||||
eq(imageUrl),
|
||||
anyString(),
|
||||
eq(HttpMethod.GET),
|
||||
any(HttpEntity.class),
|
||||
eq(byte[].class)
|
||||
@@ -1214,10 +1215,10 @@ class FileServiceTest {
|
||||
@DisplayName("throws exception when response body is null")
|
||||
@Timeout(5)
|
||||
void downloadImageFromUrl_nullBody_throwsException() {
|
||||
String imageUrl = "http://example.com/image.jpg";
|
||||
String imageUrl = "http://1.1.1.1/image.jpg";
|
||||
ResponseEntity<byte[]> responseEntity = ResponseEntity.ok(null);
|
||||
when(restTemplate.exchange(
|
||||
eq(imageUrl),
|
||||
anyString(),
|
||||
eq(HttpMethod.GET),
|
||||
any(HttpEntity.class),
|
||||
eq(byte[].class)
|
||||
@@ -1228,31 +1229,38 @@ class FileServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("returns null when ImageIO cannot read bytes")
|
||||
@DisplayName("throws IOException when ImageIO cannot read bytes")
|
||||
@Timeout(5)
|
||||
void downloadImageFromUrl_invalidImageData_returnsNull() throws IOException {
|
||||
String imageUrl = "http://example.com/image.jpg";
|
||||
void downloadImageFromUrl_invalidImageData_throwsException() throws IOException {
|
||||
String imageUrl = "http://1.1.1.1/image.jpg";
|
||||
byte[] invalidBytes = "not an image".getBytes();
|
||||
ResponseEntity<byte[]> responseEntity = ResponseEntity.ok(invalidBytes);
|
||||
when(restTemplate.exchange(
|
||||
eq(imageUrl),
|
||||
// Note: using ReflectionTestUtils to get the private mock if needed,
|
||||
// but wait, setup() already created fileService with mocks.
|
||||
// We just need to know which mock to use.
|
||||
// The setup() creates and injects mockNoRedirectRestTemplate.
|
||||
|
||||
// Let's use ReflectionTestUtils to mock the correct one since the field in test class is 'restTemplate'
|
||||
RestTemplate noRedirectMock = (RestTemplate) ReflectionTestUtils.getField(fileService, "noRedirectRestTemplate");
|
||||
|
||||
when(noRedirectMock.exchange(
|
||||
anyString(),
|
||||
eq(HttpMethod.GET),
|
||||
any(HttpEntity.class),
|
||||
eq(byte[].class)
|
||||
)).thenReturn(responseEntity);
|
||||
|
||||
BufferedImage result = fileService.downloadImageFromUrl(imageUrl);
|
||||
assertNull(result);
|
||||
assertThrows(IOException.class, () -> fileService.downloadImageFromUrl(imageUrl));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("throws exception on HTTP error status")
|
||||
@Timeout(5)
|
||||
void downloadImageFromUrl_httpError_throwsException() {
|
||||
String imageUrl = "http://example.com/image.jpg";
|
||||
String imageUrl = "http://1.1.1.1/image.jpg";
|
||||
ResponseEntity<byte[]> responseEntity = ResponseEntity.notFound().build();
|
||||
when(restTemplate.exchange(
|
||||
eq(imageUrl),
|
||||
anyString(),
|
||||
eq(HttpMethod.GET),
|
||||
any(HttpEntity.class),
|
||||
eq(byte[].class)
|
||||
@@ -1271,14 +1279,14 @@ class FileServiceTest {
|
||||
@DisplayName("downloads and saves cover images successfully")
|
||||
@Timeout(5)
|
||||
void createThumbnailFromUrl_validImage_createsCoverAndThumbnail() throws IOException {
|
||||
String imageUrl = "http://example.com/cover.jpg";
|
||||
String imageUrl = "http://1.1.1.1/cover.jpg";
|
||||
long bookId = 42L;
|
||||
BufferedImage testImage = createTestImage(800, 1200); // Portrait image
|
||||
byte[] imageBytes = imageToBytes(testImage);
|
||||
|
||||
ResponseEntity<byte[]> responseEntity = ResponseEntity.ok(imageBytes);
|
||||
when(restTemplate.exchange(
|
||||
eq(imageUrl),
|
||||
anyString(),
|
||||
eq(HttpMethod.GET),
|
||||
any(HttpEntity.class),
|
||||
eq(byte[].class)
|
||||
@@ -1304,7 +1312,7 @@ class FileServiceTest {
|
||||
long bookId = 42L;
|
||||
|
||||
when(restTemplate.exchange(
|
||||
eq(imageUrl),
|
||||
anyString(),
|
||||
eq(HttpMethod.GET),
|
||||
any(HttpEntity.class),
|
||||
eq(byte[].class)
|
||||
|
||||
@@ -189,9 +189,251 @@ class FileUtilsTest {
|
||||
void testGetFileSizeInKb_validFile_returnsSize() throws IOException {
|
||||
Path file = tempDir.resolve("test.txt");
|
||||
Files.write(file, "test".getBytes());
|
||||
|
||||
|
||||
Long size = FileUtils.getFileSizeInKb(file);
|
||||
assertNotNull(size, "File size should not be null for existing file");
|
||||
assertTrue(size >= 0, "File size should be non-negative");
|
||||
}
|
||||
|
||||
// ========== isSeriesFolder Tests ==========
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_distinctTitles_returnsTrue() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("1. The Lightning Thief.m4b"),
|
||||
Path.of("2. The Sea of Monsters.m4b"),
|
||||
Path.of("3. The Titans Curse.m4b")
|
||||
);
|
||||
assertTrue(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_chapterFiles_returnsFalse() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("Chapter 01.mp3"),
|
||||
Path.of("Chapter 02.mp3"),
|
||||
Path.of("Chapter 03.mp3")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_bareNumberedTracks_returnsFalse() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("01.mp3"),
|
||||
Path.of("02.mp3"),
|
||||
Path.of("03.mp3")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_trackFiles_returnsFalse() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("Track 01.mp3"),
|
||||
Path.of("Track 02.mp3"),
|
||||
Path.of("Track 03.mp3")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_mixedWithParts_returnsTrue() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("1. The Lost Hero (part 1).m4b"),
|
||||
Path.of("1. The Lost Hero (part 2).m4b"),
|
||||
Path.of("2. The Son of Neptune.m4b")
|
||||
);
|
||||
assertTrue(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_singleFile_returnsFalse() {
|
||||
List<Path> files = List.of(Path.of("The Lightning Thief.m4b"));
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_dashSeparatedNumbers_returnsTrue() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("01 - The Lightning Thief.m4b"),
|
||||
Path.of("02 - The Sea of Monsters.m4b")
|
||||
);
|
||||
assertTrue(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_emptyList_returnsFalse() {
|
||||
assertFalse(FileUtils.isSeriesFolder(List.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_allSameTitle_returnsFalse() {
|
||||
// Same book split across multiple files (no number prefix)
|
||||
List<Path> files = List.of(
|
||||
Path.of("The Lightning Thief.m4b"),
|
||||
Path.of("The Lightning Thief.mp3")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_sameTitleWithParts_returnsFalse() {
|
||||
// Same book split into parts: after stripping part indicators, all produce same title
|
||||
List<Path> files = List.of(
|
||||
Path.of("The Lightning Thief (part 1).m4b"),
|
||||
Path.of("The Lightning Thief (part 2).m4b"),
|
||||
Path.of("The Lightning Thief (part 3).m4b")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_genericPartTitles_returnsFalse() {
|
||||
// "Part" is in the generic list, so "Part 1", "Part 2" → stripped to "part" → generic
|
||||
List<Path> files = List.of(
|
||||
Path.of("Part 1.mp3"),
|
||||
Path.of("Part 2.mp3"),
|
||||
Path.of("Part 3.mp3")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_genericDiscTitles_returnsFalse() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("Disc 1.mp3"),
|
||||
Path.of("Disc 2.mp3")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_genericSideTitles_returnsFalse() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("Side 1.mp3"),
|
||||
Path.of("Side 2.mp3")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_genericIntroEpilogue_returnsFalse() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("Intro.mp3"),
|
||||
Path.of("Epilogue.mp3")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_genericOutro_returnsFalse() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("Intro.mp3"),
|
||||
Path.of("Outro.mp3")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_mixedGenericAndRealTitles_returnsFalse() {
|
||||
// Only one non-generic title → not > 1 distinct → not a series
|
||||
List<Path> files = List.of(
|
||||
Path.of("Intro.mp3"),
|
||||
Path.of("Chapter 01.mp3"),
|
||||
Path.of("The Lightning Thief.m4b")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_mixedCaseFileNames_returnsTrue() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("1. THE LIGHTNING THIEF.M4B"),
|
||||
Path.of("2. the Sea of Monsters.m4b")
|
||||
);
|
||||
assertTrue(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_noExtension_returnsTrue() {
|
||||
// Files without dots in the name (no extension confusion)
|
||||
List<Path> files = List.of(
|
||||
Path.of("The Lightning Thief"),
|
||||
Path.of("The Sea of Monsters")
|
||||
);
|
||||
assertTrue(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_zeroPaddedNumbers_returnsTrue() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("001. A Game of Thrones.m4b"),
|
||||
Path.of("002. A Clash of Kings.m4b"),
|
||||
Path.of("003. A Storm of Swords.m4b")
|
||||
);
|
||||
assertTrue(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_numberedPartsOfSameBook_returnsFalse() {
|
||||
// Same book number but different parts → single distinct title after stripping
|
||||
List<Path> files = List.of(
|
||||
Path.of("1. The Lost Hero (part 1).m4b"),
|
||||
Path.of("1. The Lost Hero (part 2).m4b"),
|
||||
Path.of("1. The Lost Hero (part 3).m4b")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_twoDistinctAmongManyParts_returnsTrue() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("1. The Lost Hero (part 1).m4b"),
|
||||
Path.of("1. The Lost Hero (part 2).m4b"),
|
||||
Path.of("1. The Lost Hero (part 3).m4b"),
|
||||
Path.of("2. The Son of Neptune (part 1).m4b"),
|
||||
Path.of("2. The Son of Neptune (part 2).m4b")
|
||||
);
|
||||
assertTrue(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_titlesWithSpecialCharacters_returnsTrue() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("1. The Lion, the Witch & the Wardrobe.m4b"),
|
||||
Path.of("2. Prince Caspian.m4b")
|
||||
);
|
||||
assertTrue(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_prologueAndChapters_returnsFalse() {
|
||||
// All generic: prologue, chapter, epilogue
|
||||
List<Path> files = List.of(
|
||||
Path.of("Prologue.mp3"),
|
||||
Path.of("Chapter 01.mp3"),
|
||||
Path.of("Chapter 02.mp3"),
|
||||
Path.of("Chapter 03.mp3"),
|
||||
Path.of("Epilogue.mp3")
|
||||
);
|
||||
assertFalse(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSeriesFolder_largeSeriesFolder_returnsTrue() {
|
||||
List<Path> files = List.of(
|
||||
Path.of("01. The Colour of Magic.m4b"),
|
||||
Path.of("02. The Light Fantastic.m4b"),
|
||||
Path.of("03. Equal Rites.m4b"),
|
||||
Path.of("04. Mort.m4b"),
|
||||
Path.of("05. Sourcery.m4b"),
|
||||
Path.of("06. Wyrd Sisters.m4b"),
|
||||
Path.of("07. Pyramids.m4b"),
|
||||
Path.of("08. Guards Guards.m4b"),
|
||||
Path.of("09. Eric.m4b"),
|
||||
Path.of("10. Moving Pictures.m4b")
|
||||
);
|
||||
assertTrue(FileUtils.isSeriesFolder(files));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package org.booklore.util;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assumptions.assumeThat;
|
||||
|
||||
class UnrarHelperIntegrationTest {
|
||||
|
||||
private static final Path RAR5_CBR = Path.of("src/test/resources/cbx/test-rar5.cbr");
|
||||
|
||||
@BeforeAll
|
||||
static void checkUnrarAvailable() {
|
||||
assumeThat(UnrarHelper.isAvailable())
|
||||
.as("unrar binary must be on PATH to run these tests")
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listEntries_returnsAllEntriesFromRar5Archive() throws IOException {
|
||||
List<String> entries = UnrarHelper.listEntries(RAR5_CBR);
|
||||
|
||||
assertThat(entries).containsExactly(
|
||||
"ComicInfo.xml",
|
||||
"page_001.jpg",
|
||||
"page_002.jpg",
|
||||
"page_003.jpg"
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractEntryBytes_extractsComicInfoXml() throws IOException {
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(RAR5_CBR, "ComicInfo.xml");
|
||||
String xml = new String(bytes);
|
||||
|
||||
assertThat(xml).contains("<Title>Test RAR5 Comic</Title>");
|
||||
assertThat(xml).contains("<Series>RAR5 Test Series</Series>");
|
||||
assertThat(xml).contains("<Writer>Test Author</Writer>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractEntry_streamsImageToOutputStream() throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
UnrarHelper.extractEntry(RAR5_CBR, "page_001.jpg", out);
|
||||
|
||||
byte[] imageBytes = out.toByteArray();
|
||||
assertThat(imageBytes).hasSizeGreaterThan(0);
|
||||
assertThat(imageBytes[0]).isEqualTo((byte) 0xFF);
|
||||
assertThat(imageBytes[1]).isEqualTo((byte) 0xD8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractAll_extractsAllFilesToDirectory(@TempDir Path tempDir) throws IOException {
|
||||
UnrarHelper.extractAll(RAR5_CBR, tempDir);
|
||||
|
||||
assertThat(tempDir.resolve("ComicInfo.xml")).exists();
|
||||
assertThat(tempDir.resolve("page_001.jpg")).exists();
|
||||
assertThat(tempDir.resolve("page_002.jpg")).exists();
|
||||
assertThat(tempDir.resolve("page_003.jpg")).exists();
|
||||
|
||||
String xml = Files.readString(tempDir.resolve("ComicInfo.xml"));
|
||||
assertThat(xml).contains("<Title>Test RAR5 Comic</Title>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void listEntries_throwsForNonExistentFile() {
|
||||
Path bogus = Path.of("/tmp/does-not-exist.cbr");
|
||||
|
||||
assertThatThrownBy(() -> UnrarHelper.listEntries(bogus))
|
||||
.isInstanceOf(IOException.class)
|
||||
.hasMessageContaining("unrar list failed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractEntryBytes_throwsForNonExistentEntry() {
|
||||
assertThatThrownBy(() -> UnrarHelper.extractEntryBytes(RAR5_CBR, "no-such-file.jpg"))
|
||||
.isInstanceOf(IOException.class)
|
||||
.hasMessageContaining("unrar extract failed");
|
||||
}
|
||||
}
|
||||
@@ -119,6 +119,127 @@ class KoboUrlBuilderTest {
|
||||
String result = koboUrlBuilder.downloadUrl(token, bookId);
|
||||
|
||||
assertTrue(result.startsWith("https://books.example.com"));
|
||||
assertFalse(result.contains(":443"));
|
||||
assertTrue(result.contains("/api/kobo/" + token + "/v1/books/" + bookId + "/download"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHostHeaderWithoutPort_restoresLocalPort() {
|
||||
// Kobo devices send "Host: 192.168.1.100" without port.
|
||||
// Tomcat resolves missing port to 80 (HTTP default), which Spring strips.
|
||||
// The fix should restore the actual listening port from request.getLocalPort().
|
||||
mockRequest.setServerName("192.168.1.100");
|
||||
mockRequest.setServerPort(80);
|
||||
mockRequest.setLocalPort(6060);
|
||||
|
||||
String result = koboUrlBuilder.downloadUrl("testToken", 123L);
|
||||
|
||||
assertTrue(result.startsWith("http://192.168.1.100:6060/"));
|
||||
assertTrue(result.contains("/api/kobo/testToken/v1/books/123/download"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHostHeaderWithoutPort_imageUrls() {
|
||||
mockRequest.setServerName("192.168.1.100");
|
||||
mockRequest.setServerPort(80);
|
||||
mockRequest.setLocalPort(6060);
|
||||
|
||||
assertTrue(koboUrlBuilder.imageUrlTemplate("t").startsWith("http://192.168.1.100:6060/"));
|
||||
assertTrue(koboUrlBuilder.imageUrlQualityTemplate("t").startsWith("http://192.168.1.100:6060/"));
|
||||
assertTrue(koboUrlBuilder.librarySyncUrl("t").startsWith("http://192.168.1.100:6060/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReverseProxy_xForwardedProto_doesNotOverridePort() {
|
||||
mockRequest.setScheme("https");
|
||||
mockRequest.setServerName("books.example.com");
|
||||
mockRequest.setServerPort(443);
|
||||
mockRequest.setLocalPort(6060);
|
||||
mockRequest.addHeader("X-Forwarded-Proto", "https");
|
||||
|
||||
String result = koboUrlBuilder.downloadUrl("testToken", 123L);
|
||||
|
||||
assertTrue(result.startsWith("https://books.example.com/"));
|
||||
assertFalse(result.contains(":6060"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReverseProxy_xForwardedHost_doesNotOverridePort() {
|
||||
mockRequest.setScheme("https");
|
||||
mockRequest.setServerName("books.example.com");
|
||||
mockRequest.setServerPort(443);
|
||||
mockRequest.setLocalPort(6060);
|
||||
mockRequest.addHeader("X-Forwarded-Host", "books.example.com");
|
||||
|
||||
String result = koboUrlBuilder.downloadUrl("testToken", 123L);
|
||||
|
||||
assertTrue(result.startsWith("https://books.example.com/"));
|
||||
assertFalse(result.contains(":6060"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReverseProxy_xForwardedPort_doesNotOverridePort() {
|
||||
mockRequest.setScheme("https");
|
||||
mockRequest.setServerName("books.example.com");
|
||||
mockRequest.setServerPort(443);
|
||||
mockRequest.setLocalPort(6060);
|
||||
mockRequest.addHeader("X-Forwarded-Port", "443");
|
||||
|
||||
String result = koboUrlBuilder.downloadUrl("testToken", 123L);
|
||||
|
||||
assertTrue(result.startsWith("https://books.example.com/"));
|
||||
assertFalse(result.contains(":6060"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReverseProxy_forwardedHeader_doesNotOverridePort() {
|
||||
mockRequest.setScheme("https");
|
||||
mockRequest.setServerName("books.example.com");
|
||||
mockRequest.setServerPort(443);
|
||||
mockRequest.setLocalPort(6060);
|
||||
mockRequest.addHeader("Forwarded", "proto=https;host=books.example.com");
|
||||
|
||||
String result = koboUrlBuilder.downloadUrl("testToken", 123L);
|
||||
|
||||
assertTrue(result.startsWith("https://books.example.com/"));
|
||||
assertFalse(result.contains(":6060"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReverseProxy_nonStandardPort_preserved() {
|
||||
mockRequest.setScheme("https");
|
||||
mockRequest.setServerName("books.example.com");
|
||||
mockRequest.setServerPort(8443);
|
||||
mockRequest.setLocalPort(6060);
|
||||
mockRequest.addHeader("X-Forwarded-Port", "8443");
|
||||
|
||||
String result = koboUrlBuilder.downloadUrl("testToken", 123L);
|
||||
|
||||
assertTrue(result.startsWith("https://books.example.com:8443/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testServerOnPort80_noPortAdded() {
|
||||
mockRequest.setServerName("192.168.1.100");
|
||||
mockRequest.setServerPort(80);
|
||||
mockRequest.setLocalPort(80);
|
||||
|
||||
String result = koboUrlBuilder.downloadUrl("testToken", 123L);
|
||||
|
||||
assertTrue(result.startsWith("http://192.168.1.100/"));
|
||||
assertFalse(result.contains(":80"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testServerOnPort443_noPortAdded() {
|
||||
mockRequest.setScheme("https");
|
||||
mockRequest.setServerName("192.168.1.100");
|
||||
mockRequest.setServerPort(443);
|
||||
mockRequest.setLocalPort(443);
|
||||
|
||||
String result = koboUrlBuilder.downloadUrl("testToken", 123L);
|
||||
|
||||
assertTrue(result.startsWith("https://192.168.1.100/"));
|
||||
assertFalse(result.contains(":443"));
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Generated
+338
-418
File diff suppressed because it is too large
Load Diff
@@ -24,7 +24,7 @@
|
||||
"@angular/service-worker": "^21.1.5",
|
||||
"@iharbeck/ngx-virtual-scroller": "^20.0.0",
|
||||
"@jsverse/transloco": "^8.2.1",
|
||||
"@primeng/themes": "^21.0.3",
|
||||
"@primeuix/themes": "^2.0.3",
|
||||
"@stomp/rx-stomp": "^2.3.0",
|
||||
"@stomp/stompjs": "^7.3.0",
|
||||
"@tweenjs/tween.js": "^25.0.0",
|
||||
@@ -33,6 +33,7 @@
|
||||
"chartjs-chart-matrix": "^3.0.0",
|
||||
"chartjs-plugin-datalabels": "^2.2.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"dompurify": "^3.3.1",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"ng-lazyload-image": "^9.1.3",
|
||||
"ng2-charts": "^8.0.0",
|
||||
@@ -44,25 +45,32 @@
|
||||
"rxjs": "^7.8.2",
|
||||
"showdown": "^2.1.0",
|
||||
"tslib": "^2.8.1",
|
||||
"uuid": "^13.0.0",
|
||||
"uuid": "^11.0.0",
|
||||
"ws": "^8.19.0",
|
||||
"zone.js": "^0.16.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@analogjs/vite-plugin-angular": "^2.2.3",
|
||||
"@analogjs/vitest-angular": "^2.2.3",
|
||||
"@angular/build": "^21.1.4",
|
||||
"@angular/cli": "^21.1.4",
|
||||
"@angular/build": "^21.1.5",
|
||||
"@angular/cli": "^21.1.5",
|
||||
"@angular/compiler-cli": "^21.1.5",
|
||||
"@types/dompurify": "^3.0.5",
|
||||
"@types/node": "^25.3.0",
|
||||
"@types/showdown": "^2.0.6",
|
||||
"@types/uuid": "^11.0.0",
|
||||
"@vitest/coverage-v8": "^4.0.17",
|
||||
"angular-eslint": "^21.2.0",
|
||||
"eslint": "^10.0.0",
|
||||
"eslint": "^9.39.3",
|
||||
"jsdom": "^28.1.0",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.56.0",
|
||||
"typescript-eslint": "^8.56.1",
|
||||
"vitest": "^4.0.17"
|
||||
},
|
||||
"overrides": {
|
||||
"minimatch": "^10.2.1",
|
||||
"ajv": "^8.18.0",
|
||||
"eslint": {
|
||||
"ajv": "^6.14.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ function deepMerge(base: Record<string, any>, override: Record<string, any>): Re
|
||||
if (override[key] && typeof override[key] === 'object' && !Array.isArray(override[key])
|
||||
&& base[key] && typeof base[key] === 'object' && !Array.isArray(base[key])) {
|
||||
result[key] = deepMerge(base[key], override[key]);
|
||||
} else {
|
||||
} else if (override[key] !== '') {
|
||||
result[key] = override[key];
|
||||
}
|
||||
}
|
||||
|
||||
+9
-3
@@ -23,6 +23,7 @@
|
||||
<p-select
|
||||
[options]="fileTypeOptions"
|
||||
[(ngModel)]="fileType"
|
||||
(ngModelChange)="onFileTypeChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
[placeholder]="t('selectFileType')"
|
||||
@@ -34,7 +35,7 @@
|
||||
<p-fileupload class="file-upload" name="file"
|
||||
[customUpload]="true"
|
||||
[multiple]="false"
|
||||
accept=".pdf,.epub,.cbz,.cbr,.cb7,.fb2,.mobi,.azw,.azw3,.m4b,.m4a,.mp3"
|
||||
[accept]="acceptedFormats"
|
||||
(onSelect)="onFilesSelect($event)"
|
||||
(uploadHandler)="uploadFiles($event)"
|
||||
[disabled]="isUploading">
|
||||
@@ -123,8 +124,13 @@
|
||||
<i class="pi pi-cloud-upload empty-icon"></i>
|
||||
<p class="empty-text">{{ t('dragDropText') }}</p>
|
||||
<p class="empty-subtext">
|
||||
<span [innerHTML]="t('supportedFormats')"></span>
|
||||
<br/>
|
||||
@if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) {
|
||||
<span [innerHTML]="t('supportedFormats')"></span>
|
||||
<br/>
|
||||
} @else {
|
||||
<span>{{ t('supplementaryAllFormats') }}</span>
|
||||
<br/>
|
||||
}
|
||||
{{ t('maxFileSize', { size: maxFileSizeDisplay }) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
+17
-1
@@ -1,4 +1,4 @@
|
||||
import {ChangeDetectorRef, Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {ChangeDetectorRef, Component, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
|
||||
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
@@ -48,11 +48,14 @@ export class AdditionalFileUploaderComponent implements OnInit, OnDestroy {
|
||||
files: UploadingFile[] = [];
|
||||
fileType: AdditionalFileType = AdditionalFileType.ALTERNATIVE_FORMAT;
|
||||
isUploading = false;
|
||||
readonly AdditionalFileType = AdditionalFileType;
|
||||
private static readonly BOOK_FORMAT_ACCEPT = '.pdf,.epub,.cbz,.cbr,.cb7,.fb2,.mobi,.azw,.azw3,.m4b,.m4a,.mp3';
|
||||
maxFileSizeBytes?: number;
|
||||
maxFileSizeDisplay: string = '100 MB';
|
||||
|
||||
fileTypeOptions: FileTypeOption[] = [];
|
||||
|
||||
@ViewChild(FileUpload) private fileUpload!: FileUpload;
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
constructor(
|
||||
@@ -89,6 +92,19 @@ export class AdditionalFileUploaderComponent implements OnInit, OnDestroy {
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
onFileTypeChange(): void {
|
||||
this.files = [];
|
||||
if (this.fileUpload) {
|
||||
this.fileUpload.clear();
|
||||
}
|
||||
}
|
||||
|
||||
get acceptedFormats(): string {
|
||||
return this.fileType === AdditionalFileType.ALTERNATIVE_FORMAT
|
||||
? AdditionalFileUploaderComponent.BOOK_FORMAT_ACCEPT
|
||||
: '';
|
||||
}
|
||||
|
||||
hasPendingFiles(): boolean {
|
||||
return this.files.some(f => f.status === 'Pending');
|
||||
}
|
||||
|
||||
@@ -312,6 +312,7 @@
|
||||
[isSeriesCollapsed]="seriesCollapseFilter.isSeriesCollapsed"
|
||||
(checkboxClick)="onCheckboxClicked($event)"
|
||||
[isSelected]="selectedBooks.has(book.id)"
|
||||
[useSquareCovers]="isAudiobookOnlyLibrary"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</div>
|
||||
|
||||
+19
-5
@@ -196,7 +196,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
const totalGaps = (columns - 1) * this.MOBILE_GAP;
|
||||
const availableWidth = this.screenWidth - totalGaps - this.MOBILE_PADDING;
|
||||
const cardWidth = Math.floor(availableWidth / columns);
|
||||
const coverHeight = Math.floor(cardWidth * this.CARD_ASPECT_RATIO);
|
||||
const coverHeight = this.isAudiobookOnlyLibrary ? cardWidth : Math.floor(cardWidth * this.CARD_ASPECT_RATIO);
|
||||
const cardHeight = coverHeight + this.MOBILE_TITLE_BAR_HEIGHT;
|
||||
return {width: cardWidth, height: cardHeight};
|
||||
}
|
||||
@@ -209,23 +209,31 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
if (this.isMobile) {
|
||||
return this.mobileCardSize;
|
||||
}
|
||||
return this.coverScalePreferenceService.currentCardSize;
|
||||
const base = this.coverScalePreferenceService.currentCardSize;
|
||||
if (this.isAudiobookOnlyLibrary) {
|
||||
const squareSide = Math.round(base.width * 1.1);
|
||||
return { width: squareSide, height: squareSide + 31 };
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
get gridColumnMinWidth(): string {
|
||||
if (this.isMobile) {
|
||||
return `${this.mobileCardSize.width}px`;
|
||||
}
|
||||
if (this.isAudiobookOnlyLibrary) {
|
||||
return `${this.currentCardSize.width}px`;
|
||||
}
|
||||
return this.coverScalePreferenceService.gridColumnMinWidth;
|
||||
}
|
||||
|
||||
getCardHeight(_book: Book): number {
|
||||
// Use uniform height for all book types to ensure smooth virtual scrolling.
|
||||
// Mixed heights cause choppy/jumpy scrolling because the virtual scroller
|
||||
// cannot accurately estimate positions when item heights vary.
|
||||
if (this.isMobile) {
|
||||
return this.mobileCardSize.height;
|
||||
}
|
||||
if (this.isAudiobookOnlyLibrary) {
|
||||
return this.currentCardSize.height;
|
||||
}
|
||||
return this.coverScalePreferenceService.getCardHeight(_book);
|
||||
}
|
||||
|
||||
@@ -267,6 +275,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
: filterSummary;
|
||||
}
|
||||
|
||||
get isAudiobookOnlyLibrary(): boolean {
|
||||
if (!this.entity || this.entityType !== EntityType.LIBRARY) return false;
|
||||
const library = this.entity as Library;
|
||||
return !!library.allowedFormats && library.allowedFormats.length === 1 && library.allowedFormats[0] === 'AUDIOBOOK';
|
||||
}
|
||||
|
||||
get seriesViewEnabled(): boolean {
|
||||
return Boolean(this.userService.getCurrentUser()?.userSettings?.enableSeriesView);
|
||||
}
|
||||
|
||||
+2
-2
@@ -2,12 +2,12 @@
|
||||
[class.selected]="isSelected"
|
||||
(click)="onCardClick($event)">
|
||||
|
||||
<div class="cover-container" [ngClass]="{ 'center-info-btn': _isSeriesViewActive, 'loaded': isImageLoaded, 'audiobook-cover': _isAudiobook }">
|
||||
<div class="cover-container" [ngClass]="{ 'center-info-btn': _isSeriesViewActive || !hasDigitalFile(), 'loaded': isImageLoaded, 'audiobook-cover': _isAudiobook, 'square-library-cover': useSquareCovers }">
|
||||
<img
|
||||
[src]="coverImageUrl"
|
||||
class="book-cover"
|
||||
[class.loaded]="isImageLoaded"
|
||||
[class.square-cover]="_isAudiobook"
|
||||
[class.square-cover]="_isAudiobook || useSquareCovers"
|
||||
[alt]="('book.card.alt.cover' | transloco: { title: displayTitle })"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
|
||||
+5
@@ -56,6 +56,11 @@
|
||||
background-color: var(--surface-ground);
|
||||
}
|
||||
|
||||
.cover-container.square-library-cover {
|
||||
aspect-ratio: 1/1;
|
||||
background-color: var(--surface-ground);
|
||||
}
|
||||
|
||||
.book-cover {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
+2
-1
@@ -53,6 +53,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
@Input() isSeriesCollapsed: boolean = false;
|
||||
@Input() overlayPreferenceService?: BookCardOverlayPreferenceService;
|
||||
@Input() forceEbookMode: boolean = false;
|
||||
@Input() useSquareCovers: boolean = false;
|
||||
|
||||
@ViewChild('checkboxElem') checkboxElem!: ElementRef<HTMLInputElement>;
|
||||
|
||||
@@ -138,7 +139,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['book'] || changes['forceEbookMode']) {
|
||||
if (changes['book'] || changes['forceEbookMode'] || changes['useSquareCovers']) {
|
||||
this.computeAllMemoizedValues();
|
||||
if (changes['book'] && !changes['book'].firstChange && this.menuInitialized) {
|
||||
this.additionalFilesLoaded = false;
|
||||
|
||||
+1
@@ -426,6 +426,7 @@ export class BookdropFileReviewComponent implements OnInit {
|
||||
severity: 'success',
|
||||
outlined: true
|
||||
},
|
||||
acceptIcon: 'pi pi-check',
|
||||
accept: () => this.finalizeImport(),
|
||||
});
|
||||
}
|
||||
|
||||
+4
-4
@@ -35,6 +35,10 @@ export class MetadataProviderFieldSelectorComponent implements OnInit {
|
||||
label: 'Hardcover',
|
||||
fields: ['hardcoverId', 'hardcoverBookId', 'hardcoverRating', 'hardcoverReviewCount']
|
||||
},
|
||||
{
|
||||
label: 'Audible',
|
||||
fields: ['audibleId', 'audibleRating', 'audibleReviewCount']
|
||||
},
|
||||
{
|
||||
label: 'Comicvine',
|
||||
fields: ['comicvineId']
|
||||
@@ -46,10 +50,6 @@ export class MetadataProviderFieldSelectorComponent implements OnInit {
|
||||
{
|
||||
label: 'Ranobedb',
|
||||
fields: ['ranobedbId', 'ranobedbRating']
|
||||
},
|
||||
{
|
||||
label: 'Audible',
|
||||
fields: ['audibleId', 'audibleRating', 'audibleReviewCount']
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
+8
-2
@@ -34,19 +34,22 @@ export class MetadataMatchWeightsComponent implements OnInit {
|
||||
coverImage: 'Cover Image',
|
||||
seriesName: 'Series Name',
|
||||
seriesNumber: 'Series Number',
|
||||
seriesTotal: 'Series Total',
|
||||
language: 'Language',
|
||||
isbn13: 'ISBN-13',
|
||||
isbn10: 'ISBN-10',
|
||||
pageCount: 'Page Count',
|
||||
amazonRating: 'Amazon Rating',
|
||||
amazonReviewCount: 'Amazon Rating # ',
|
||||
amazonReviewCount: 'Amazon Rating #',
|
||||
goodreadsRating: 'Goodreads Rating',
|
||||
goodreadsReviewCount: 'Goodreads Rating #',
|
||||
hardcoverRating: 'Hardcover Rating',
|
||||
hardcoverReviewCount: 'Hardcover Rating #',
|
||||
ranobedbRating: 'Ranobedb Rating',
|
||||
audibleRating: 'Audible Rating',
|
||||
audibleReviewCount: 'Audible Rating #',
|
||||
doubanRating: 'Douban Rating',
|
||||
doubanReviewCount: 'Douban Rating #',
|
||||
ranobedbRating: 'Ranobedb Rating',
|
||||
};
|
||||
|
||||
form!: FormGroup;
|
||||
@@ -72,6 +75,7 @@ export class MetadataMatchWeightsComponent implements OnInit {
|
||||
categories: [0, [Validators.required, Validators.min(0)]],
|
||||
seriesName: [0, [Validators.required, Validators.min(0)]],
|
||||
seriesNumber: [0, [Validators.required, Validators.min(0)]],
|
||||
seriesTotal: [0, [Validators.required, Validators.min(0)]],
|
||||
isbn13: [0, [Validators.required, Validators.min(0)]],
|
||||
isbn10: [0, [Validators.required, Validators.min(0)]],
|
||||
pageCount: [0, [Validators.required, Validators.min(0)]],
|
||||
@@ -82,6 +86,8 @@ export class MetadataMatchWeightsComponent implements OnInit {
|
||||
goodreadsReviewCount: [0, [Validators.required, Validators.min(0)]],
|
||||
hardcoverRating: [0, [Validators.required, Validators.min(0)]],
|
||||
hardcoverReviewCount: [0, [Validators.required, Validators.min(0)]],
|
||||
doubanRating: [0, [Validators.required, Validators.min(0)]],
|
||||
doubanReviewCount: [0, [Validators.required, Validators.min(0)]],
|
||||
ranobedbRating: [0, [Validators.required, Validators.min(0)]],
|
||||
audibleRating: [0, [Validators.required, Validators.min(0)]],
|
||||
audibleReviewCount: [0, [Validators.required, Validators.min(0)]],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import Aura from '@primeng/themes/aura';
|
||||
import Aura from '@primeuix/themes/aura';
|
||||
|
||||
type ColorPalette = Record<string, string>;
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ export interface MetadataMatchWeights {
|
||||
doubanReviewCount: number;
|
||||
lubimyczytacRating: number;
|
||||
ranobedbRating: number;
|
||||
audibleRating: number;
|
||||
audibleReviewCount: number;
|
||||
coverImage: number;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {DOCUMENT, isPlatformBrowser} from '@angular/common';
|
||||
import {effect, inject, Injectable, PLATFORM_ID, signal} from '@angular/core';
|
||||
import {$t, updatePreset, updateSurfacePalette} from '@primeng/themes';
|
||||
import Aura from '@primeng/themes/aura';
|
||||
import {AppState} from '../model/app-state.model';
|
||||
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
|
||||
import { effect, inject, Injectable, PLATFORM_ID, signal } from '@angular/core';
|
||||
import { $t, updatePreset, updateSurfacePalette } from '@primeuix/themes';
|
||||
import Aura from '@primeuix/themes/aura';
|
||||
import { AppState } from '../model/app-state.model';
|
||||
|
||||
type ColorPalette = Record<string, string>;
|
||||
|
||||
@@ -332,7 +332,7 @@ export class AppConfigService {
|
||||
|
||||
constructor() {
|
||||
const initialState = this.loadAppState();
|
||||
this.appState.set({...initialState});
|
||||
this.appState.set({ ...initialState });
|
||||
this.document.documentElement.classList.add('p-dark');
|
||||
|
||||
if (isPlatformBrowser(this.platformId)) {
|
||||
@@ -383,7 +383,7 @@ export class AppConfigService {
|
||||
if (primaryName === 'noir') {
|
||||
return {
|
||||
semantic: {
|
||||
primary: {...surfacePalette},
|
||||
primary: { ...surfacePalette },
|
||||
colorScheme: {
|
||||
dark: {
|
||||
primary: {
|
||||
@@ -430,6 +430,6 @@ export class AppConfigService {
|
||||
onPresetChange(): void {
|
||||
const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral');
|
||||
const preset = this.getPresetExt();
|
||||
$t().preset(Aura).preset(preset).surfacePalette(surfacePalette).use({useDefaultOptions: true});
|
||||
$t().preset(Aura).preset(preset).surfacePalette(surfacePalette).use({ useDefaultOptions: true });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable, of} from 'rxjs';
|
||||
import {finalize, map, shareReplay, tap} from 'rxjs/operators';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {IconCacheService} from './icon-cache.service';
|
||||
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { finalize, map, shareReplay, tap } from 'rxjs/operators';
|
||||
import { API_CONFIG } from '../../core/config/api-config';
|
||||
import { IconCacheService } from './icon-cache.service';
|
||||
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
interface SvgIconData {
|
||||
svgName: string;
|
||||
@@ -25,7 +26,6 @@ interface SvgIconBatchResponse {
|
||||
}
|
||||
|
||||
type IconContentMap = Record<string, string>;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
@@ -39,6 +39,16 @@ export class IconService {
|
||||
private iconCache = inject(IconCacheService);
|
||||
private sanitizer = inject(DomSanitizer);
|
||||
|
||||
/**
|
||||
* Sanitizes SVG content using DOMPurify.
|
||||
*/
|
||||
private sanitizeSvgContent(content: string): string {
|
||||
return DOMPurify.sanitize(content, {
|
||||
USE_PROFILES: { svg: true },
|
||||
FORBID_TAGS: ['script', 'style', 'foreignObject']
|
||||
});
|
||||
}
|
||||
|
||||
preloadAllIcons(): Observable<void> {
|
||||
if (this.preloadCache$) {
|
||||
return this.preloadCache$;
|
||||
@@ -47,12 +57,12 @@ export class IconService {
|
||||
this.preloadCache$ = this.http.get<IconContentMap>(`${this.baseUrl}/all/content`).pipe(
|
||||
tap((iconsMap) => {
|
||||
Object.entries(iconsMap).forEach(([iconName, content]) => {
|
||||
const sanitized = this.sanitizer.bypassSecurityTrustHtml(content);
|
||||
const sanitized = this.sanitizer.bypassSecurityTrustHtml(this.sanitizeSvgContent(content));
|
||||
this.iconCache.cacheIcon(iconName, content, sanitized);
|
||||
});
|
||||
}),
|
||||
map(() => void 0),
|
||||
shareReplay({bufferSize: 1, refCount: false}),
|
||||
shareReplay({ bufferSize: 1, refCount: false }),
|
||||
finalize(() => this.preloadCache$ = null)
|
||||
);
|
||||
|
||||
@@ -70,10 +80,10 @@ export class IconService {
|
||||
responseType: 'text'
|
||||
}).pipe(
|
||||
tap(content => {
|
||||
const sanitized = this.sanitizer.bypassSecurityTrustHtml(content);
|
||||
const sanitized = this.sanitizer.bypassSecurityTrustHtml(this.sanitizeSvgContent(content));
|
||||
this.iconCache.cacheIcon(iconName, content, sanitized);
|
||||
}),
|
||||
shareReplay({bufferSize: 1, refCount: true}),
|
||||
shareReplay({ bufferSize: 1, refCount: true }),
|
||||
finalize(() => this.requestCache.delete(iconName))
|
||||
);
|
||||
|
||||
@@ -113,13 +123,13 @@ export class IconService {
|
||||
}
|
||||
|
||||
saveBatchSvgIcons(icons: SvgIconData[]): Observable<SvgIconBatchResponse> {
|
||||
return this.http.post<SvgIconBatchResponse>(`${this.baseUrl}/batch`, {icons}).pipe(
|
||||
return this.http.post<SvgIconBatchResponse>(`${this.baseUrl}/batch`, { icons }).pipe(
|
||||
tap((response) => {
|
||||
response.results.forEach(result => {
|
||||
if (result.success) {
|
||||
const iconData = icons.find(icon => icon.svgName === result.iconName);
|
||||
if (iconData) {
|
||||
const sanitized = this.sanitizer.bypassSecurityTrustHtml(iconData.svgData);
|
||||
const sanitized = this.sanitizer.bypassSecurityTrustHtml(this.sanitizeSvgContent(iconData.svgData));
|
||||
this.iconCache.cacheIcon(iconData.svgName, iconData.svgData, sanitized);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -445,6 +445,7 @@
|
||||
"statusFailed": "Failed",
|
||||
"dragDropText": "Drag and drop a file here to upload.",
|
||||
"supportedFormats": "Supported formats: <strong>.pdf</strong>, <strong>.epub</strong>, <strong>.cbz</strong>, <strong>.cbr</strong>, <strong>.cb7</strong>, <strong>.fb2</strong>, <strong>.mobi</strong>, <strong>.azw3</strong>, <strong>.m4b</strong>, <strong>.mp3</strong>",
|
||||
"supplementaryAllFormats": "All file formats are supported for supplementary files.",
|
||||
"maxFileSize": "Maximum file size: {{ size }} per file",
|
||||
"uploadForBook": "Upload an additional file for <strong>{{ title }}</strong>.",
|
||||
"thisBook": "this book",
|
||||
|
||||
@@ -445,6 +445,7 @@
|
||||
"statusFailed": "Fallido",
|
||||
"dragDropText": "Arrastre y suelte un archivo aquí para subir.",
|
||||
"supportedFormats": "Formatos compatibles: <strong>.pdf</strong>, <strong>.epub</strong>, <strong>.cbz</strong>, <strong>.cbr</strong>, <strong>.cb7</strong>, <strong>.fb2</strong>, <strong>.mobi</strong>, <strong>.azw3</strong>, <strong>.m4b</strong>, <strong>.mp3</strong>",
|
||||
"supplementaryAllFormats": "Todos los formatos de archivo son compatibles con archivos complementarios.",
|
||||
"maxFileSize": "Tamaño máximo de archivo: {{ size }} por archivo",
|
||||
"uploadForBook": "Subir un archivo adicional para <strong>{{ title }}</strong>.",
|
||||
"thisBook": "este libro",
|
||||
|
||||
+24
-24
@@ -1,28 +1,28 @@
|
||||
import {provideHttpClient, withInterceptors} from '@angular/common/http';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {RxStompService} from './app/shared/websocket/rx-stomp.service';
|
||||
import {rxStompServiceFactory} from './app/shared/websocket/rx-stomp-service-factory';
|
||||
import {provideRouter, RouteReuseStrategy} from '@angular/router';
|
||||
import {CustomReuseStrategy} from './app/core/custom-reuse-strategy';
|
||||
import {provideAnimationsAsync} from '@angular/platform-browser/animations/async';
|
||||
import {providePrimeNG} from 'primeng/config';
|
||||
import {bootstrapApplication} from '@angular/platform-browser';
|
||||
import {AppComponent} from './app/app.component';
|
||||
import Aura from '@primeng/themes/aura';
|
||||
import {routes} from './app/app.routes';
|
||||
import {AuthInterceptorService} from './app/core/security/auth-interceptor.service';
|
||||
import {AuthService, websocketInitializer} from './app/shared/service/auth.service';
|
||||
import {OAuthStorage, provideOAuthClient} from 'angular-oauth2-oidc';
|
||||
import {inject, isDevMode, provideAppInitializer, provideZoneChangeDetection} from '@angular/core';
|
||||
import {initializeAuthFactory} from './app/core/security/auth-initializer';
|
||||
import {StartupService} from './app/shared/service/startup.service';
|
||||
import {provideCharts, withDefaultRegisterables} from 'ng2-charts';
|
||||
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
||||
import { DialogService } from 'primeng/dynamicdialog';
|
||||
import { ConfirmationService, MessageService } from 'primeng/api';
|
||||
import { RxStompService } from './app/shared/websocket/rx-stomp.service';
|
||||
import { rxStompServiceFactory } from './app/shared/websocket/rx-stomp-service-factory';
|
||||
import { provideRouter, RouteReuseStrategy } from '@angular/router';
|
||||
import { CustomReuseStrategy } from './app/core/custom-reuse-strategy';
|
||||
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
|
||||
import { providePrimeNG } from 'primeng/config';
|
||||
import { bootstrapApplication } from '@angular/platform-browser';
|
||||
import { AppComponent } from './app/app.component';
|
||||
import Aura from '@primeuix/themes/aura';
|
||||
import { routes } from './app/app.routes';
|
||||
import { AuthInterceptorService } from './app/core/security/auth-interceptor.service';
|
||||
import { AuthService, websocketInitializer } from './app/shared/service/auth.service';
|
||||
import { OAuthStorage, provideOAuthClient } from 'angular-oauth2-oidc';
|
||||
import { inject, isDevMode, provideAppInitializer, provideZoneChangeDetection } from '@angular/core';
|
||||
import { initializeAuthFactory } from './app/core/security/auth-initializer';
|
||||
import { StartupService } from './app/shared/service/startup.service';
|
||||
import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
|
||||
import ChartDataLabels from 'chartjs-plugin-datalabels';
|
||||
import {provideServiceWorker} from '@angular/service-worker';
|
||||
import {provideTransloco} from '@jsverse/transloco';
|
||||
import {AVAILABLE_LANGS, TranslocoInlineLoader} from './app/core/config/transloco-loader';
|
||||
import {initializeLanguage} from './app/core/config/language-initializer';
|
||||
import { provideServiceWorker } from '@angular/service-worker';
|
||||
import { provideTransloco } from '@jsverse/transloco';
|
||||
import { AVAILABLE_LANGS, TranslocoInlineLoader } from './app/core/config/transloco-loader';
|
||||
import { initializeLanguage } from './app/core/config/language-initializer';
|
||||
|
||||
export function storageFactory(): OAuthStorage {
|
||||
return localStorage;
|
||||
|
||||
@@ -4,12 +4,13 @@ services:
|
||||
command: sh -c "cd /booklore-api && ./gradlew bootRun"
|
||||
ports:
|
||||
- "${BACKEND_PORT:-6060}:6060"
|
||||
- "${REMOTE_DEBUG_PORT:-5005}:5005"
|
||||
- "127.0.0.1:${REMOTE_DEBUG_PORT:-5005}:5005"
|
||||
environment:
|
||||
- DATABASE_URL=jdbc:mariadb://backend_db:3306/booklore
|
||||
- DATABASE_USERNAME=booklore
|
||||
- DATABASE_PASSWORD=booklore
|
||||
- REMOTE_DEBUG_ENABLED=true
|
||||
- ALLOWED_ORIGINS=http://localhost:4200
|
||||
stdin_open: true
|
||||
tty: true
|
||||
restart: unless-stopped
|
||||
|
||||
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
@@ -14,6 +14,7 @@ services:
|
||||
- DATABASE_PASSWORD=your_secure_password # Use a strong password; must match MYSQL_PASSWORD defined in the mariadb container
|
||||
- SWAGGER_ENABLED=false # Enable or disable Swagger UI (API docs). Set to 'true' to allow access; 'false' to block access (recommended for production).
|
||||
- FORCE_DISABLE_OIDC=false # Set to 'true' to force-disable OIDC and allow internal login, regardless of UI config
|
||||
# ALLOWED_ORIGINS= # Comma-separated list of allowed cross-origin URLs for CORS (e.g. https://app.example.com). Defaults to '*' (allow all) if unset. Leave empty to restrict to same-origin.
|
||||
depends_on:
|
||||
mariadb:
|
||||
condition: service_healthy
|
||||
|
||||
Reference in New Issue
Block a user