chore: rename springboot app folder to backend (#752)
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
/gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
@@ -0,0 +1,40 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Local scripts ###
|
||||
local/
|
||||
@@ -0,0 +1 @@
|
||||
java=25.0.2-tem
|
||||
@@ -0,0 +1,134 @@
|
||||
# Grimmory API Development
|
||||
|
||||
This document is the canonical development guide for the Grimmory `backend`. It covers the local command
|
||||
surface, setup expectations, build and test workflows, and backend-specific conventions.
|
||||
|
||||
For repository-wide contribution policy, branch strategy, PR requirements, and release semantics, start
|
||||
with [../CONTRIBUTING.md](../CONTRIBUTING.md). For repo-level environment setup and Docker workflows,
|
||||
see [../DEVELOPMENT.md](../DEVELOPMENT.md).
|
||||
|
||||
## Project Scope
|
||||
|
||||
The `backend` project is the Spring Boot backend for Grimmory. It owns the HTTP API, database
|
||||
migrations, background processing, authentication, and the packaged runtime jar used by the production
|
||||
container.
|
||||
|
||||
## Stack
|
||||
|
||||
- Java 25
|
||||
- Spring Boot 4
|
||||
- Gradle Wrapper
|
||||
- Spring Data JPA + Flyway
|
||||
- MariaDB in production, H2 for selected tests
|
||||
- JUnit 5, Mockito, AssertJ, JaCoCo
|
||||
|
||||
## Preferred Command Surface
|
||||
|
||||
Use [`Justfile`](Justfile) when possible:
|
||||
|
||||
```bash
|
||||
just # List backend recipes
|
||||
just run # Start the backend with the dev profile
|
||||
just test # Run backend tests
|
||||
just coverage # Generate JaCoCo coverage output
|
||||
just check # Run the Gradle check lifecycle
|
||||
just build # Build the backend jar
|
||||
just tasks # Show available Gradle tasks
|
||||
```
|
||||
|
||||
From the repository root, the same recipes are available through the `api` namespace:
|
||||
|
||||
```bash
|
||||
just api run
|
||||
just api test
|
||||
just api coverage
|
||||
just api check
|
||||
```
|
||||
|
||||
## Running Locally
|
||||
|
||||
The backend expects a MariaDB instance and a local `application-dev.yml` with your database and
|
||||
storage paths. The common backend loop is:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
just run
|
||||
```
|
||||
|
||||
If you need a different Spring profile:
|
||||
|
||||
```bash
|
||||
just run profile=local
|
||||
```
|
||||
|
||||
Use the repo-level guide in [../DEVELOPMENT.md](../DEVELOPMENT.md) for the full Docker stack, MariaDB
|
||||
setup, and cross-project local workflows.
|
||||
|
||||
## Build and Test
|
||||
|
||||
```bash
|
||||
just build
|
||||
just test
|
||||
just coverage
|
||||
just check
|
||||
```
|
||||
|
||||
The frontend bundle is consumed during packaging when the UI build output exists. For normal
|
||||
backend-only development and test runs, frontend resources are optional.
|
||||
|
||||
## API Docs (`API_DOCS_ENABLED`)
|
||||
|
||||
- `application.yaml` binds `app.api-docs.enabled` to `API_DOCS_ENABLED` (default `false`).
|
||||
- `application.yaml` binds `springdoc.api-docs.enabled` to `app.api-docs.enabled`.
|
||||
- `application-dev.yml` enables docs for local dev profile runs by default.
|
||||
- For runtime or container profiles, set `API_DOCS_ENABLED=true` to expose:
|
||||
- `/api/openapi.json`
|
||||
- `/api/docs`
|
||||
|
||||
## Packaging Notes
|
||||
|
||||
- The production container image is built from the repository root `Dockerfile`.
|
||||
- That Docker build compiles the UI first and passes the resolved frontend dist path into the backend
|
||||
build.
|
||||
- The backend jar remains the packaged application artifact for the current all-in-one runtime model.
|
||||
|
||||
## Backend Conventions
|
||||
|
||||
- Use Spring Data JPA repository methods or JPQL. Do not introduce native queries unless a maintainer
|
||||
has explicitly approved them.
|
||||
- Prefer constructor injection via Lombok `@AllArgsConstructor`. Do not add `@Autowired`.
|
||||
- Use Lombok `@Slf4j` for logging. Do not instantiate loggers manually.
|
||||
- Throw API-facing errors via `ApiError` helpers instead of raw `RuntimeException`.
|
||||
- Entities use the `*Entity` suffix. DTOs and API models do not.
|
||||
- Use MapStruct for entity-to-DTO mapping instead of hand-written mapping code.
|
||||
- Security checks should use the existing project patterns such as
|
||||
`@PreAuthorize("@securityUtil.isAdmin()")` or `@CheckBookAccess`.
|
||||
- Use modern Java language features where they clarify the code.
|
||||
- Keep imports explicit. Do not inline fully-qualified class names.
|
||||
|
||||
## Migrations
|
||||
|
||||
- Flyway migrations live in `src/main/resources/db/migration/`.
|
||||
- Name migrations `V<number>__<Description>.sql`.
|
||||
- Never modify a released migration. Add a new migration instead.
|
||||
- Prefer idempotent guards such as `IF EXISTS` and `IF NOT EXISTS` when the SQL dialect allows them.
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests should normally use JUnit 6 + Mockito + AssertJ.
|
||||
- Use `@ExtendWith(MockitoExtension.class)` for unit tests.
|
||||
- Use `@SpringBootTest` only when you need a real Spring integration context.
|
||||
- Keep tests behavior-oriented. Avoid shallow tests that only exercise getters, setters, or mocks
|
||||
without asserting meaningful outcomes.
|
||||
|
||||
## Validation Before Opening a PR
|
||||
|
||||
Run the backend checks locally before sending a PR:
|
||||
|
||||
```bash
|
||||
just test
|
||||
just check
|
||||
```
|
||||
|
||||
If your change affects migrations, persistence, or API behavior, also run the full stack locally and
|
||||
verify the behavior manually.
|
||||
@@ -0,0 +1,43 @@
|
||||
set shell := ["bash", "-eu", "-o", "pipefail", "-c"]
|
||||
|
||||
gradle := "./gradlew"
|
||||
|
||||
# Show the backend recipes available in this directory.
|
||||
help:
|
||||
@just --list
|
||||
|
||||
# Print the backend Gradle and JVM versions.
|
||||
version:
|
||||
{{ gradle }} --version
|
||||
|
||||
# Run the backend locally with the requested Spring profile. Default: `dev`.
|
||||
run profile='dev':
|
||||
{{ gradle }} bootRun --args="--spring.profiles.active={{ profile }}"
|
||||
|
||||
# Build the backend jar and run the standard Gradle build lifecycle.
|
||||
build:
|
||||
{{ gradle }} build --no-daemon --parallel --build-cache
|
||||
|
||||
# Run the backend test suite.
|
||||
test:
|
||||
{{ gradle }} test --no-daemon --parallel --build-cache
|
||||
|
||||
# Run a single backend test class, for example `just test-class test_class=org.booklore.service.BookServiceTest`.
|
||||
test-class test_class:
|
||||
{{ gradle }} test --tests "{{ test_class }}" --no-daemon --parallel --build-cache
|
||||
|
||||
# Run tests and generate JaCoCo coverage output.
|
||||
coverage:
|
||||
{{ gradle }} test jacocoTestReport --no-daemon --parallel --build-cache
|
||||
|
||||
# Run the Gradle `check` lifecycle used for local backend verification.
|
||||
check:
|
||||
{{ gradle }} check --no-daemon --parallel --build-cache
|
||||
|
||||
# Remove backend build outputs.
|
||||
clean:
|
||||
{{ gradle }} clean --no-daemon
|
||||
|
||||
# List the available backend Gradle tasks.
|
||||
tasks:
|
||||
{{ gradle }} tasks --all --no-daemon
|
||||
@@ -0,0 +1,241 @@
|
||||
import org.gradle.api.tasks.Copy
|
||||
import org.gradle.api.tasks.testing.Test
|
||||
import org.gradle.testing.jacoco.tasks.JacocoReport
|
||||
import org.springframework.boot.gradle.tasks.bundling.BootJar
|
||||
import org.springframework.boot.gradle.tasks.run.BootRun
|
||||
|
||||
plugins {
|
||||
java
|
||||
id("org.springframework.boot") version "4.0.5"
|
||||
id("io.spring.dependency-management") version "1.1.7"
|
||||
id("org.hibernate.orm") version "7.3.0.Final"
|
||||
id("com.github.ben-manes.versions") version "0.53.0"
|
||||
jacoco
|
||||
}
|
||||
|
||||
group = "org.booklore"
|
||||
version = "0.0.1-SNAPSHOT"
|
||||
|
||||
val defaultFrontendDistDir = file("${rootDir}/../frontend/dist/grimmory/browser")
|
||||
val configuredFrontendDistDir = providers.gradleProperty("frontendDistDir")
|
||||
.map { file(it) }
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(25)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.compilerArgs.add("--enable-preview")
|
||||
}
|
||||
|
||||
val useLocalLibs = providers.gradleProperty("useLocalLibs").isPresent
|
||||
|
||||
repositories {
|
||||
if (useLocalLibs) mavenLocal()
|
||||
mavenCentral()
|
||||
maven(url = "https://jitpack.io")
|
||||
}
|
||||
|
||||
fun pdfiumNativesClassifier(): String {
|
||||
// Support cross-compilation: check for explicit target overrides first
|
||||
val targetPlatform = System.getenv("TARGETPLATFORM")
|
||||
?: project.findProperty("targetPlatform")?.toString()
|
||||
val targetArch = System.getenv("TARGETARCH")
|
||||
?: project.findProperty("targetArch")?.toString()
|
||||
|
||||
val osName: String
|
||||
val arch: String
|
||||
|
||||
if (targetPlatform != null) {
|
||||
// Docker TARGETPLATFORM format: linux/amd64, linux/arm64
|
||||
val parts = targetPlatform.split("/")
|
||||
osName = parts.getOrElse(0) { "linux" }
|
||||
arch = parts.getOrElse(1) { "amd64" }
|
||||
} else {
|
||||
osName = System.getProperty("os.name").lowercase()
|
||||
arch = targetArch ?: System.getProperty("os.arch").lowercase()
|
||||
}
|
||||
|
||||
val osKey = when {
|
||||
"win" in osName -> "windows"
|
||||
"mac" in osName || "darwin" in osName -> "darwin"
|
||||
"nux" in osName || "linux" in osName -> {
|
||||
val isMusl = try {
|
||||
val libDir = File("/lib")
|
||||
libDir.exists() && (libDir.listFiles()?.any { f -> f.name.startsWith("ld-musl-") } == true)
|
||||
} catch (_: Exception) {
|
||||
try {
|
||||
File("/proc/self/maps").readText().contains("musl")
|
||||
} catch (_: Exception) { false }
|
||||
}
|
||||
if (isMusl) "linux-musl" else "linux"
|
||||
}
|
||||
else -> error("Unsupported OS: $osName")
|
||||
}
|
||||
|
||||
val archKey = when (arch) {
|
||||
"x86_64", "amd64" -> "x64"
|
||||
"aarch64", "arm64" -> "arm64"
|
||||
else -> error("Unsupported architecture: $arch")
|
||||
}
|
||||
|
||||
return "natives-$osKey-$archKey"
|
||||
}
|
||||
|
||||
configurations {
|
||||
compileOnly {
|
||||
extendsFrom(configurations.annotationProcessor.get())
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// --- Spring Boot ---
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
implementation("org.springframework.boot:spring-boot-starter-websocket")
|
||||
implementation("org.springframework.boot:spring-boot-starter-actuator")
|
||||
implementation("org.springframework.boot:spring-boot-configuration-processor")
|
||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||
implementation("org.springframework.boot:spring-boot-starter-mail")
|
||||
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
|
||||
|
||||
// --- Reactive Streams ---
|
||||
implementation("io.projectreactor:reactor-core")
|
||||
|
||||
// --- Database & Migration ---
|
||||
implementation("org.mariadb.jdbc:mariadb-java-client:3.5.8")
|
||||
implementation("org.springframework.boot:spring-boot-starter-flyway")
|
||||
implementation("org.flywaydb:flyway-mysql:12.3.0")
|
||||
|
||||
// --- Security & Authentication ---
|
||||
implementation("io.jsonwebtoken:jjwt-api:0.13.0")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.13.0")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.13.0")
|
||||
|
||||
// --- Lombok (For Clean Code) ---
|
||||
compileOnly("org.projectlombok:lombok:1.18.44")
|
||||
annotationProcessor("org.projectlombok:lombok:1.18.44")
|
||||
|
||||
// --- Book & Image Processing ---
|
||||
val pdfium4jVersion = if (useLocalLibs) "+" else "0.14.0"
|
||||
implementation("org.grimmory:pdfium4j:$pdfium4jVersion")
|
||||
runtimeOnly("org.grimmory:pdfium4j:$pdfium4jVersion:${pdfiumNativesClassifier()}")
|
||||
|
||||
// --- TwelveMonkeys ImageIO ---
|
||||
implementation("com.twelvemonkeys.imageio:imageio-jpeg:3.13.1")
|
||||
implementation("com.twelvemonkeys.imageio:imageio-tiff:3.13.1")
|
||||
implementation("com.twelvemonkeys.imageio:imageio-webp:3.13.1")
|
||||
implementation("com.twelvemonkeys.imageio:imageio-bmp:3.13.1")
|
||||
|
||||
// epub4j-grimmory fork publishes as org.grimmory:epub4j-core
|
||||
val epub4jCoords = if (useLocalLibs) "org.grimmory:epub4j-core:+" else "org.grimmory:epub4j-core:1.1.0"
|
||||
implementation(epub4jCoords)
|
||||
|
||||
// epub4j-native for native archive parsing
|
||||
val epub4jNativeCoords = if (useLocalLibs) "org.grimmory:epub4j-native:+" else "org.grimmory:epub4j-native:1.1.0"
|
||||
implementation(epub4jNativeCoords)
|
||||
|
||||
// --- Audio Metadata (Audiobook Support) ---
|
||||
implementation("com.github.RouHim:jaudiotagger:2.0.19")
|
||||
|
||||
// --- Archive Support ---
|
||||
implementation("com.github.gotson.nightcompress:nightcompress:1.1.1")
|
||||
|
||||
// --- JSON & Web Scraping ---
|
||||
implementation("org.jsoup:jsoup:1.22.1")
|
||||
|
||||
// --- Mapping (DTOs & Entities) ---
|
||||
implementation("org.mapstruct:mapstruct:1.6.3")
|
||||
annotationProcessor("org.mapstruct:mapstruct-processor:1.6.3")
|
||||
|
||||
// --- API Documentation ---
|
||||
implementation("org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.2")
|
||||
implementation("org.apache.commons:commons-compress:1.28.0")
|
||||
implementation("org.tukaani:xz:1.12") // Required by commons-compress for 7z support
|
||||
implementation("org.apache.commons:commons-text:1.15.0")
|
||||
|
||||
// --- MIME Detection ---
|
||||
implementation("org.apache.tika:tika-core:3.3.0")
|
||||
|
||||
// --- XML Support (JAXB) ---
|
||||
implementation("jakarta.xml.bind:jakarta.xml.bind-api:4.0.5")
|
||||
runtimeOnly("org.glassfish.jaxb:jaxb-runtime:4.0.7")
|
||||
|
||||
// --- Template Engine ---
|
||||
implementation("org.freemarker:freemarker:2.3.34")
|
||||
|
||||
// --- Jackson 3 ---
|
||||
implementation(platform("tools.jackson:jackson-bom:3.1.1"))
|
||||
implementation("tools.jackson.core:jackson-core")
|
||||
implementation("tools.jackson.core:jackson-databind")
|
||||
implementation("tools.jackson.module:jackson-module-blackbird")
|
||||
|
||||
// --- Jackson 2 (Compatibility) ---
|
||||
// jackson-annotations version is managed by Jackson 3 BOM (requires 2.20+)
|
||||
implementation("com.fasterxml.jackson.core:jackson-annotations")
|
||||
|
||||
// --- Caching ---
|
||||
implementation("org.springframework.boot:spring-boot-starter-cache")
|
||||
implementation("com.github.ben-manes.caffeine:caffeine:3.2.3")
|
||||
|
||||
// --- Test Dependencies ---
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.springframework.boot:spring-boot-test-autoconfigure")
|
||||
testImplementation("org.assertj:assertj-core:3.27.7")
|
||||
testImplementation("org.mockito:mockito-inline:5.2.0")
|
||||
testRuntimeOnly("com.h2database:h2")
|
||||
|
||||
// PDFBox for test PDF creation only (production code uses PDFium4j)
|
||||
testImplementation("org.apache.pdfbox:pdfbox:3.0.7")
|
||||
}
|
||||
|
||||
hibernate {
|
||||
enhancement {
|
||||
enableAssociationManagement = false
|
||||
enableLazyInitialization = true
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
maxHeapSize = "2560m"
|
||||
jvmArgs("-XX:+EnableDynamicAgentLoading", "--enable-native-access=ALL-UNNAMED", "--enable-preview")
|
||||
finalizedBy(tasks.named("jacocoTestReport"))
|
||||
}
|
||||
|
||||
tasks.named<JacocoReport>("jacocoTestReport") {
|
||||
dependsOn(tasks.named("test"))
|
||||
reports {
|
||||
xml.required.set(true)
|
||||
html.required.set(true)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named<Copy>("processResources") {
|
||||
val frontendResourcesDir = configuredFrontendDistDir
|
||||
.orElse(providers.provider { defaultFrontendDistDir })
|
||||
.get()
|
||||
|
||||
inputs.property("frontendDistDir", frontendResourcesDir.absolutePath)
|
||||
inputs.property("hasFrontendResources", frontendResourcesDir.exists())
|
||||
|
||||
if (frontendResourcesDir.exists()) {
|
||||
from(frontendResourcesDir) {
|
||||
into("static")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named<BootRun>("bootRun") {
|
||||
jvmArgs("--enable-native-access=ALL-UNNAMED", "--enable-preview")
|
||||
if (System.getenv("REMOTE_DEBUG_ENABLED") == "true") {
|
||||
jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005")
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named<BootJar>("bootJar") {
|
||||
mainClass.set("org.booklore.BookloreApplication")
|
||||
}
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = "backend"
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.booklore;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
import org.booklore.config.AppProperties;
|
||||
import org.booklore.config.BookmarkProperties;
|
||||
|
||||
@EnableScheduling
|
||||
@EnableConfigurationProperties({AppProperties.class, BookmarkProperties.class})
|
||||
@SpringBootApplication
|
||||
public class BookloreApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(BookloreApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package org.booklore.app.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.booklore.app.dto.AppAuthorDetail;
|
||||
import org.booklore.app.dto.AppAuthorSummary;
|
||||
import org.booklore.app.dto.AppPageResponse;
|
||||
import org.booklore.app.service.AppAuthorService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/app/authors")
|
||||
@Tag(name = "App Authors", description = "Endpoints for browsing authors in the app experience")
|
||||
public class AppAuthorController {
|
||||
|
||||
private final AppAuthorService mobileAuthorService;
|
||||
|
||||
@Operation(
|
||||
summary = "List app authors",
|
||||
description = "Retrieve paginated authors for the app with optional filtering and sorting.",
|
||||
operationId = "appGetAuthors"
|
||||
)
|
||||
@GetMapping
|
||||
public ResponseEntity<AppPageResponse<AppAuthorSummary>> getAuthors(
|
||||
@RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@RequestParam(required = false, defaultValue = "30") Integer size,
|
||||
@RequestParam(required = false, defaultValue = "name") String sort,
|
||||
@RequestParam(required = false, defaultValue = "asc") String dir,
|
||||
@RequestParam(required = false) Long libraryId,
|
||||
@RequestParam(required = false) String search,
|
||||
@RequestParam(required = false) Boolean hasPhoto) {
|
||||
|
||||
return ResponseEntity.ok(mobileAuthorService.getAuthors(page, size, sort, dir, libraryId, search, hasPhoto));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Get app author details",
|
||||
description = "Retrieve detailed app-facing information for a single author.",
|
||||
operationId = "appGetAuthorDetail"
|
||||
)
|
||||
@GetMapping("/{authorId}")
|
||||
public ResponseEntity<AppAuthorDetail> getAuthorDetail(
|
||||
@PathVariable Long authorId) {
|
||||
|
||||
return ResponseEntity.ok(mobileAuthorService.getAuthorDetail(authorId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package org.booklore.app.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.booklore.app.dto.*;
|
||||
import org.booklore.app.service.AppBookService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/app/books")
|
||||
@Tag(name = "App Books", description = "Endpoints for browsing and updating books in the app experience")
|
||||
public class AppBookController {
|
||||
|
||||
private final AppBookService mobileBookService;
|
||||
|
||||
@Operation(
|
||||
summary = "List app books",
|
||||
description = "Retrieve paginated books for the app with optional filtering and sorting.",
|
||||
operationId = "appGetBooks"
|
||||
)
|
||||
@GetMapping
|
||||
public ResponseEntity<AppPageResponse<AppBookSummary>> getBooks(
|
||||
@ModelAttribute BookListRequest request) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.getBooks(request));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Get all book IDs matching filters",
|
||||
description = "Return all book IDs that match the given filters without pagination. Useful for bulk selection.",
|
||||
operationId = "appGetAllBookIds"
|
||||
)
|
||||
@GetMapping("/ids")
|
||||
public ResponseEntity<List<Long>> getAllBookIds(
|
||||
@ModelAttribute BookListRequest request) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.getAllBookIds(request));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Get app book details",
|
||||
description = "Retrieve detailed app-facing information for a single book.",
|
||||
operationId = "appGetBookDetail"
|
||||
)
|
||||
@GetMapping("/{bookId}")
|
||||
public ResponseEntity<AppBookDetail> getBookDetail(
|
||||
@PathVariable Long bookId) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.getBookDetail(bookId));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/progress")
|
||||
public ResponseEntity<AppBookProgressResponse> getBookProgress(
|
||||
@PathVariable Long bookId) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.getBookProgress(bookId));
|
||||
}
|
||||
|
||||
@PutMapping("/{bookId}/progress")
|
||||
public ResponseEntity<Void> updateBookProgress(
|
||||
@PathVariable Long bookId,
|
||||
@Valid @RequestBody UpdateProgressRequest request) {
|
||||
|
||||
mobileBookService.updateBookProgress(bookId, request);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Search app books",
|
||||
description = "Search books in the app catalog using a free-text query.",
|
||||
operationId = "appSearchBooks"
|
||||
)
|
||||
@GetMapping("/search")
|
||||
public ResponseEntity<AppPageResponse<AppBookSummary>> searchBooks(
|
||||
@RequestParam String q,
|
||||
@RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@RequestParam(required = false, defaultValue = "20") Integer size) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.searchBooks(q, page, size));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Get continue reading books",
|
||||
description = "Retrieve books currently in progress for reading in the app.",
|
||||
operationId = "appGetContinueReading"
|
||||
)
|
||||
@GetMapping("/continue-reading")
|
||||
public ResponseEntity<List<AppBookSummary>> getContinueReading(
|
||||
@RequestParam(required = false, defaultValue = "10") Integer limit) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.getContinueReading(limit));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Get continue listening books",
|
||||
description = "Retrieve audiobooks currently in progress for listening in the app.",
|
||||
operationId = "appGetContinueListening"
|
||||
)
|
||||
@GetMapping("/continue-listening")
|
||||
public ResponseEntity<List<AppBookSummary>> getContinueListening(
|
||||
@RequestParam(required = false, defaultValue = "10") Integer limit) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.getContinueListening(limit));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Get recently added books",
|
||||
description = "Retrieve recently added books for the app home experience.",
|
||||
operationId = "appGetRecentlyAdded"
|
||||
)
|
||||
@GetMapping("/recently-added")
|
||||
public ResponseEntity<List<AppBookSummary>> getRecentlyAdded(
|
||||
@RequestParam(required = false, defaultValue = "10") Integer limit) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.getRecentlyAdded(limit));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Get recently scanned books",
|
||||
description = "Retrieve recently scanned books for the app home experience.",
|
||||
operationId = "appGetRecentlyScanned"
|
||||
)
|
||||
@GetMapping("/recently-scanned")
|
||||
public ResponseEntity<List<AppBookSummary>> getRecentlyScanned(
|
||||
@RequestParam(required = false, defaultValue = "10") Integer limit) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.getRecentlyScanned(limit));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Update app book read status",
|
||||
description = "Update the read status of a book from the app interface.",
|
||||
operationId = "appUpdateStatus"
|
||||
)
|
||||
@PutMapping("/{bookId}/status")
|
||||
public ResponseEntity<Void> updateStatus(
|
||||
@PathVariable Long bookId,
|
||||
@Valid @RequestBody UpdateStatusRequest request) {
|
||||
|
||||
mobileBookService.updateReadStatus(bookId, request.getStatus());
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Update app book rating",
|
||||
description = "Update the personal rating of a book from the app interface.",
|
||||
operationId = "appUpdateRating"
|
||||
)
|
||||
@PutMapping("/{bookId}/rating")
|
||||
public ResponseEntity<Void> updateRating(
|
||||
@PathVariable Long bookId,
|
||||
@Valid @RequestBody UpdateRatingRequest request) {
|
||||
|
||||
mobileBookService.updatePersonalRating(bookId, request.getRating());
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Get random app books",
|
||||
description = "Retrieve a paginated random selection of books for discovery in the app.",
|
||||
operationId = "appGetRandomBooks"
|
||||
)
|
||||
@GetMapping("/random")
|
||||
public ResponseEntity<AppPageResponse<AppBookSummary>> getRandomBooks(
|
||||
@RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@RequestParam(required = false, defaultValue = "20") Integer size,
|
||||
@RequestParam(required = false) Long libraryId) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.getRandomBooks(page, size, libraryId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.booklore.app.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.booklore.app.dto.AppFilterOptions;
|
||||
import org.booklore.app.service.AppBookService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/app")
|
||||
@Tag(name = "App Filters", description = "Endpoints for retrieving app filter options")
|
||||
public class AppFilterController {
|
||||
|
||||
private final AppBookService mobileBookService;
|
||||
|
||||
@Operation(
|
||||
summary = "Get app filter options",
|
||||
description = "Retrieve available filter values for app book browsing.",
|
||||
operationId = "appGetFilterOptions"
|
||||
)
|
||||
@GetMapping("/filter-options")
|
||||
public ResponseEntity<AppFilterOptions> getFilterOptions(
|
||||
@RequestParam(required = false) Long libraryId,
|
||||
@RequestParam(required = false) Long shelfId,
|
||||
@RequestParam(required = false) Long magicShelfId) {
|
||||
return ResponseEntity.ok(mobileBookService.getFilterOptions(libraryId, shelfId, magicShelfId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package org.booklore.app.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.app.dto.AppLibrarySummary;
|
||||
import org.booklore.app.mapper.AppBookMapper;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.LibraryRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/app/libraries")
|
||||
@Tag(name = "App Libraries", description = "Endpoints for retrieving libraries in the app experience")
|
||||
public class AppLibraryController {
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final AppBookMapper mobileBookMapper;
|
||||
|
||||
@Operation(
|
||||
summary = "List app libraries",
|
||||
description = "Retrieve libraries visible to the current app user, including per-library book counts.",
|
||||
operationId = "appGetLibraries"
|
||||
)
|
||||
@GetMapping
|
||||
public ResponseEntity<List<AppLibrarySummary>> getLibraries() {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
List<LibraryEntity> libraries;
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
libraries = libraryRepository.findAll();
|
||||
} else {
|
||||
List<Long> libraryIds = user.getAssignedLibraries() != null
|
||||
? user.getAssignedLibraries().stream().map(Library::getId).collect(Collectors.toList())
|
||||
: List.of();
|
||||
libraries = libraryRepository.findByIdIn(libraryIds);
|
||||
}
|
||||
|
||||
List<AppLibrarySummary> summaries = libraries.stream()
|
||||
.map(library -> {
|
||||
long bookCount = bookRepository.countByLibraryId(library.getId());
|
||||
return mobileBookMapper.toLibrarySummary(library, bookCount);
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return ResponseEntity.ok(summaries);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package org.booklore.app.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.booklore.app.dto.AppNotebookBookSummary;
|
||||
import org.booklore.app.dto.AppNotebookEntry;
|
||||
import org.booklore.app.dto.AppNotebookUpdateRequest;
|
||||
import org.booklore.app.dto.AppPageResponse;
|
||||
import org.booklore.app.service.AppNotebookService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/app/notebook")
|
||||
@Tag(name = "App Notebook", description = "Endpoints for notebook browsing and editing in the app experience")
|
||||
public class AppNotebookController {
|
||||
|
||||
private final AppNotebookService mobileNotebookService;
|
||||
|
||||
@Operation(
|
||||
summary = "List notebook books",
|
||||
description = "Retrieve paginated books that contain notebook entries in the app.",
|
||||
operationId = "appGetBooksWithAnnotations"
|
||||
)
|
||||
@GetMapping("/books")
|
||||
public ResponseEntity<AppPageResponse<AppNotebookBookSummary>> getBooksWithAnnotations(
|
||||
@RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@RequestParam(required = false, defaultValue = "20") Integer size,
|
||||
@RequestParam(required = false) String search) {
|
||||
|
||||
return ResponseEntity.ok(mobileNotebookService.getBooksWithAnnotations(page, size, search));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "List notebook entries for book",
|
||||
description = "Retrieve paginated notebook entries for a specific book in the app.",
|
||||
operationId = "appGetEntriesForBook"
|
||||
)
|
||||
@GetMapping("/books/{bookId}/entries")
|
||||
public ResponseEntity<AppPageResponse<AppNotebookEntry>> getEntriesForBook(
|
||||
@PathVariable Long bookId,
|
||||
@RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@RequestParam(required = false, defaultValue = "20") Integer size,
|
||||
@RequestParam(required = false) Set<String> types,
|
||||
@RequestParam(required = false) String search,
|
||||
@RequestParam(required = false, defaultValue = "date_desc") String sort) {
|
||||
|
||||
return ResponseEntity.ok(mobileNotebookService.getEntriesForBook(bookId, page, size, types, search, sort));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Update notebook entry",
|
||||
description = "Update an existing notebook entry in the app.",
|
||||
operationId = "appUpdateEntry"
|
||||
)
|
||||
@PutMapping("/entries/{entryId}")
|
||||
public ResponseEntity<AppNotebookEntry> updateEntry(
|
||||
@PathVariable Long entryId,
|
||||
@RequestParam String type,
|
||||
@Valid @RequestBody AppNotebookUpdateRequest request) {
|
||||
|
||||
return ResponseEntity.ok(mobileNotebookService.updateEntry(entryId, type, request));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Delete notebook entry",
|
||||
description = "Delete an existing notebook entry in the app.",
|
||||
operationId = "appDeleteEntry"
|
||||
)
|
||||
@DeleteMapping("/entries/{entryId}")
|
||||
public ResponseEntity<Void> deleteEntry(
|
||||
@PathVariable Long entryId,
|
||||
@RequestParam String type) {
|
||||
|
||||
mobileNotebookService.deleteEntry(entryId, type);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package org.booklore.app.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.app.dto.AppBookSummary;
|
||||
import org.booklore.app.dto.AppPageResponse;
|
||||
import org.booklore.app.dto.AppSeriesSummary;
|
||||
import org.booklore.app.service.AppSeriesService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/app/series")
|
||||
@Tag(name = "App Series", description = "Endpoints for browsing series in the app experience")
|
||||
public class AppSeriesController {
|
||||
|
||||
private final AppSeriesService mobileSeriesService;
|
||||
|
||||
@Operation(
|
||||
summary = "List app series",
|
||||
description = "Retrieve paginated series for the app with optional filtering and sorting.",
|
||||
operationId = "appGetSeries"
|
||||
)
|
||||
@GetMapping
|
||||
public ResponseEntity<AppPageResponse<AppSeriesSummary>> getSeries(
|
||||
@RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@RequestParam(required = false, defaultValue = "20") Integer size,
|
||||
@RequestParam(required = false, defaultValue = "recentlyAdded") String sort,
|
||||
@RequestParam(required = false, defaultValue = "desc") String dir,
|
||||
@RequestParam(required = false) Long libraryId,
|
||||
@RequestParam(required = false) String search,
|
||||
@RequestParam(required = false) String status) {
|
||||
|
||||
boolean inProgressOnly = "in-progress".equalsIgnoreCase(status);
|
||||
|
||||
AppPageResponse<AppSeriesSummary> response = mobileSeriesService.getSeries(
|
||||
page, size, sort, dir, libraryId, search, inProgressOnly);
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "List books in app series",
|
||||
description = "Retrieve paginated books belonging to a specific series for the app.",
|
||||
operationId = "appGetSeriesBooks"
|
||||
)
|
||||
@GetMapping("/{seriesName}/books")
|
||||
public ResponseEntity<AppPageResponse<AppBookSummary>> getSeriesBooks(
|
||||
@PathVariable String seriesName,
|
||||
@RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@RequestParam(required = false, defaultValue = "20") Integer size,
|
||||
@RequestParam(required = false, defaultValue = "seriesNumber") String sort,
|
||||
@RequestParam(required = false, defaultValue = "asc") String dir,
|
||||
@RequestParam(required = false) Long libraryId) {
|
||||
|
||||
AppPageResponse<AppBookSummary> response = mobileSeriesService.getSeriesBooks(
|
||||
seriesName, page, size, sort, dir, libraryId);
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package org.booklore.app.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.app.dto.AppBookSummary;
|
||||
import org.booklore.app.dto.AppMagicShelfSummary;
|
||||
import org.booklore.app.dto.AppPageResponse;
|
||||
import org.booklore.app.dto.AppShelfSummary;
|
||||
import org.booklore.app.mapper.AppBookMapper;
|
||||
import org.booklore.app.service.AppBookService;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.MagicShelfEntity;
|
||||
import org.booklore.model.entity.ShelfEntity;
|
||||
import org.booklore.repository.MagicShelfRepository;
|
||||
import org.booklore.repository.ShelfRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/app/shelves")
|
||||
@Tag(name = "App Shelves", description = "Endpoints for browsing shelves and magic shelves in the app experience")
|
||||
public class AppShelfController {
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final ShelfRepository shelfRepository;
|
||||
private final MagicShelfRepository magicShelfRepository;
|
||||
private final AppBookMapper mobileBookMapper;
|
||||
private final AppBookService mobileBookService;
|
||||
|
||||
@Operation(
|
||||
summary = "List app shelves",
|
||||
description = "Retrieve all regular shelves visible to the current app user.",
|
||||
operationId = "appGetShelves"
|
||||
)
|
||||
@GetMapping
|
||||
public ResponseEntity<List<AppShelfSummary>> getShelves() {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Long userId = user.getId();
|
||||
|
||||
List<ShelfEntity> shelves = shelfRepository.findByUserIdOrPublicShelfTrue(userId);
|
||||
|
||||
List<AppShelfSummary> summaries = shelves.stream()
|
||||
.map(mobileBookMapper::toShelfSummaryFromEntity)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return ResponseEntity.ok(summaries);
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "List app magic shelves",
|
||||
description = "Retrieve all magic shelves visible to the current app user.",
|
||||
operationId = "appGetMagicShelves"
|
||||
)
|
||||
@GetMapping("/magic")
|
||||
public ResponseEntity<List<AppMagicShelfSummary>> getMagicShelves() {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Long userId = user.getId();
|
||||
|
||||
// Get user's own magic shelves
|
||||
List<MagicShelfEntity> userShelves = magicShelfRepository.findAllByUserId(userId);
|
||||
|
||||
// Get public magic shelves
|
||||
List<MagicShelfEntity> publicShelves = magicShelfRepository.findAllByIsPublicIsTrue();
|
||||
|
||||
// Combine and deduplicate (user's shelves that are also public shouldn't appear twice)
|
||||
Set<Long> seenIds = new HashSet<>();
|
||||
List<MagicShelfEntity> allShelves = new ArrayList<>();
|
||||
|
||||
for (MagicShelfEntity shelf : userShelves) {
|
||||
if (seenIds.add(shelf.getId())) {
|
||||
allShelves.add(shelf);
|
||||
}
|
||||
}
|
||||
for (MagicShelfEntity shelf : publicShelves) {
|
||||
if (seenIds.add(shelf.getId())) {
|
||||
allShelves.add(shelf);
|
||||
}
|
||||
}
|
||||
|
||||
List<AppMagicShelfSummary> summaries = allShelves.stream()
|
||||
.map(mobileBookMapper::toMagicShelfSummary)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return ResponseEntity.ok(summaries);
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "List books in app magic shelf",
|
||||
description = "Retrieve paginated books contained in a specific magic shelf for the app.",
|
||||
operationId = "appGetBooksByMagicShelf"
|
||||
)
|
||||
@GetMapping("/magic/{magicShelfId}/books")
|
||||
public ResponseEntity<AppPageResponse<AppBookSummary>> getBooksByMagicShelf(
|
||||
@PathVariable Long magicShelfId,
|
||||
@RequestParam(required = false, defaultValue = "0") Integer page,
|
||||
@RequestParam(required = false, defaultValue = "20") Integer size) {
|
||||
|
||||
return ResponseEntity.ok(mobileBookService.getBooksByMagicShelf(magicShelfId, page, size));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package org.booklore.app.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.app.dto.AppUserInfo;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/app/users")
|
||||
@Tag(name = "App Users", description = "Endpoints for retrieving app user capabilities and profile information")
|
||||
public class AppUserController {
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
@Operation(
|
||||
summary = "Get current app user",
|
||||
description = "Retrieve current user flags and capability information used by the app experience.",
|
||||
operationId = "appGetCurrentUser"
|
||||
)
|
||||
@GetMapping("/me")
|
||||
public ResponseEntity<AppUserInfo> getCurrentUser() {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BookLoreUser.UserPermissions perms = user.getPermissions();
|
||||
|
||||
int maxUploadSizeMb = 100; // default
|
||||
try {
|
||||
Integer configured = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
|
||||
if (configured != null) {
|
||||
maxUploadSizeMb = configured;
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// fall back to default
|
||||
}
|
||||
|
||||
AppUserInfo info = AppUserInfo.builder()
|
||||
.isAdmin(perms.isAdmin())
|
||||
.canUpload(perms.isCanUpload())
|
||||
.canDownload(perms.isCanDownload())
|
||||
.canAccessBookdrop(perms.isCanAccessBookdrop())
|
||||
.maxFileUploadSizeMb(maxUploadSizeMb)
|
||||
.build();
|
||||
|
||||
return ResponseEntity.ok(info);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppAuthorDetail {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private String asin;
|
||||
private int bookCount;
|
||||
private boolean hasPhoto;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppAuthorSummary {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String asin;
|
||||
private int bookCount;
|
||||
private boolean hasPhoto;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppBookDetail {
|
||||
private Long id;
|
||||
private String title;
|
||||
private List<String> authors;
|
||||
private String thumbnailUrl;
|
||||
private String readStatus;
|
||||
private Integer personalRating;
|
||||
private String seriesName;
|
||||
private Float seriesNumber;
|
||||
private Long libraryId;
|
||||
private Instant addedOn;
|
||||
private Instant lastReadTime;
|
||||
|
||||
private String subtitle;
|
||||
private String description;
|
||||
private Set<String> categories;
|
||||
private String publisher;
|
||||
private LocalDate publishedDate;
|
||||
private Integer pageCount;
|
||||
private String isbn13;
|
||||
private String language;
|
||||
private Double goodreadsRating;
|
||||
private Integer goodreadsReviewCount;
|
||||
private String libraryName;
|
||||
private List<AppShelfSummary> shelves;
|
||||
private Float readProgress;
|
||||
private String primaryFileType;
|
||||
private List<String> fileTypes;
|
||||
private List<AppBookFile> files;
|
||||
private Instant coverUpdatedOn;
|
||||
private Instant audiobookCoverUpdatedOn;
|
||||
private Boolean isPhysical;
|
||||
|
||||
private EpubProgress epubProgress;
|
||||
private PdfProgress pdfProgress;
|
||||
private CbxProgress cbxProgress;
|
||||
private AudiobookProgress audiobookProgress;
|
||||
private KoreaderProgress koreaderProgress;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class EpubProgress {
|
||||
private String cfi;
|
||||
private String href;
|
||||
private Float percentage;
|
||||
private Instant updatedAt;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class PdfProgress {
|
||||
private Integer page;
|
||||
private Float percentage;
|
||||
private Instant updatedAt;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class CbxProgress {
|
||||
private Integer page;
|
||||
private Float percentage;
|
||||
private Instant updatedAt;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class AudiobookProgress {
|
||||
private Long positionMs;
|
||||
private Integer trackIndex;
|
||||
private Float percentage;
|
||||
private Instant updatedAt;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class KoreaderProgress {
|
||||
private Float percentage;
|
||||
private String device;
|
||||
private String deviceId;
|
||||
private Instant lastSyncTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppBookFile {
|
||||
private Long id;
|
||||
private Long bookId;
|
||||
private String fileName;
|
||||
private boolean isBook;
|
||||
private boolean folderBased;
|
||||
private String bookType;
|
||||
private String archiveType;
|
||||
private Long fileSizeKb;
|
||||
private String extension;
|
||||
private Instant addedOn;
|
||||
private boolean isPrimary;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppBookProgressResponse {
|
||||
private Float readProgress;
|
||||
private String readStatus;
|
||||
private Instant lastReadTime;
|
||||
private AppBookDetail.EpubProgress epubProgress;
|
||||
private AppBookDetail.PdfProgress pdfProgress;
|
||||
private AppBookDetail.CbxProgress cbxProgress;
|
||||
private AppBookDetail.AudiobookProgress audiobookProgress;
|
||||
private AppBookDetail.KoreaderProgress koreaderProgress;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppBookSummary {
|
||||
private Long id;
|
||||
private String title;
|
||||
private List<String> authors;
|
||||
private String thumbnailUrl;
|
||||
private String readStatus;
|
||||
private Integer personalRating;
|
||||
private String seriesName;
|
||||
private Float seriesNumber;
|
||||
private Long libraryId;
|
||||
private Instant addedOn;
|
||||
private Instant lastReadTime;
|
||||
private Float readProgress;
|
||||
private String primaryFileType;
|
||||
private Instant coverUpdatedOn;
|
||||
private Instant audiobookCoverUpdatedOn;
|
||||
private Boolean isPhysical;
|
||||
|
||||
// Metadata for filtering
|
||||
private LocalDate publishedDate;
|
||||
private Integer pageCount;
|
||||
private Integer ageRating;
|
||||
private String contentRating;
|
||||
private Float metadataMatchScore;
|
||||
private Long fileSizeKb;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Builder
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record AppFilterOptions(
|
||||
List<CountedOption> authors,
|
||||
List<LanguageOption> languages,
|
||||
List<CountedOption> readStatuses,
|
||||
List<CountedOption> fileTypes,
|
||||
List<CountedOption> categories,
|
||||
List<CountedOption> publishers,
|
||||
List<CountedOption> series,
|
||||
List<CountedOption> tags,
|
||||
List<CountedOption> moods,
|
||||
List<CountedOption> narrators,
|
||||
List<CountedOption> ageRatings,
|
||||
List<CountedOption> contentRatings,
|
||||
List<CountedOption> matchScores,
|
||||
List<CountedOption> publishedYears,
|
||||
List<CountedOption> fileSizes,
|
||||
List<CountedOption> personalRatings,
|
||||
List<CountedOption> amazonRatings,
|
||||
List<CountedOption> goodreadsRatings,
|
||||
List<CountedOption> hardcoverRatings,
|
||||
List<CountedOption> lubimyczytacRatings,
|
||||
List<CountedOption> ranobedbRatings,
|
||||
List<CountedOption> audibleRatings,
|
||||
List<CountedOption> pageCounts,
|
||||
List<CountedOption> shelfStatuses,
|
||||
List<CountedOption> comicCharacters,
|
||||
List<CountedOption> comicTeams,
|
||||
List<CountedOption> comicLocations,
|
||||
List<CountedOption> comicCreators,
|
||||
List<CountedOption> shelves,
|
||||
List<CountedOption> libraries) {
|
||||
|
||||
public record LanguageOption(String code, String label, long count) {}
|
||||
|
||||
public record CountedOption(String name, long count) {}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppLibrarySummary {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String icon;
|
||||
private long bookCount;
|
||||
private List<BookFileType> allowedFormats;
|
||||
private List<PathSummary> paths;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class PathSummary {
|
||||
private Long id;
|
||||
private String path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppMagicShelfSummary {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String icon;
|
||||
private String iconType;
|
||||
private boolean publicShelf;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppNotebookBookSummary {
|
||||
private Long bookId;
|
||||
private String bookTitle;
|
||||
private int noteCount;
|
||||
private List<String> authors;
|
||||
private Instant coverUpdatedOn;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppNotebookEntry {
|
||||
private Long id;
|
||||
private String type;
|
||||
private Long bookId;
|
||||
private String text;
|
||||
private String note;
|
||||
private String color;
|
||||
private String style;
|
||||
private String chapterTitle;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class AppNotebookUpdateRequest {
|
||||
@Size(max = 5000)
|
||||
private String note;
|
||||
|
||||
@Pattern(regexp = "^#[0-9A-Fa-f]{6}$")
|
||||
private String color;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppPageResponse<T> {
|
||||
private List<T> content;
|
||||
private int page;
|
||||
private int size;
|
||||
private long totalElements;
|
||||
private int totalPages;
|
||||
private boolean hasNext;
|
||||
private boolean hasPrevious;
|
||||
|
||||
public static <T> AppPageResponse<T> of(List<T> content, int page, int size, long totalElements) {
|
||||
int totalPages = size > 0 ? (int) Math.ceil((double) totalElements / size) : 0;
|
||||
return AppPageResponse.<T>builder()
|
||||
.content(content)
|
||||
.page(page)
|
||||
.size(size)
|
||||
.totalElements(totalElements)
|
||||
.totalPages(totalPages)
|
||||
.hasNext(page < totalPages - 1)
|
||||
.hasPrevious(page > 0)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppSeriesSummary {
|
||||
private String seriesName;
|
||||
private int bookCount;
|
||||
private Integer seriesTotal;
|
||||
private List<String> authors;
|
||||
private int booksRead;
|
||||
private Instant latestAddedOn;
|
||||
private List<SeriesCoverBook> coverBooks;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AppShelfSummary {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String icon;
|
||||
private int bookCount;
|
||||
private boolean publicShelf;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class AppUserInfo {
|
||||
private boolean isAdmin;
|
||||
private boolean canUpload;
|
||||
private boolean canDownload;
|
||||
private boolean canAccessBookdrop;
|
||||
private int maxFileUploadSizeMb;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record BookListRequest(
|
||||
Integer page,
|
||||
Integer size,
|
||||
String sort,
|
||||
String dir,
|
||||
Long libraryId,
|
||||
Long shelfId,
|
||||
@Size(max = 20) List<String> status,
|
||||
String search,
|
||||
@Size(max = 20) List<String> fileType,
|
||||
Integer minRating,
|
||||
Integer maxRating,
|
||||
@Size(max = 20) List<String> authors,
|
||||
@Size(max = 20) List<String> language,
|
||||
@Size(max = 20) List<String> series,
|
||||
@Size(max = 20) List<String> category,
|
||||
@Size(max = 20) List<String> publisher,
|
||||
@Size(max = 20) List<String> tag,
|
||||
@Size(max = 20) List<String> mood,
|
||||
@Size(max = 20) List<String> narrator,
|
||||
@Size(max = 20) List<String> ageRating,
|
||||
@Size(max = 20) List<String> contentRating,
|
||||
@Size(max = 20) List<String> matchScore,
|
||||
@Size(max = 20) List<String> publishedDate,
|
||||
@Size(max = 20) List<String> fileSize,
|
||||
@Size(max = 20) List<String> personalRating,
|
||||
@Size(max = 20) List<String> amazonRating,
|
||||
@Size(max = 20) List<String> goodreadsRating,
|
||||
@Size(max = 20) List<String> hardcoverRating,
|
||||
@Size(max = 20) List<String> lubimyczytacRating,
|
||||
@Size(max = 20) List<String> ranobedbRating,
|
||||
@Size(max = 20) List<String> audibleRating,
|
||||
@Size(max = 20) List<String> pageCount,
|
||||
@Size(max = 20) List<String> shelfStatus,
|
||||
@Size(max = 20) List<String> comicCharacter,
|
||||
@Size(max = 20) List<String> comicTeam,
|
||||
@Size(max = 20) List<String> comicLocation,
|
||||
@Size(max = 20) List<String> comicCreator,
|
||||
@Size(max = 20) List<String> shelves,
|
||||
@Size(max = 20) List<String> libraries,
|
||||
Long magicShelfId,
|
||||
Boolean unshelved,
|
||||
String filterMode) {
|
||||
|
||||
/**
|
||||
* Returns the effective filter mode, defaulting to "or" when not specified.
|
||||
*/
|
||||
public String effectiveFilterMode() {
|
||||
if (filterMode == null || filterMode.isBlank()) return "or";
|
||||
return switch (filterMode.toLowerCase()) {
|
||||
case "and", "not" -> filterMode.toLowerCase();
|
||||
default -> "or";
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean hasValues(List<String> list) {
|
||||
return list != null && !list.isEmpty() && list.stream().anyMatch(s -> s != null && !s.isBlank());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns non-blank trimmed values from the given list, or an empty list.
|
||||
*/
|
||||
public static List<String> cleanValues(List<String> list) {
|
||||
if (list == null) return List.of();
|
||||
return list.stream()
|
||||
.filter(s -> s != null && !s.isBlank())
|
||||
.map(String::trim)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class SeriesCoverBook {
|
||||
private Long bookId;
|
||||
private Instant coverUpdatedOn;
|
||||
private Float seriesNumber;
|
||||
private String primaryFileType;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import lombok.Data;
|
||||
import org.booklore.model.dto.progress.AudiobookProgress;
|
||||
import org.booklore.model.dto.progress.CbxProgress;
|
||||
import org.booklore.model.dto.progress.EpubProgress;
|
||||
import org.booklore.model.dto.progress.PdfProgress;
|
||||
import org.booklore.model.dto.request.BookFileProgress;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Data
|
||||
public class UpdateProgressRequest {
|
||||
|
||||
private BookFileProgress fileProgress;
|
||||
|
||||
@Deprecated
|
||||
private EpubProgress epubProgress;
|
||||
@Deprecated
|
||||
private PdfProgress pdfProgress;
|
||||
@Deprecated
|
||||
private CbxProgress cbxProgress;
|
||||
@Deprecated
|
||||
private AudiobookProgress audiobookProgress;
|
||||
|
||||
private Instant dateFinished;
|
||||
|
||||
@AssertTrue(message = "At least one progress field must be provided")
|
||||
public boolean isProgressValid() {
|
||||
return fileProgress != null || epubProgress != null || pdfProgress != null || cbxProgress != null || audiobookProgress != null || dateFinished != null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UpdateRatingRequest {
|
||||
@Min(value = 1, message = "Rating must be at least 1")
|
||||
@Max(value = 5, message = "Rating must be at most 5")
|
||||
private Integer rating;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.booklore.app.dto;
|
||||
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UpdateStatusRequest {
|
||||
@NotNull(message = "Status is required")
|
||||
private ReadStatus status;
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
package org.booklore.app.mapper;
|
||||
|
||||
import org.booklore.app.dto.AppBookDetail;
|
||||
import org.booklore.app.dto.AppBookFile;
|
||||
import org.booklore.app.dto.AppBookProgressResponse;
|
||||
import org.booklore.app.dto.AppBookSummary;
|
||||
import org.booklore.app.dto.AppLibrarySummary;
|
||||
import org.booklore.app.dto.AppMagicShelfSummary;
|
||||
import org.booklore.app.dto.AppShelfSummary;
|
||||
import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.mapstruct.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface AppBookMapper {
|
||||
|
||||
@Mapping(target = "id", source = "book.id")
|
||||
@Mapping(target = "title", source = "book.metadata.title")
|
||||
@Mapping(target = "authors", source = "book.metadata.authors", qualifiedByName = "mapAuthors")
|
||||
@Mapping(target = "thumbnailUrl", source = "book", qualifiedByName = "mapThumbnailUrl")
|
||||
@Mapping(target = "readStatus", source = "progress.readStatus")
|
||||
@Mapping(target = "personalRating", source = "progress.personalRating")
|
||||
@Mapping(target = "seriesName", source = "book.metadata.seriesName")
|
||||
@Mapping(target = "seriesNumber", source = "book.metadata.seriesNumber")
|
||||
@Mapping(target = "libraryId", source = "book.library.id")
|
||||
@Mapping(target = "addedOn", source = "book.addedOn")
|
||||
@Mapping(target = "lastReadTime", source = "progress.lastReadTime")
|
||||
@Mapping(target = "readProgress", source = "progress", qualifiedByName = "mapReadProgress")
|
||||
@Mapping(target = "primaryFileType", source = "book", qualifiedByName = "mapPrimaryFileType")
|
||||
@Mapping(target = "coverUpdatedOn", source = "book.metadata.coverUpdatedOn")
|
||||
@Mapping(target = "audiobookCoverUpdatedOn", source = "book.metadata.audiobookCoverUpdatedOn")
|
||||
@Mapping(target = "isPhysical", source = "book.isPhysical")
|
||||
@Mapping(target = "publishedDate", source = "book.metadata.publishedDate")
|
||||
@Mapping(target = "pageCount", source = "book.metadata.pageCount")
|
||||
@Mapping(target = "ageRating", source = "book.metadata.ageRating")
|
||||
@Mapping(target = "contentRating", source = "book.metadata.contentRating")
|
||||
@Mapping(target = "metadataMatchScore", source = "book.metadataMatchScore")
|
||||
@Mapping(target = "fileSizeKb", source = "book", qualifiedByName = "mapFileSizeKb")
|
||||
AppBookSummary toSummary(BookEntity book, UserBookProgressEntity progress);
|
||||
|
||||
@Mapping(target = "id", source = "book.id")
|
||||
@Mapping(target = "title", source = "book.metadata.title")
|
||||
@Mapping(target = "authors", source = "book.metadata.authors", qualifiedByName = "mapAuthors")
|
||||
@Mapping(target = "thumbnailUrl", source = "book", qualifiedByName = "mapThumbnailUrl")
|
||||
@Mapping(target = "readStatus", source = "progress.readStatus")
|
||||
@Mapping(target = "personalRating", source = "progress.personalRating")
|
||||
@Mapping(target = "seriesName", source = "book.metadata.seriesName")
|
||||
@Mapping(target = "seriesNumber", source = "book.metadata.seriesNumber")
|
||||
@Mapping(target = "libraryId", source = "book.library.id")
|
||||
@Mapping(target = "addedOn", source = "book.addedOn")
|
||||
@Mapping(target = "lastReadTime", source = "progress.lastReadTime")
|
||||
@Mapping(target = "subtitle", source = "book.metadata.subtitle")
|
||||
@Mapping(target = "description", source = "book.metadata.description")
|
||||
@Mapping(target = "categories", source = "book.metadata.categories", qualifiedByName = "mapCategories")
|
||||
@Mapping(target = "publisher", source = "book.metadata.publisher")
|
||||
@Mapping(target = "publishedDate", source = "book.metadata.publishedDate")
|
||||
@Mapping(target = "pageCount", source = "book.metadata.pageCount")
|
||||
@Mapping(target = "isbn13", source = "book.metadata.isbn13")
|
||||
@Mapping(target = "language", source = "book.metadata.language")
|
||||
@Mapping(target = "goodreadsRating", source = "book.metadata.goodreadsRating")
|
||||
@Mapping(target = "goodreadsReviewCount", source = "book.metadata.goodreadsReviewCount")
|
||||
@Mapping(target = "libraryName", source = "book.library.name")
|
||||
@Mapping(target = "shelves", source = "book.shelves", qualifiedByName = "mapShelves")
|
||||
@Mapping(target = "readProgress", source = "progress", qualifiedByName = "mapReadProgress")
|
||||
@Mapping(target = "primaryFileType", source = "book", qualifiedByName = "mapPrimaryFileType")
|
||||
@Mapping(target = "coverUpdatedOn", source = "book.metadata.coverUpdatedOn")
|
||||
@Mapping(target = "audiobookCoverUpdatedOn", source = "book.metadata.audiobookCoverUpdatedOn")
|
||||
@Mapping(target = "isPhysical", source = "book.isPhysical")
|
||||
@Mapping(target = "fileTypes", source = "book", qualifiedByName = "mapFileTypes")
|
||||
@Mapping(target = "files", source = "book", qualifiedByName = "mapFiles")
|
||||
@Mapping(target = "epubProgress", source = "progress", qualifiedByName = "mapEpubProgress")
|
||||
@Mapping(target = "pdfProgress", source = "progress", qualifiedByName = "mapPdfProgress")
|
||||
@Mapping(target = "cbxProgress", source = "progress", qualifiedByName = "mapCbxProgress")
|
||||
@Mapping(target = "audiobookProgress", source = "fileProgress", qualifiedByName = "mapAudiobookProgress")
|
||||
@Mapping(target = "koreaderProgress", source = "progress", qualifiedByName = "mapKoreaderProgress")
|
||||
AppBookDetail toDetail(BookEntity book, UserBookProgressEntity progress, UserBookFileProgressEntity fileProgress);
|
||||
|
||||
default AppBookProgressResponse toProgressResponse(UserBookProgressEntity progress, UserBookFileProgressEntity fileProgress) {
|
||||
return AppBookProgressResponse.builder()
|
||||
.readProgress(mapReadProgress(progress))
|
||||
.readStatus(progress != null && progress.getReadStatus() != null
|
||||
? progress.getReadStatus().name() : null)
|
||||
.lastReadTime(progress != null ? progress.getLastReadTime() : null)
|
||||
.epubProgress(mapEpubProgress(progress))
|
||||
.pdfProgress(mapPdfProgress(progress))
|
||||
.cbxProgress(mapCbxProgress(progress))
|
||||
.audiobookProgress(mapAudiobookProgress(fileProgress))
|
||||
.koreaderProgress(mapKoreaderProgress(progress))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Named("mapAuthors")
|
||||
default List<String> mapAuthors(List<AuthorEntity> authors) {
|
||||
if (authors == null || authors.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return authors.stream()
|
||||
.map(AuthorEntity::getName)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Named("mapCategories")
|
||||
default Set<String> mapCategories(Set<CategoryEntity> categories) {
|
||||
if (categories == null || categories.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return categories.stream()
|
||||
.map(CategoryEntity::getName)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Named("mapThumbnailUrl")
|
||||
default String mapThumbnailUrl(BookEntity book) {
|
||||
if (book == null || book.getId() == null) {
|
||||
return null;
|
||||
}
|
||||
return "/api/books/" + book.getId() + "/cover";
|
||||
}
|
||||
|
||||
@Named("mapFileSizeKb")
|
||||
default Long mapFileSizeKb(BookEntity book) {
|
||||
if (book == null) return null;
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
return primaryFile != null ? primaryFile.getFileSizeKb() : null;
|
||||
}
|
||||
|
||||
@Named("mapShelves")
|
||||
default List<AppShelfSummary> mapShelves(Set<ShelfEntity> shelves) {
|
||||
if (shelves == null || shelves.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return shelves.stream()
|
||||
.map(this::toShelfSummary)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
default AppShelfSummary toShelfSummary(ShelfEntity shelf) {
|
||||
if (shelf == null) {
|
||||
return null;
|
||||
}
|
||||
return AppShelfSummary.builder()
|
||||
.id(shelf.getId())
|
||||
.name(shelf.getName())
|
||||
.icon(shelf.getIcon())
|
||||
.bookCount(shelf.getBookCount())
|
||||
.publicShelf(shelf.isPublic())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Named("mapReadProgress")
|
||||
default Float mapReadProgress(UserBookProgressEntity progress) {
|
||||
if (progress == null) {
|
||||
return null;
|
||||
}
|
||||
if (progress.getKoreaderProgressPercent() != null) {
|
||||
return progress.getKoreaderProgressPercent();
|
||||
}
|
||||
if (progress.getKoboProgressPercent() != null) {
|
||||
return progress.getKoboProgressPercent();
|
||||
}
|
||||
if (progress.getEpubProgressPercent() != null) {
|
||||
return progress.getEpubProgressPercent();
|
||||
}
|
||||
if (progress.getPdfProgressPercent() != null) {
|
||||
return progress.getPdfProgressPercent();
|
||||
}
|
||||
if (progress.getCbxProgressPercent() != null) {
|
||||
return progress.getCbxProgressPercent();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Named("mapEpubProgress")
|
||||
default AppBookDetail.EpubProgress mapEpubProgress(UserBookProgressEntity progress) {
|
||||
if (progress == null || progress.getEpubProgress() == null) {
|
||||
return null;
|
||||
}
|
||||
return AppBookDetail.EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.href(progress.getEpubProgressHref())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.updatedAt(progress.getLastReadTime())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Named("mapPdfProgress")
|
||||
default AppBookDetail.PdfProgress mapPdfProgress(UserBookProgressEntity progress) {
|
||||
if (progress == null || progress.getPdfProgress() == null) {
|
||||
return null;
|
||||
}
|
||||
return AppBookDetail.PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.updatedAt(progress.getLastReadTime())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Named("mapCbxProgress")
|
||||
default AppBookDetail.CbxProgress mapCbxProgress(UserBookProgressEntity progress) {
|
||||
if (progress == null || progress.getCbxProgress() == null) {
|
||||
return null;
|
||||
}
|
||||
return AppBookDetail.CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.updatedAt(progress.getLastReadTime())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Named("mapKoreaderProgress")
|
||||
default AppBookDetail.KoreaderProgress mapKoreaderProgress(UserBookProgressEntity progress) {
|
||||
if (progress == null || progress.getKoreaderProgressPercent() == null) {
|
||||
return null;
|
||||
}
|
||||
return AppBookDetail.KoreaderProgress.builder()
|
||||
.percentage(progress.getKoreaderProgressPercent())
|
||||
.device(progress.getKoreaderDevice())
|
||||
.deviceId(progress.getKoreaderDeviceId())
|
||||
.lastSyncTime(progress.getKoreaderLastSyncTime())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Named("mapAudiobookProgress")
|
||||
default AppBookDetail.AudiobookProgress mapAudiobookProgress(UserBookFileProgressEntity fileProgress) {
|
||||
if (fileProgress == null) return null;
|
||||
if (fileProgress.getBookFile() == null ||
|
||||
fileProgress.getBookFile().getBookType() != BookFileType.AUDIOBOOK) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return AppBookDetail.AudiobookProgress.builder()
|
||||
.positionMs(parseLongOrNull(fileProgress.getPositionData()))
|
||||
.trackIndex(parseIntOrNull(fileProgress.getPositionHref()))
|
||||
.percentage(fileProgress.getProgressPercent())
|
||||
.updatedAt(fileProgress.getLastReadTime())
|
||||
.build();
|
||||
}
|
||||
|
||||
default Long parseLongOrNull(String value) {
|
||||
if (value == null) return null;
|
||||
try {
|
||||
return Long.parseLong(value);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
default Integer parseIntOrNull(String value) {
|
||||
if (value == null) return null;
|
||||
try {
|
||||
return Integer.parseInt(value);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Named("mapPrimaryFileType")
|
||||
default String mapPrimaryFileType(BookEntity book) {
|
||||
if (book == null) {
|
||||
return null;
|
||||
}
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile != null && primaryFile.getBookType() != null) {
|
||||
return primaryFile.getBookType().name();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Named("mapFileTypes")
|
||||
default List<String> mapFileTypes(BookEntity book) {
|
||||
if (book == null || book.getBookFiles() == null || book.getBookFiles().isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return book.getBookFiles().stream()
|
||||
.filter(bf -> bf.getBookType() != null)
|
||||
.map(bf -> bf.getBookType().name())
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Named("mapFiles")
|
||||
default List<AppBookFile> mapFiles(BookEntity book) {
|
||||
if (book == null || book.getBookFiles() == null || book.getBookFiles().isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
Long primaryId = primaryFile != null ? primaryFile.getId() : null;
|
||||
|
||||
return book.getBookFiles().stream()
|
||||
.filter(bf -> bf.getBookType() != null && bf.isBook())
|
||||
.map(bf -> {
|
||||
String extension = null;
|
||||
try {
|
||||
String fileName = bf.getFileName();
|
||||
int lastDot = fileName.lastIndexOf('.');
|
||||
if (lastDot > 0) {
|
||||
extension = fileName.substring(lastDot + 1);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Handle case where extension cannot be extracted
|
||||
}
|
||||
|
||||
return AppBookFile.builder()
|
||||
.id(bf.getId())
|
||||
.bookId(bf.getBook() != null ? bf.getBook().getId() : null)
|
||||
.fileName(bf.getFileName())
|
||||
.isBook(bf.isBook())
|
||||
.folderBased(bf.isFolderBased())
|
||||
.bookType(bf.getBookType().name())
|
||||
.archiveType(bf.getArchiveType() != null ? bf.getArchiveType().name() : null)
|
||||
.fileSizeKb(bf.getFileSizeKb())
|
||||
.extension(extension)
|
||||
.addedOn(bf.getAddedOn())
|
||||
.isPrimary(bf.getId().equals(primaryId))
|
||||
.build();
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
default AppLibrarySummary toLibrarySummary(LibraryEntity library, long bookCount) {
|
||||
if (library == null) {
|
||||
return null;
|
||||
}
|
||||
List<AppLibrarySummary.PathSummary> paths = Collections.emptyList();
|
||||
if (library.getLibraryPaths() != null && !library.getLibraryPaths().isEmpty()) {
|
||||
paths = library.getLibraryPaths().stream()
|
||||
.map(lp -> AppLibrarySummary.PathSummary.builder()
|
||||
.id(lp.getId())
|
||||
.path(lp.getPath())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
return AppLibrarySummary.builder()
|
||||
.id(library.getId())
|
||||
.name(library.getName())
|
||||
.icon(library.getIcon())
|
||||
.bookCount(bookCount)
|
||||
.allowedFormats(library.getAllowedFormats())
|
||||
.paths(paths)
|
||||
.build();
|
||||
}
|
||||
|
||||
default AppShelfSummary toShelfSummaryFromEntity(ShelfEntity shelf) {
|
||||
if (shelf == null) {
|
||||
return null;
|
||||
}
|
||||
return AppShelfSummary.builder()
|
||||
.id(shelf.getId())
|
||||
.name(shelf.getName())
|
||||
.icon(shelf.getIcon())
|
||||
.bookCount(shelf.getBookCount())
|
||||
.publicShelf(shelf.isPublic())
|
||||
.build();
|
||||
}
|
||||
|
||||
default AppMagicShelfSummary toMagicShelfSummary(MagicShelfEntity magicShelf) {
|
||||
if (magicShelf == null) {
|
||||
return null;
|
||||
}
|
||||
return AppMagicShelfSummary.builder()
|
||||
.id(magicShelf.getId())
|
||||
.name(magicShelf.getName())
|
||||
.icon(magicShelf.getIcon())
|
||||
.iconType(magicShelf.getIconType() != null ? magicShelf.getIconType().name() : null)
|
||||
.publicShelf(magicShelf.isPublic())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package org.booklore.app.service;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.app.dto.AppAuthorDetail;
|
||||
import org.booklore.app.dto.AppAuthorSummary;
|
||||
import org.booklore.app.dto.AppPageResponse;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.entity.AuthorEntity;
|
||||
import org.booklore.repository.AuthorRepository;
|
||||
import org.booklore.util.FileService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.TypedQuery;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class AppAuthorService {
|
||||
|
||||
private static final int DEFAULT_PAGE_SIZE = 30;
|
||||
private static final int MAX_PAGE_SIZE = 50;
|
||||
|
||||
private final AuthorRepository authorRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final FileService fileService;
|
||||
private final EntityManager entityManager;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AppPageResponse<AppAuthorSummary> getAuthors(
|
||||
Integer page,
|
||||
Integer size,
|
||||
String sortBy,
|
||||
String sortDir,
|
||||
Long libraryId,
|
||||
String search,
|
||||
Boolean hasPhoto) {
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
|
||||
|
||||
int pageNum = page != null && page >= 0 ? page : 0;
|
||||
int pageSize = size != null && size > 0 ? Math.min(size, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
|
||||
|
||||
StringBuilder whereClause = new StringBuilder(" WHERE (1=1)");
|
||||
buildLibraryFilter(whereClause, accessibleLibraryIds, libraryId);
|
||||
buildSearchFilter(whereClause, search);
|
||||
|
||||
String fromClause = " FROM AuthorEntity a LEFT JOIN a.bookMetadataEntityList bm LEFT JOIN bm.book b";
|
||||
|
||||
// Count query
|
||||
String countJpql = "SELECT COUNT(DISTINCT a.id)" + fromClause + whereClause;
|
||||
TypedQuery<Long> countQuery = entityManager.createQuery(countJpql, Long.class);
|
||||
setQueryParams(countQuery, accessibleLibraryIds, libraryId, search);
|
||||
long totalElements = countQuery.getSingleResult();
|
||||
|
||||
if (totalElements == 0) {
|
||||
return AppPageResponse.of(Collections.emptyList(), pageNum, pageSize, 0L);
|
||||
}
|
||||
|
||||
// Data query with book count
|
||||
String orderClause = buildOrderClause(sortBy, sortDir);
|
||||
String dataJpql = "SELECT a, COUNT(DISTINCT bm.id)" + fromClause + whereClause
|
||||
+ " GROUP BY a" + orderClause;
|
||||
TypedQuery<Object[]> dataQuery = entityManager.createQuery(dataJpql, Object[].class);
|
||||
setQueryParams(dataQuery, accessibleLibraryIds, libraryId, search);
|
||||
dataQuery.setFirstResult(pageNum * pageSize);
|
||||
dataQuery.setMaxResults(pageSize);
|
||||
|
||||
List<Object[]> results = dataQuery.getResultList();
|
||||
|
||||
List<AppAuthorSummary> summaries = results.stream()
|
||||
.map(row -> {
|
||||
AuthorEntity author = (AuthorEntity) row[0];
|
||||
long bookCount = (Long) row[1];
|
||||
boolean authorHasPhoto = Files.exists(Paths.get(fileService.getAuthorThumbnailFile(author.getId())));
|
||||
return AppAuthorSummary.builder()
|
||||
.id(author.getId())
|
||||
.name(author.getName())
|
||||
.asin(author.getAsin())
|
||||
.bookCount((int) bookCount)
|
||||
.hasPhoto(authorHasPhoto)
|
||||
.build();
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Post-filter by hasPhoto if requested
|
||||
if (hasPhoto != null) {
|
||||
summaries = summaries.stream()
|
||||
.filter(s -> s.isHasPhoto() == hasPhoto)
|
||||
.collect(Collectors.toList());
|
||||
// Adjust total count for hasPhoto filter — requires a separate count
|
||||
long filteredTotal = countAuthorsWithPhotoFilter(accessibleLibraryIds, libraryId, search, hasPhoto);
|
||||
return AppPageResponse.of(summaries, pageNum, pageSize, filteredTotal);
|
||||
}
|
||||
|
||||
return AppPageResponse.of(summaries, pageNum, pageSize, totalElements);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AppAuthorDetail getAuthorDetail(Long authorId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
|
||||
|
||||
AuthorEntity author = authorRepository.findById(authorId)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
|
||||
|
||||
// Verify access for non-admin users
|
||||
if (accessibleLibraryIds != null) {
|
||||
if (accessibleLibraryIds.isEmpty() || !authorRepository.existsByIdAndLibraryIds(authorId, accessibleLibraryIds)) {
|
||||
throw ApiError.AUTHOR_NOT_FOUND.createException(authorId);
|
||||
}
|
||||
}
|
||||
|
||||
// Count books accessible to this user
|
||||
int bookCount = countAccessibleBooks(authorId, accessibleLibraryIds);
|
||||
boolean authorHasPhoto = Files.exists(Paths.get(fileService.getAuthorThumbnailFile(author.getId())));
|
||||
|
||||
return AppAuthorDetail.builder()
|
||||
.id(author.getId())
|
||||
.name(author.getName())
|
||||
.description(author.getDescription())
|
||||
.asin(author.getAsin())
|
||||
.bookCount(bookCount)
|
||||
.hasPhoto(authorHasPhoto)
|
||||
.build();
|
||||
}
|
||||
|
||||
private int countAccessibleBooks(Long authorId, Set<Long> accessibleLibraryIds) {
|
||||
StringBuilder jpql = new StringBuilder(
|
||||
"SELECT COUNT(DISTINCT bm.id) FROM AuthorEntity a JOIN a.bookMetadataEntityList bm JOIN bm.book b"
|
||||
+ " WHERE a.id = :authorId AND (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY");
|
||||
if (accessibleLibraryIds != null) {
|
||||
jpql.append(" AND b.library.id IN :libraryIds");
|
||||
}
|
||||
TypedQuery<Long> query = entityManager.createQuery(jpql.toString(), Long.class);
|
||||
query.setParameter("authorId", authorId);
|
||||
if (accessibleLibraryIds != null) {
|
||||
query.setParameter("libraryIds", accessibleLibraryIds);
|
||||
}
|
||||
return query.getSingleResult().intValue();
|
||||
}
|
||||
|
||||
private long countAuthorsWithPhotoFilter(Set<Long> accessibleLibraryIds, Long libraryId, String search, boolean hasPhoto) {
|
||||
// Since hasPhoto is file-system based, we need to count all matching authors
|
||||
// and check their photos. For large datasets this could be optimized with a DB column.
|
||||
StringBuilder whereClause = new StringBuilder(" WHERE (1=1)");
|
||||
buildLibraryFilter(whereClause, accessibleLibraryIds, libraryId);
|
||||
buildSearchFilter(whereClause, search);
|
||||
|
||||
String jpql = "SELECT DISTINCT a FROM AuthorEntity a LEFT JOIN a.bookMetadataEntityList bm LEFT JOIN bm.book b"
|
||||
+ whereClause;
|
||||
TypedQuery<AuthorEntity> query = entityManager.createQuery(jpql, AuthorEntity.class);
|
||||
setQueryParams(query, accessibleLibraryIds, libraryId, search);
|
||||
|
||||
return query.getResultList().stream()
|
||||
.filter(a -> Files.exists(Paths.get(fileService.getAuthorThumbnailFile(a.getId()))) == hasPhoto)
|
||||
.count();
|
||||
}
|
||||
|
||||
private void buildLibraryFilter(StringBuilder whereClause, Set<Long> accessibleLibraryIds, Long libraryId) {
|
||||
if (libraryId != null) {
|
||||
whereClause.append(" AND b.library.id = :libraryId");
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
whereClause.append(" AND b.library.id IN :libraryIds");
|
||||
}
|
||||
whereClause.append(" AND (b.deleted IS NULL OR b.deleted = false)");
|
||||
whereClause.append(" AND b.bookFiles IS NOT EMPTY");
|
||||
}
|
||||
|
||||
private void buildSearchFilter(StringBuilder whereClause, String search) {
|
||||
if (search != null && !search.trim().isEmpty()) {
|
||||
whereClause.append(" AND LOWER(a.name) LIKE :search");
|
||||
}
|
||||
}
|
||||
|
||||
private String buildOrderClause(String sortBy, String sortDir) {
|
||||
String direction = "asc".equalsIgnoreCase(sortDir) ? "ASC" : "DESC";
|
||||
String field = switch (sortBy != null ? sortBy.toLowerCase() : "") {
|
||||
case "name" -> "a.name";
|
||||
case "bookcount", "book_count" -> "COUNT(DISTINCT bm.id)";
|
||||
case "recent", "id" -> "a.id";
|
||||
default -> "a.name";
|
||||
};
|
||||
return " ORDER BY " + field + " " + direction;
|
||||
}
|
||||
|
||||
private void setQueryParams(TypedQuery<?> query, Set<Long> accessibleLibraryIds, Long libraryId, String search) {
|
||||
if (libraryId != null) {
|
||||
query.setParameter("libraryId", libraryId);
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
query.setParameter("libraryIds", accessibleLibraryIds);
|
||||
}
|
||||
if (search != null && !search.trim().isEmpty()) {
|
||||
query.setParameter("search", "%" + search.trim().toLowerCase() + "%");
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Long> getAccessibleLibraryIds(BookLoreUser user) {
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
return null;
|
||||
}
|
||||
if (user.getAssignedLibraries() == null || user.getAssignedLibraries().isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,197 @@
|
||||
package org.booklore.app.service;
|
||||
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.app.dto.AppNotebookBookSummary;
|
||||
import org.booklore.app.dto.AppNotebookEntry;
|
||||
import org.booklore.app.dto.AppNotebookUpdateRequest;
|
||||
import org.booklore.app.dto.AppPageResponse;
|
||||
import org.booklore.model.dto.UpdateAnnotationRequest;
|
||||
import org.booklore.model.dto.UpdateBookMarkRequest;
|
||||
import org.booklore.model.dto.UpdateBookNoteV2Request;
|
||||
import org.booklore.repository.AuthorRepository;
|
||||
import org.booklore.repository.NotebookEntryRepository;
|
||||
import org.booklore.service.book.AnnotationService;
|
||||
import org.booklore.service.book.BookMarkService;
|
||||
import org.booklore.service.book.BookNoteV2Service;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class AppNotebookService {
|
||||
|
||||
private final NotebookEntryRepository notebookEntryRepository;
|
||||
private final AuthorRepository authorRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final AnnotationService annotationService;
|
||||
private final BookNoteV2Service bookNoteV2Service;
|
||||
private final BookMarkService bookMarkService;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AppPageResponse<AppNotebookBookSummary> getBooksWithAnnotations(int page, int size, String search) {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
Pageable pageable = PageRequest.of(page, size);
|
||||
|
||||
Page<NotebookEntryRepository.BookWithCountProjection> booksPage =
|
||||
notebookEntryRepository.findBooksWithAnnotationsPaginated(userId, wrapSearch(search), pageable);
|
||||
|
||||
List<NotebookEntryRepository.BookWithCountProjection> content = booksPage.getContent();
|
||||
if (content.isEmpty()) {
|
||||
return AppPageResponse.of(List.of(), page, size, 0);
|
||||
}
|
||||
|
||||
Set<Long> bookIds = content.stream()
|
||||
.map(NotebookEntryRepository.BookWithCountProjection::getBookId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Map<Long, List<String>> authorsByBook = authorRepository.findAuthorNamesByBookIds(bookIds)
|
||||
.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
AuthorRepository.AuthorBookProjection::getBookId,
|
||||
Collectors.mapping(AuthorRepository.AuthorBookProjection::getAuthorName, Collectors.toList())));
|
||||
|
||||
List<AppNotebookBookSummary> summaries = content.stream()
|
||||
.map(p -> AppNotebookBookSummary.builder()
|
||||
.bookId(p.getBookId())
|
||||
.bookTitle(p.getBookTitle())
|
||||
.noteCount(p.getNoteCount())
|
||||
.authors(authorsByBook.getOrDefault(p.getBookId(), List.of()))
|
||||
.coverUpdatedOn(p.getCoverUpdatedOn())
|
||||
.build())
|
||||
.toList();
|
||||
|
||||
return AppPageResponse.of(summaries, page, size, booksPage.getTotalElements());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AppPageResponse<AppNotebookEntry> getEntriesForBook(Long bookId, int page, int size,
|
||||
Set<String> types, String search, String sort) {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
Set<String> entryTypes = (types == null || types.isEmpty())
|
||||
? Set.of("HIGHLIGHT", "NOTE", "BOOKMARK")
|
||||
: types;
|
||||
Pageable pageable = PageRequest.of(page, size, toSort(sort));
|
||||
|
||||
Page<NotebookEntryRepository.EntryProjection> entriesPage =
|
||||
notebookEntryRepository.findEntries(userId, entryTypes, bookId, wrapSearch(search), pageable);
|
||||
|
||||
List<AppNotebookEntry> entries = entriesPage.getContent().stream()
|
||||
.map(AppNotebookService::toMobileEntry)
|
||||
.toList();
|
||||
|
||||
return AppPageResponse.of(entries, page, size, entriesPage.getTotalElements());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AppNotebookEntry updateEntry(Long entryId, String type, AppNotebookUpdateRequest request) {
|
||||
return switch (type.toUpperCase()) {
|
||||
case "HIGHLIGHT" -> {
|
||||
var updateReq = new UpdateAnnotationRequest();
|
||||
if (request.getNote() != null) updateReq.setNote(request.getNote());
|
||||
if (request.getColor() != null) updateReq.setColor(request.getColor());
|
||||
var result = annotationService.updateAnnotation(entryId, updateReq);
|
||||
yield AppNotebookEntry.builder()
|
||||
.id(result.getId())
|
||||
.type("HIGHLIGHT")
|
||||
.bookId(result.getBookId())
|
||||
.text(result.getText())
|
||||
.note(result.getNote())
|
||||
.color(result.getColor())
|
||||
.style(result.getStyle())
|
||||
.chapterTitle(result.getChapterTitle())
|
||||
.createdAt(result.getCreatedAt())
|
||||
.updatedAt(result.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
case "NOTE" -> {
|
||||
var updateReq = new UpdateBookNoteV2Request();
|
||||
if (request.getNote() != null) updateReq.setNoteContent(request.getNote());
|
||||
if (request.getColor() != null) updateReq.setColor(request.getColor());
|
||||
var result = bookNoteV2Service.updateNote(entryId, updateReq);
|
||||
yield AppNotebookEntry.builder()
|
||||
.id(result.getId())
|
||||
.type("NOTE")
|
||||
.bookId(result.getBookId())
|
||||
.text(result.getSelectedText())
|
||||
.note(result.getNoteContent())
|
||||
.color(result.getColor())
|
||||
.chapterTitle(result.getChapterTitle())
|
||||
.createdAt(result.getCreatedAt())
|
||||
.updatedAt(result.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
case "BOOKMARK" -> {
|
||||
var updateReq = new UpdateBookMarkRequest();
|
||||
if (request.getNote() != null) updateReq.setNotes(request.getNote());
|
||||
if (request.getColor() != null) updateReq.setColor(request.getColor());
|
||||
var result = bookMarkService.updateBookmark(entryId, updateReq);
|
||||
yield AppNotebookEntry.builder()
|
||||
.id(result.getId())
|
||||
.type("BOOKMARK")
|
||||
.bookId(result.getBookId())
|
||||
.text(result.getTitle())
|
||||
.note(result.getNotes())
|
||||
.color(result.getColor())
|
||||
.createdAt(result.getCreatedAt())
|
||||
.updatedAt(result.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
default -> throw new IllegalArgumentException("Unknown entry type: " + type);
|
||||
};
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteEntry(Long entryId, String type) {
|
||||
switch (type.toUpperCase()) {
|
||||
case "HIGHLIGHT" -> annotationService.deleteAnnotation(entryId);
|
||||
case "NOTE" -> bookNoteV2Service.deleteNote(entryId);
|
||||
case "BOOKMARK" -> bookMarkService.deleteBookmark(entryId);
|
||||
default -> throw new IllegalArgumentException("Unknown entry type: " + type);
|
||||
}
|
||||
}
|
||||
|
||||
private String wrapSearch(String search) {
|
||||
if (search == null || search.isBlank()) return null;
|
||||
return "%" + escapeLike(search) + "%";
|
||||
}
|
||||
|
||||
private static String escapeLike(String input) {
|
||||
return input.trim()
|
||||
.replace("\\", "\\\\")
|
||||
.replace("%", "\\%")
|
||||
.replace("_", "\\_");
|
||||
}
|
||||
|
||||
private static Sort toSort(String sort) {
|
||||
if ("chapter".equalsIgnoreCase(sort)) {
|
||||
return Sort.by(Sort.Order.asc("chapterTitle"), Sort.Order.asc("createdAt"));
|
||||
}
|
||||
if ("date_asc".equalsIgnoreCase(sort)) {
|
||||
return Sort.by("createdAt").ascending();
|
||||
}
|
||||
return Sort.by("createdAt").descending();
|
||||
}
|
||||
|
||||
private static AppNotebookEntry toMobileEntry(NotebookEntryRepository.EntryProjection p) {
|
||||
return AppNotebookEntry.builder()
|
||||
.id(p.getId())
|
||||
.type(p.getType())
|
||||
.bookId(p.getBookId())
|
||||
.text(p.getText())
|
||||
.note(p.getNote())
|
||||
.color(p.getColor())
|
||||
.style(p.getStyle())
|
||||
.chapterTitle(p.getChapterTitle())
|
||||
.createdAt(p.getCreatedAt())
|
||||
.updatedAt(p.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package org.booklore.app.service;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.Tuple;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.app.dto.*;
|
||||
import org.booklore.app.mapper.AppBookMapper;
|
||||
import org.booklore.app.specification.AppBookSpecification;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Library;
|
||||
import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.UserBookProgressRepository;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class AppSeriesService {
|
||||
|
||||
private static final int DEFAULT_PAGE_SIZE = 20;
|
||||
private static final int MAX_PAGE_SIZE = 50;
|
||||
|
||||
private final EntityManager entityManager;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final BookRepository bookRepository;
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final AppBookMapper mobileBookMapper;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AppPageResponse<AppSeriesSummary> getSeries(
|
||||
Integer page,
|
||||
Integer size,
|
||||
String sortBy,
|
||||
String sortDir,
|
||||
Long libraryId,
|
||||
String search,
|
||||
boolean inProgressOnly) {
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Long userId = user.getId();
|
||||
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
|
||||
|
||||
if (libraryId != null) {
|
||||
validateLibraryAccess(accessibleLibraryIds, libraryId);
|
||||
}
|
||||
|
||||
int pageNum = page != null && page >= 0 ? page : 0;
|
||||
int pageSize = size != null && size > 0 ? Math.min(size, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
|
||||
|
||||
// Build WHERE clause fragments
|
||||
String libraryClause = buildLibraryClause(accessibleLibraryIds, libraryId);
|
||||
String searchClause = (search != null && !search.trim().isEmpty())
|
||||
? " AND LOWER(m.seriesName) LIKE :searchPattern"
|
||||
: "";
|
||||
|
||||
String havingClause = inProgressOnly
|
||||
? " HAVING SUM(CASE WHEN p.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING) THEN 1 ELSE 0 END) > 0"
|
||||
: "";
|
||||
|
||||
String orderBy = buildSeriesOrderBy(sortBy, sortDir, inProgressOnly);
|
||||
|
||||
// Phase 1: Aggregate query
|
||||
String aggregateQuery = "SELECT m.seriesName, COUNT(b.id), MAX(m.seriesTotal), MAX(b.addedOn),"
|
||||
+ " SUM(CASE WHEN p.readStatus = org.booklore.model.enums.ReadStatus.READ THEN 1 ELSE 0 END)"
|
||||
+ (inProgressOnly ? ", MAX(p.lastReadTime)" : "")
|
||||
+ " FROM BookEntity b JOIN b.metadata m"
|
||||
+ " LEFT JOIN b.userBookProgress p ON p.user.id = :userId"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ " AND m.seriesName IS NOT NULL"
|
||||
+ libraryClause
|
||||
+ searchClause
|
||||
+ " GROUP BY m.seriesName"
|
||||
+ havingClause
|
||||
+ " ORDER BY " + orderBy;
|
||||
|
||||
var aggregateQ = entityManager.createQuery(aggregateQuery, Tuple.class);
|
||||
aggregateQ.setParameter("userId", userId);
|
||||
setLibraryParams(aggregateQ, accessibleLibraryIds, libraryId);
|
||||
if (!searchClause.isEmpty()) {
|
||||
aggregateQ.setParameter("searchPattern", "%" + search.trim().toLowerCase() + "%");
|
||||
}
|
||||
aggregateQ.setFirstResult(pageNum * pageSize);
|
||||
aggregateQ.setMaxResults(pageSize);
|
||||
|
||||
List<Tuple> aggregateResults = aggregateQ.getResultList();
|
||||
|
||||
// Count query
|
||||
String countQuery = "SELECT COUNT(DISTINCT m.seriesName) FROM BookEntity b JOIN b.metadata m"
|
||||
+ (inProgressOnly ? " LEFT JOIN b.userBookProgress p ON p.user.id = :userId" : "")
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ " AND m.seriesName IS NOT NULL"
|
||||
+ libraryClause
|
||||
+ searchClause;
|
||||
|
||||
if (inProgressOnly) {
|
||||
// For in-progress, we need the HAVING filter in the count — use a subquery approach
|
||||
String countWithHaving = "SELECT COUNT(*) FROM ("
|
||||
+ "SELECT m.seriesName FROM BookEntity b JOIN b.metadata m"
|
||||
+ " LEFT JOIN b.userBookProgress p ON p.user.id = :userId"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ " AND m.seriesName IS NOT NULL"
|
||||
+ libraryClause
|
||||
+ searchClause
|
||||
+ " GROUP BY m.seriesName"
|
||||
+ " HAVING SUM(CASE WHEN p.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING) THEN 1 ELSE 0 END) > 0"
|
||||
+ ")";
|
||||
// JPQL doesn't support subqueries in FROM — count via result list size instead
|
||||
String countAlt = "SELECT m.seriesName FROM BookEntity b JOIN b.metadata m"
|
||||
+ " LEFT JOIN b.userBookProgress p ON p.user.id = :userId"
|
||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ " AND m.seriesName IS NOT NULL"
|
||||
+ libraryClause
|
||||
+ searchClause
|
||||
+ " GROUP BY m.seriesName"
|
||||
+ " HAVING SUM(CASE WHEN p.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING) THEN 1 ELSE 0 END) > 0";
|
||||
var countQ = entityManager.createQuery(countAlt, String.class);
|
||||
countQ.setParameter("userId", userId);
|
||||
setLibraryParams(countQ, accessibleLibraryIds, libraryId);
|
||||
if (!searchClause.isEmpty()) {
|
||||
countQ.setParameter("searchPattern", "%" + search.trim().toLowerCase() + "%");
|
||||
}
|
||||
long totalElements = countQ.getResultList().size();
|
||||
return buildSeriesPage(aggregateResults, userId, accessibleLibraryIds, libraryId, inProgressOnly, pageNum, pageSize, totalElements);
|
||||
}
|
||||
|
||||
var countQ = entityManager.createQuery(countQuery, Long.class);
|
||||
if (inProgressOnly) {
|
||||
countQ.setParameter("userId", userId);
|
||||
}
|
||||
setLibraryParams(countQ, accessibleLibraryIds, libraryId);
|
||||
if (!searchClause.isEmpty()) {
|
||||
countQ.setParameter("searchPattern", "%" + search.trim().toLowerCase() + "%");
|
||||
}
|
||||
long totalElements = countQ.getSingleResult();
|
||||
|
||||
return buildSeriesPage(aggregateResults, userId, accessibleLibraryIds, libraryId, inProgressOnly, pageNum, pageSize, totalElements);
|
||||
}
|
||||
|
||||
private AppPageResponse<AppSeriesSummary> buildSeriesPage(
|
||||
List<Tuple> aggregateResults,
|
||||
Long userId,
|
||||
Set<Long> accessibleLibraryIds,
|
||||
Long libraryId,
|
||||
boolean inProgressOnly,
|
||||
int pageNum,
|
||||
int pageSize,
|
||||
long totalElements) {
|
||||
|
||||
if (aggregateResults.isEmpty()) {
|
||||
return AppPageResponse.of(Collections.emptyList(), pageNum, pageSize, totalElements);
|
||||
}
|
||||
|
||||
List<String> seriesNames = aggregateResults.stream()
|
||||
.map(t -> t.get(0, String.class))
|
||||
.toList();
|
||||
|
||||
// Phase 2: Fetch books for enrichment (only ToOne joins; collections loaded via @BatchSize)
|
||||
String libraryClause = buildLibraryClause(accessibleLibraryIds, libraryId);
|
||||
String booksQuery = "SELECT b FROM BookEntity b"
|
||||
+ " JOIN FETCH b.metadata m"
|
||||
+ " WHERE m.seriesName IN :seriesNames"
|
||||
+ " AND (b.deleted IS NULL OR b.deleted = false)"
|
||||
+ " AND b.bookFiles IS NOT EMPTY"
|
||||
+ libraryClause;
|
||||
|
||||
var booksQ = entityManager.createQuery(booksQuery, BookEntity.class);
|
||||
booksQ.setParameter("seriesNames", seriesNames);
|
||||
setLibraryParams(booksQ, accessibleLibraryIds, libraryId);
|
||||
|
||||
List<BookEntity> books = booksQ.getResultList();
|
||||
|
||||
// Group books by series name
|
||||
Map<String, List<BookEntity>> booksBySeries = books.stream()
|
||||
.collect(Collectors.groupingBy(b -> b.getMetadata().getSeriesName()));
|
||||
|
||||
// Build aggregates map from Phase 1
|
||||
Map<String, Tuple> aggregateMap = new LinkedHashMap<>();
|
||||
for (Tuple t : aggregateResults) {
|
||||
aggregateMap.put(t.get(0, String.class), t);
|
||||
}
|
||||
|
||||
// Merge into summaries, preserving Phase 1 order
|
||||
List<AppSeriesSummary> summaries = new ArrayList<>();
|
||||
for (String seriesName : seriesNames) {
|
||||
Tuple agg = aggregateMap.get(seriesName);
|
||||
List<BookEntity> seriesBooks = booksBySeries.getOrDefault(seriesName, Collections.emptyList());
|
||||
|
||||
// Distinct authors across all books in series
|
||||
List<String> authors = seriesBooks.stream()
|
||||
.filter(b -> b.getMetadata() != null && b.getMetadata().getAuthors() != null)
|
||||
.flatMap(b -> b.getMetadata().getAuthors().stream())
|
||||
.map(AuthorEntity::getName)
|
||||
.distinct()
|
||||
.toList();
|
||||
|
||||
// Cover books sorted by seriesNumber ASC nulls last
|
||||
List<SeriesCoverBook> coverBooks = seriesBooks.stream()
|
||||
.sorted(Comparator.comparing(
|
||||
(BookEntity b) -> b.getMetadata().getSeriesNumber(),
|
||||
Comparator.nullsLast(Comparator.naturalOrder())))
|
||||
.map(b -> {
|
||||
BookFileEntity primaryFile = b.getPrimaryBookFile();
|
||||
String fileType = (primaryFile != null && primaryFile.getBookType() != null)
|
||||
? primaryFile.getBookType().name()
|
||||
: null;
|
||||
return SeriesCoverBook.builder()
|
||||
.bookId(b.getId())
|
||||
.coverUpdatedOn(b.getMetadata().getCoverUpdatedOn())
|
||||
.seriesNumber(b.getMetadata().getSeriesNumber())
|
||||
.primaryFileType(fileType)
|
||||
.build();
|
||||
})
|
||||
.toList();
|
||||
|
||||
Long booksReadLong = agg.get(4, Long.class);
|
||||
int booksRead = booksReadLong != null ? booksReadLong.intValue() : 0;
|
||||
|
||||
summaries.add(AppSeriesSummary.builder()
|
||||
.seriesName(agg.get(0, String.class))
|
||||
.bookCount(agg.get(1, Long.class).intValue())
|
||||
.seriesTotal(agg.get(2, Integer.class))
|
||||
.latestAddedOn(agg.get(3, Instant.class))
|
||||
.booksRead(booksRead)
|
||||
.authors(authors)
|
||||
.coverBooks(coverBooks)
|
||||
.build());
|
||||
}
|
||||
|
||||
return AppPageResponse.of(summaries, pageNum, pageSize, totalElements);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AppPageResponse<AppBookSummary> getSeriesBooks(
|
||||
String seriesName,
|
||||
Integer page,
|
||||
Integer size,
|
||||
String sortBy,
|
||||
String sortDir,
|
||||
Long libraryId) {
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Long userId = user.getId();
|
||||
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
|
||||
|
||||
if (libraryId != null) {
|
||||
validateLibraryAccess(accessibleLibraryIds, libraryId);
|
||||
}
|
||||
|
||||
int pageNum = page != null && page >= 0 ? page : 0;
|
||||
int pageSize = size != null && size > 0 ? Math.min(size, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;
|
||||
|
||||
Sort sort = buildBookSort(sortBy, sortDir);
|
||||
Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
|
||||
|
||||
Specification<BookEntity> spec = buildSeriesBooksSpec(accessibleLibraryIds, libraryId, seriesName);
|
||||
|
||||
Page<BookEntity> bookPage = bookRepository.findAll(spec, pageable);
|
||||
|
||||
Set<Long> bookIds = bookPage.getContent().stream()
|
||||
.map(BookEntity::getId)
|
||||
.collect(Collectors.toSet());
|
||||
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, bookIds);
|
||||
|
||||
List<AppBookSummary> summaries = bookPage.getContent().stream()
|
||||
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
|
||||
.toList();
|
||||
|
||||
return AppPageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
|
||||
}
|
||||
|
||||
// --- Access control helpers (duplicated from AppBookService to minimize blast radius) ---
|
||||
|
||||
private Set<Long> getAccessibleLibraryIds(BookLoreUser user) {
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
return null;
|
||||
}
|
||||
if (user.getAssignedLibraries() == null || user.getAssignedLibraries().isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private void validateLibraryAccess(Set<Long> accessibleLibraryIds, Long libraryId) {
|
||||
if (accessibleLibraryIds != null && !accessibleLibraryIds.contains(libraryId)) {
|
||||
throw ApiError.FORBIDDEN.createException("Access denied to library " + libraryId);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Query helpers ---
|
||||
|
||||
private String buildLibraryClause(Set<Long> accessibleLibraryIds, Long libraryId) {
|
||||
if (libraryId != null) {
|
||||
return " AND b.library.id = :libraryId";
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
return " AND b.library.id IN :libraryIds";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private void setLibraryParams(jakarta.persistence.Query query, Set<Long> accessibleLibraryIds, Long libraryId) {
|
||||
if (libraryId != null) {
|
||||
query.setParameter("libraryId", libraryId);
|
||||
} else if (accessibleLibraryIds != null) {
|
||||
query.setParameter("libraryIds", accessibleLibraryIds);
|
||||
}
|
||||
}
|
||||
|
||||
private String buildSeriesOrderBy(String sortBy, String sortDir, boolean inProgressOnly) {
|
||||
String dir = "asc".equalsIgnoreCase(sortDir) ? "ASC" : "DESC";
|
||||
String nullsClause = "ASC".equals(dir) ? " NULLS LAST" : " NULLS FIRST";
|
||||
|
||||
return switch (sortBy != null ? sortBy.toLowerCase() : "") {
|
||||
case "name" -> "m.seriesName " + dir;
|
||||
case "bookcount" -> "COUNT(b.id) " + dir;
|
||||
case "readprogress" -> "SUM(CASE WHEN p.readStatus = org.booklore.model.enums.ReadStatus.READ THEN 1 ELSE 0 END) " + dir;
|
||||
case "lastreadtime" -> {
|
||||
if (inProgressOnly) {
|
||||
yield "MAX(p.lastReadTime) " + dir + nullsClause;
|
||||
}
|
||||
yield "MAX(b.addedOn) " + dir + nullsClause;
|
||||
}
|
||||
default -> {
|
||||
if (inProgressOnly) {
|
||||
yield "MAX(p.lastReadTime) " + dir + nullsClause;
|
||||
}
|
||||
yield "MAX(b.addedOn) " + dir + nullsClause;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private Sort buildBookSort(String sortBy, String sortDir) {
|
||||
Sort.Direction direction = "asc".equalsIgnoreCase(sortDir) ? Sort.Direction.ASC : Sort.Direction.DESC;
|
||||
String field = switch (sortBy != null ? sortBy.toLowerCase() : "") {
|
||||
case "title" -> "metadata.title";
|
||||
case "seriesnumber" -> "metadata.seriesNumber";
|
||||
case "recentlyadded" -> "addedOn";
|
||||
default -> "metadata.seriesNumber";
|
||||
};
|
||||
return Sort.by(direction, field);
|
||||
}
|
||||
|
||||
private Specification<BookEntity> buildSeriesBooksSpec(Set<Long> accessibleLibraryIds, Long libraryId, String seriesName) {
|
||||
List<Specification<BookEntity>> specs = new ArrayList<>();
|
||||
specs.add(AppBookSpecification.notDeleted());
|
||||
specs.add(AppBookSpecification.hasDigitalFile());
|
||||
specs.add(AppBookSpecification.inSeries(seriesName));
|
||||
|
||||
if (accessibleLibraryIds != null) {
|
||||
specs.add(libraryId != null
|
||||
? AppBookSpecification.inLibrary(libraryId)
|
||||
: AppBookSpecification.inLibraries(accessibleLibraryIds));
|
||||
} else if (libraryId != null) {
|
||||
specs.add(AppBookSpecification.inLibrary(libraryId));
|
||||
}
|
||||
|
||||
return AppBookSpecification.combine(specs.toArray(new Specification[0]));
|
||||
}
|
||||
|
||||
private Map<Long, UserBookProgressEntity> getProgressMap(Long userId, Set<Long> bookIds) {
|
||||
if (bookIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds).stream()
|
||||
.collect(Collectors.toMap(
|
||||
p -> p.getBook().getId(),
|
||||
Function.identity()
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,963 @@
|
||||
package org.booklore.app.specification;
|
||||
|
||||
import org.booklore.exception.APIException;
|
||||
import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.model.enums.ComicCreatorRole;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import jakarta.persistence.criteria.*;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class AppBookSpecification {
|
||||
|
||||
private AppBookSpecification() {
|
||||
}
|
||||
|
||||
private static List<Integer> parseIntList(List<String> values, String paramName) {
|
||||
List<String> invalid = new ArrayList<>();
|
||||
List<Integer> result = values.stream()
|
||||
.filter(s -> s != null && !s.isBlank())
|
||||
.map(s -> {
|
||||
try {
|
||||
return Integer.parseInt(s.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
invalid.add(s.trim());
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
if (!invalid.isEmpty()) {
|
||||
throw new APIException("Invalid " + paramName + " values: " + invalid, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static List<Long> parseLongList(List<String> values, String paramName) {
|
||||
List<String> invalid = new ArrayList<>();
|
||||
List<Long> result = values.stream()
|
||||
.filter(s -> s != null && !s.isBlank())
|
||||
.map(s -> {
|
||||
try {
|
||||
return Long.parseLong(s.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
invalid.add(s.trim());
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
if (!invalid.isEmpty()) {
|
||||
throw new APIException("Invalid " + paramName + " values: " + invalid, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <X, Y> Join<X, Y> getOrCreateJoin(From<?, X> from, String attribute, JoinType joinType) {
|
||||
for (Join<X, ?> join : from.getJoins()) {
|
||||
if (join.getAttribute().getName().equals(attribute) && join.getJoinType() == joinType) {
|
||||
return (Join<X, Y>) join;
|
||||
}
|
||||
}
|
||||
return from.join(attribute, joinType);
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> inLibraries(Collection<Long> libraryIds) {
|
||||
return (root, query, cb) -> {
|
||||
if (libraryIds == null || libraryIds.isEmpty()) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
return root.get("library").get("id").in(libraryIds);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> inLibrary(Long libraryId) {
|
||||
return (root, query, cb) -> {
|
||||
if (libraryId == null) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
return cb.equal(root.get("library").get("id"), libraryId);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> inShelf(Long shelfId) {
|
||||
return (root, query, cb) -> {
|
||||
if (shelfId == null) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
Join<BookEntity, ShelfEntity> shelvesJoin = root.join("shelves", JoinType.INNER);
|
||||
return cb.equal(shelvesJoin.get("id"), shelfId);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withReadStatus(ReadStatus status, Long userId) {
|
||||
return (root, query, cb) -> {
|
||||
if (status == null || userId == null) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
Subquery<Long> subquery = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> progressRoot = subquery.from(UserBookProgressEntity.class);
|
||||
subquery.select(progressRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(progressRoot.get("user").get("id"), userId),
|
||||
cb.equal(progressRoot.get("readStatus"), status)
|
||||
);
|
||||
return root.get("id").in(subquery);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> inProgress(Long userId) {
|
||||
return (root, query, cb) -> {
|
||||
if (userId == null) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
Subquery<Long> subquery = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> progressRoot = subquery.from(UserBookProgressEntity.class);
|
||||
subquery.select(progressRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(progressRoot.get("user").get("id"), userId),
|
||||
progressRoot.get("readStatus").in(ReadStatus.READING, ReadStatus.RE_READING)
|
||||
);
|
||||
return root.get("id").in(subquery);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> addedWithinDays(int days) {
|
||||
return (root, query, cb) -> {
|
||||
Instant cutoff = Instant.now().minus(days, ChronoUnit.DAYS);
|
||||
return cb.greaterThanOrEqualTo(root.get("addedOn"), cutoff);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> searchText(String searchQuery) {
|
||||
return (root, query, cb) -> {
|
||||
if (searchQuery == null || searchQuery.trim().isEmpty()) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
String pattern = "%" + searchQuery.toLowerCase().trim() + "%";
|
||||
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = root.join("metadata", JoinType.LEFT);
|
||||
|
||||
// Use EXISTS subquery for author search to avoid DISTINCT and cartesian products
|
||||
Subquery<Long> authorSubquery = query.subquery(Long.class);
|
||||
Root<BookMetadataEntity> metaRoot = authorSubquery.from(BookMetadataEntity.class);
|
||||
Join<BookMetadataEntity, AuthorEntity> authorJoin = metaRoot.join("authors", JoinType.INNER);
|
||||
authorSubquery.select(cb.literal(1L))
|
||||
.where(
|
||||
cb.equal(metaRoot.get("id"), root.get("id")),
|
||||
cb.like(cb.lower(authorJoin.get("name")), pattern)
|
||||
);
|
||||
|
||||
return cb.or(
|
||||
cb.like(cb.lower(metadataJoin.get("title")), pattern),
|
||||
cb.like(cb.lower(metadataJoin.get("seriesName")), pattern),
|
||||
cb.exists(authorSubquery)
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> notDeleted() {
|
||||
return (root, query, cb) -> cb.or(
|
||||
cb.isNull(root.get("deleted")),
|
||||
cb.equal(root.get("deleted"), false)
|
||||
);
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> hasScannedOn() {
|
||||
return (root, query, cb) -> cb.isNotNull(root.get("scannedOn"));
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> hasDigitalFile() {
|
||||
return (root, query, cb) -> cb.isNotEmpty(root.get("bookFiles"));
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> hasAudiobookFile() {
|
||||
return (root, query, cb) -> {
|
||||
Subquery<Long> subquery = query.subquery(Long.class);
|
||||
Root<BookFileEntity> bookFileRoot = subquery.from(BookFileEntity.class);
|
||||
subquery.select(bookFileRoot.get("book").get("id"))
|
||||
.where(cb.equal(bookFileRoot.get("bookType"), BookFileType.AUDIOBOOK));
|
||||
return root.get("id").in(subquery);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> hasNonAudiobookFile() {
|
||||
return (root, query, cb) -> {
|
||||
Subquery<Long> subquery = query.subquery(Long.class);
|
||||
Root<BookFileEntity> bookFileRoot = subquery.from(BookFileEntity.class);
|
||||
subquery.select(bookFileRoot.get("book").get("id"))
|
||||
.where(cb.notEqual(bookFileRoot.get("bookType"), BookFileType.AUDIOBOOK));
|
||||
return root.get("id").in(subquery);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books that have at least one file of the given type.
|
||||
*/
|
||||
public static Specification<BookEntity> withFileType(BookFileType fileType) {
|
||||
return (root, query, cb) -> {
|
||||
if (fileType == null) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
Subquery<Long> subquery = query.subquery(Long.class);
|
||||
Root<BookFileEntity> bookFileRoot = subquery.from(BookFileEntity.class);
|
||||
subquery.select(bookFileRoot.get("book").get("id"))
|
||||
.where(cb.equal(bookFileRoot.get("bookType"), fileType));
|
||||
return root.get("id").in(subquery);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by multiple file types with mode support.
|
||||
* OR = books with at least one file of ANY listed type
|
||||
* AND = books with files of ALL listed types
|
||||
* NOT = books with NONE of the listed file types
|
||||
*/
|
||||
public static Specification<BookEntity> withFileTypes(List<String> fileTypes, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> unknown = new ArrayList<>();
|
||||
List<BookFileType> parsed = fileTypes.stream()
|
||||
.filter(s -> s != null && !s.isBlank())
|
||||
.map(s -> {
|
||||
String trimmed = s.trim().toUpperCase();
|
||||
try {
|
||||
return BookFileType.valueOf(trimmed);
|
||||
} catch (IllegalArgumentException e) {
|
||||
unknown.add(s.trim());
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
if (!unknown.isEmpty()) {
|
||||
throw new APIException("Invalid fileType values: " + unknown + ". Valid values: " + List.of(BookFileType.values()), HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
if (parsed.isEmpty()) return cb.conjunction();
|
||||
|
||||
if ("and".equals(mode)) {
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (BookFileType ft : parsed) {
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookFileEntity> bfRoot = sub.from(BookFileEntity.class);
|
||||
sub.select(bfRoot.get("book").get("id"))
|
||||
.where(cb.equal(bfRoot.get("bookType"), ft));
|
||||
predicates.add(root.get("id").in(sub));
|
||||
}
|
||||
return cb.and(predicates.toArray(new Predicate[0]));
|
||||
}
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookFileEntity> bfRoot = sub.from(BookFileEntity.class);
|
||||
sub.select(bfRoot.get("book").get("id"))
|
||||
.where(bfRoot.get("bookType").in(parsed));
|
||||
|
||||
if ("not".equals(mode)) {
|
||||
return cb.not(root.get("id").in(sub));
|
||||
}
|
||||
return root.get("id").in(sub);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by multiple read statuses with mode support (per-user).
|
||||
* OR = books with ANY of the listed read statuses
|
||||
* AND = impossible for a single-value field, treated as OR
|
||||
* NOT = books with NONE of the listed read statuses
|
||||
*/
|
||||
public static Specification<BookEntity> withReadStatuses(List<String> statuses, Long userId, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (userId == null) return cb.conjunction();
|
||||
List<String> unknown = new ArrayList<>();
|
||||
List<ReadStatus> parsed = statuses.stream()
|
||||
.filter(s -> s != null && !s.isBlank())
|
||||
.map(s -> {
|
||||
String trimmed = s.trim().toUpperCase();
|
||||
try {
|
||||
return ReadStatus.valueOf(trimmed);
|
||||
} catch (IllegalArgumentException e) {
|
||||
unknown.add(s.trim());
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
if (!unknown.isEmpty()) {
|
||||
throw new APIException("Invalid status values: " + unknown + ". Valid values: " + List.of(ReadStatus.values()), HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
if (parsed.isEmpty()) return cb.conjunction();
|
||||
|
||||
boolean hasUnset = parsed.contains(ReadStatus.UNSET);
|
||||
List<ReadStatus> realStatuses = parsed.stream().filter(s -> s != ReadStatus.UNSET).toList();
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> progressRoot = sub.from(UserBookProgressEntity.class);
|
||||
sub.select(progressRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(progressRoot.get("user").get("id"), userId),
|
||||
realStatuses.isEmpty() ? cb.disjunction() : progressRoot.get("readStatus").in(realStatuses)
|
||||
);
|
||||
|
||||
Predicate isReal = root.get("id").in(sub);
|
||||
|
||||
// UNSET means either no progress entry OR entry with UNSET status
|
||||
Subquery<Long> anyEntrySub = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> anyEntryRoot = anyEntrySub.from(UserBookProgressEntity.class);
|
||||
anyEntrySub.select(anyEntryRoot.get("book").get("id"))
|
||||
.where(cb.equal(anyEntryRoot.get("user").get("id"), userId));
|
||||
|
||||
Predicate noEntry = cb.not(root.get("id").in(anyEntrySub));
|
||||
|
||||
Subquery<Long> unsetEntrySub = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> unsetEntryRoot = unsetEntrySub.from(UserBookProgressEntity.class);
|
||||
unsetEntrySub.select(unsetEntryRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(unsetEntryRoot.get("user").get("id"), userId),
|
||||
cb.equal(unsetEntryRoot.get("readStatus"), ReadStatus.UNSET)
|
||||
);
|
||||
Predicate hasUnsetEntry = root.get("id").in(unsetEntrySub);
|
||||
|
||||
Predicate isUnset = cb.or(noEntry, hasUnsetEntry);
|
||||
|
||||
Predicate combined;
|
||||
if (hasUnset && !realStatuses.isEmpty()) {
|
||||
combined = cb.or(isReal, isUnset);
|
||||
} else if (hasUnset) {
|
||||
combined = isUnset;
|
||||
} else {
|
||||
combined = isReal;
|
||||
}
|
||||
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books where the user's personal rating is >= minRating.
|
||||
*/
|
||||
public static Specification<BookEntity> withMinRating(int minRating, Long userId) {
|
||||
return (root, query, cb) -> {
|
||||
Subquery<Long> subquery = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> progressRoot = subquery.from(UserBookProgressEntity.class);
|
||||
subquery.select(progressRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(progressRoot.get("user").get("id"), userId),
|
||||
cb.greaterThanOrEqualTo(progressRoot.get("personalRating"), minRating)
|
||||
);
|
||||
return root.get("id").in(subquery);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books where the user's personal rating is <= maxRating.
|
||||
* Use maxRating=0 to find unrated books.
|
||||
*/
|
||||
public static Specification<BookEntity> withMaxRating(int maxRating, Long userId) {
|
||||
return (root, query, cb) -> {
|
||||
Subquery<Long> subquery = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> progressRoot = subquery.from(UserBookProgressEntity.class);
|
||||
|
||||
if (maxRating == 0) {
|
||||
// Unrated: books with no progress entry or null personalRating
|
||||
Subquery<Long> ratedSubquery = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> ratedRoot = ratedSubquery.from(UserBookProgressEntity.class);
|
||||
ratedSubquery.select(ratedRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(ratedRoot.get("user").get("id"), userId),
|
||||
cb.isNotNull(ratedRoot.get("personalRating"))
|
||||
);
|
||||
return cb.not(root.get("id").in(ratedSubquery));
|
||||
}
|
||||
|
||||
subquery.select(progressRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(progressRoot.get("user").get("id"), userId),
|
||||
cb.lessThanOrEqualTo(progressRoot.get("personalRating"), maxRating)
|
||||
);
|
||||
return root.get("id").in(subquery);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by author name (case-insensitive exact match).
|
||||
*/
|
||||
public static Specification<BookEntity> withAuthor(String authorName) {
|
||||
return withAuthors(authorName == null ? List.of() : List.of(authorName), "or");
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by multiple author names with mode support.
|
||||
* OR = books with ANY of the authors
|
||||
* AND = books with ALL of the authors
|
||||
* NOT = books with NONE of the authors
|
||||
*/
|
||||
public static Specification<BookEntity> withAuthors(List<String> authorNames, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(authorNames);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
|
||||
return buildManyToManySpec(root, query, cb, cleaned, mode,
|
||||
"metadata", "authors", "name");
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by language code (case-insensitive).
|
||||
*/
|
||||
public static Specification<BookEntity> withLanguage(String language) {
|
||||
return withLanguages(language == null ? List.of() : List.of(language), "or");
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by multiple language codes with mode support.
|
||||
*/
|
||||
public static Specification<BookEntity> withLanguages(List<String> languages, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(languages);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
|
||||
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "language");
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> inSeries(String seriesName) {
|
||||
return inSeriesMulti(seriesName == null ? List.of() : List.of(seriesName), "or");
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by multiple series names with mode support.
|
||||
*/
|
||||
public static Specification<BookEntity> inSeriesMulti(List<String> seriesNames, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(seriesNames);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
|
||||
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "seriesName");
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withCategory(String categoryName) {
|
||||
return withCategories(categoryName == null ? List.of() : List.of(categoryName), "or");
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by multiple categories with mode support.
|
||||
*/
|
||||
public static Specification<BookEntity> withCategories(List<String> categoryNames, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(categoryNames);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
|
||||
return buildManyToManySpec(root, query, cb, cleaned, mode,
|
||||
"metadata", "categories", "name");
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withPublisher(String publisher) {
|
||||
return withPublishers(publisher == null ? List.of() : List.of(publisher), "or");
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by multiple publishers with mode support.
|
||||
*/
|
||||
public static Specification<BookEntity> withPublishers(List<String> publishers, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(publishers);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
|
||||
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "publisher");
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withTag(String tagName) {
|
||||
return withTags(tagName == null ? List.of() : List.of(tagName), "or");
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by multiple tags with mode support.
|
||||
*/
|
||||
public static Specification<BookEntity> withTags(List<String> tagNames, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(tagNames);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
|
||||
return buildManyToManySpec(root, query, cb, cleaned, mode,
|
||||
"metadata", "tags", "name");
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withMood(String moodName) {
|
||||
return withMoods(moodName == null ? List.of() : List.of(moodName), "or");
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by multiple moods with mode support.
|
||||
*/
|
||||
public static Specification<BookEntity> withMoods(List<String> moodNames, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(moodNames);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
|
||||
return buildManyToManySpec(root, query, cb, cleaned, mode,
|
||||
"metadata", "moods", "name");
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withNarrator(String narrator) {
|
||||
return withNarrators(narrator == null ? List.of() : List.of(narrator), "or");
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter books by multiple narrators with mode support.
|
||||
*/
|
||||
public static Specification<BookEntity> withNarrators(List<String> narrators, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(narrators);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
|
||||
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "narrator");
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> unshelved() {
|
||||
return (root, query, cb) -> {
|
||||
Subquery<Long> subquery = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = subquery.correlate(root);
|
||||
Join<BookEntity, ShelfEntity> shelvesJoin = subRoot.join("shelves", JoinType.INNER);
|
||||
subquery.select(cb.literal(1L));
|
||||
return cb.not(cb.exists(subquery));
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withAgeRatings(List<String> rangeIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<Integer> ids = parseIntList(rangeIds, "ageRating");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
|
||||
Expression<Integer> ageRating = metadataJoin.get("ageRating");
|
||||
|
||||
// Age rating ranges from frontend config (mirrored here for performance)
|
||||
// 0: [0, 6), 6: [6, 10), 10: [10, 13), 13: [13, 16), 16: [16, 18), 18: [18, 21), 21: [21, inf)
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Integer id : ids) {
|
||||
predicates.add(switch (id) {
|
||||
case 0 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 0), cb.lessThan(ageRating, 6));
|
||||
case 6 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 6), cb.lessThan(ageRating, 10));
|
||||
case 10 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 10), cb.lessThan(ageRating, 13));
|
||||
case 13 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 13), cb.lessThan(ageRating, 16));
|
||||
case 16 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 16), cb.lessThan(ageRating, 18));
|
||||
case 18 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 18), cb.lessThan(ageRating, 21));
|
||||
case 21 -> cb.greaterThanOrEqualTo(ageRating, 21);
|
||||
default -> throw new APIException("Invalid ageRating bucket ID: " + id, HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
}
|
||||
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withContentRatings(List<String> values, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(values);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "contentRating");
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withMatchScores(List<String> rangeIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<Integer> ids = parseIntList(rangeIds, "matchScore");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
Expression<Float> score = root.get("metadataMatchScore");
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Integer id : ids) {
|
||||
predicates.add(switch (id) {
|
||||
case 0 -> cb.greaterThanOrEqualTo(score, 0.95f);
|
||||
case 1 -> cb.and(cb.greaterThanOrEqualTo(score, 0.90f), cb.lessThan(score, 0.95f));
|
||||
case 2 -> cb.and(cb.greaterThanOrEqualTo(score, 0.80f), cb.lessThan(score, 0.90f));
|
||||
case 3 -> cb.and(cb.greaterThanOrEqualTo(score, 0.70f), cb.lessThan(score, 0.80f));
|
||||
case 4 -> cb.and(cb.greaterThanOrEqualTo(score, 0.50f), cb.lessThan(score, 0.70f));
|
||||
case 5 -> cb.and(cb.greaterThanOrEqualTo(score, 0.30f), cb.lessThan(score, 0.50f));
|
||||
case 6 -> cb.and(cb.greaterThanOrEqualTo(score, 0.00f), cb.lessThan(score, 0.30f));
|
||||
default -> throw new APIException("Invalid matchScore bucket ID: " + id, HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
}
|
||||
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withPublishedYears(List<String> years, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (years.isEmpty()) return cb.conjunction();
|
||||
List<Integer> parsedYears = parseIntList(years, "publishedDate");
|
||||
if (parsedYears.isEmpty()) return cb.conjunction();
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
|
||||
Expression<Integer> yearExpr = cb.function("YEAR", Integer.class, metadataJoin.get("publishedDate"));
|
||||
Predicate combined = yearExpr.in(parsedYears);
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withFileSizes(List<String> rangeIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<Integer> ids = parseIntList(rangeIds, "fileSize");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = sub.correlate(root);
|
||||
Join<BookEntity, BookFileEntity> bfJoin = subRoot.join("bookFiles", JoinType.INNER);
|
||||
|
||||
Subquery<Long> minIdSub = query.subquery(Long.class);
|
||||
Root<BookEntity> minIdRoot = minIdSub.correlate(root);
|
||||
Join<BookEntity, BookFileEntity> minIdJoin = minIdRoot.join("bookFiles", JoinType.INNER);
|
||||
minIdSub.select(cb.min(minIdJoin.get("id")))
|
||||
.where(cb.equal(minIdJoin.get("isBookFormat"), true));
|
||||
|
||||
Expression<Long> size = bfJoin.get("fileSizeKb");
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Integer id : ids) {
|
||||
predicates.add(switch (id) {
|
||||
case 0 -> cb.and(cb.greaterThanOrEqualTo(size, 0L), cb.lessThan(size, 1024L));
|
||||
case 1 -> cb.and(cb.greaterThanOrEqualTo(size, 1024L), cb.lessThan(size, 10240L));
|
||||
case 2 -> cb.and(cb.greaterThanOrEqualTo(size, 10240L), cb.lessThan(size, 51200L));
|
||||
case 3 -> cb.and(cb.greaterThanOrEqualTo(size, 51200L), cb.lessThan(size, 102400L));
|
||||
case 4 -> cb.and(cb.greaterThanOrEqualTo(size, 102400L), cb.lessThan(size, 512000L));
|
||||
case 5 -> cb.and(cb.greaterThanOrEqualTo(size, 512000L), cb.lessThan(size, 1048576L));
|
||||
case 6 -> cb.and(cb.greaterThanOrEqualTo(size, 1048576L), cb.lessThan(size, 2097152L));
|
||||
case 7 -> cb.greaterThanOrEqualTo(size, 2097152L);
|
||||
default -> throw new APIException("Invalid fileSize bucket ID: " + id, HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
}
|
||||
|
||||
sub.select(cb.literal(1L))
|
||||
.where(cb.equal(bfJoin.get("id"), minIdSub),
|
||||
cb.or(predicates.toArray(new Predicate[0])));
|
||||
|
||||
return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withPersonalRatings(List<String> values, Long userId, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (userId == null || values.isEmpty()) return cb.conjunction();
|
||||
List<Integer> parsed = parseIntList(values, "personalRating");
|
||||
if (parsed.isEmpty()) return cb.conjunction();
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<UserBookProgressEntity> progressRoot = sub.from(UserBookProgressEntity.class);
|
||||
sub.select(progressRoot.get("book").get("id"))
|
||||
.where(
|
||||
cb.equal(progressRoot.get("user").get("id"), userId),
|
||||
progressRoot.get("personalRating").in(parsed)
|
||||
);
|
||||
return "not".equals(mode) ? cb.not(root.get("id").in(sub)) : root.get("id").in(sub);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withAmazonRatings(List<String> rangeIds, String mode) {
|
||||
return buildRatingRangeSpec(rangeIds, mode, "amazonRating");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withGoodreadsRatings(List<String> rangeIds, String mode) {
|
||||
return buildRatingRangeSpec(rangeIds, mode, "goodreadsRating");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withHardcoverRatings(List<String> rangeIds, String mode) {
|
||||
return buildRatingRangeSpec(rangeIds, mode, "hardcoverRating");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withLubimyczytacRatings(List<String> rangeIds, String mode) {
|
||||
return buildRatingRangeSpec(rangeIds, mode, "lubimyczytacRating");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withRanobedbRatings(List<String> rangeIds, String mode) {
|
||||
return buildRatingRangeSpec(rangeIds, mode, "ranobedbRating");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withAudibleRatings(List<String> rangeIds, String mode) {
|
||||
return buildRatingRangeSpec(rangeIds, mode, "audibleRating");
|
||||
}
|
||||
|
||||
private static Specification<BookEntity> buildRatingRangeSpec(
|
||||
List<String> rangeIds, String mode, String fieldName) {
|
||||
return (root, query, cb) -> {
|
||||
List<Integer> ids = parseIntList(rangeIds, fieldName);
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
|
||||
Expression<Double> rating = metadataJoin.get(fieldName);
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Integer id : ids) {
|
||||
predicates.add(switch (id) {
|
||||
case 5 -> cb.greaterThanOrEqualTo(rating, 4.5);
|
||||
case 4 -> cb.and(cb.greaterThanOrEqualTo(rating, 4.0), cb.lessThan(rating, 4.5));
|
||||
case 3 -> cb.and(cb.greaterThanOrEqualTo(rating, 3.0), cb.lessThan(rating, 4.0));
|
||||
case 2 -> cb.and(cb.greaterThanOrEqualTo(rating, 2.0), cb.lessThan(rating, 3.0));
|
||||
case 1 -> cb.and(cb.greaterThanOrEqualTo(rating, 1.0), cb.lessThan(rating, 2.0));
|
||||
case 0 -> cb.lessThan(rating, 1.0);
|
||||
default -> throw new APIException("Invalid " + fieldName + " bucket ID: " + id, HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
}
|
||||
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withPageCounts(List<String> rangeIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<Integer> ids = parseIntList(rangeIds, "pageCount");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
|
||||
Expression<Integer> count = metadataJoin.get("pageCount");
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Integer id : ids) {
|
||||
predicates.add(switch (id) {
|
||||
case 0 -> cb.lessThan(count, 50);
|
||||
case 1 -> cb.and(cb.greaterThanOrEqualTo(count, 50), cb.lessThan(count, 100));
|
||||
case 2 -> cb.and(cb.greaterThanOrEqualTo(count, 100), cb.lessThan(count, 200));
|
||||
case 3 -> cb.and(cb.greaterThanOrEqualTo(count, 200), cb.lessThan(count, 400));
|
||||
case 4 -> cb.and(cb.greaterThanOrEqualTo(count, 400), cb.lessThan(count, 600));
|
||||
case 5 -> cb.and(cb.greaterThanOrEqualTo(count, 600), cb.lessThan(count, 1000));
|
||||
case 6 -> cb.greaterThanOrEqualTo(count, 1000);
|
||||
default -> throw new APIException("Invalid pageCount bucket ID: " + id, HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
}
|
||||
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withShelfStatus(List<String> values, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(values);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
List<String> invalid = cleaned.stream()
|
||||
.filter(v -> !v.equals("shelved") && !v.equals("unshelved"))
|
||||
.toList();
|
||||
if (!invalid.isEmpty()) {
|
||||
throw new APIException("Invalid shelfStatus values: " + invalid
|
||||
+ ". Valid values: [shelved, unshelved]", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
boolean wantShelved = cleaned.contains("shelved");
|
||||
boolean wantUnshelved = cleaned.contains("unshelved");
|
||||
if (wantShelved && wantUnshelved) return cb.conjunction();
|
||||
Predicate hasShelves = cb.isNotEmpty(root.get("shelves"));
|
||||
Predicate combined = wantShelved ? hasShelves : cb.not(hasShelves);
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withComicCharacters(List<String> values, String mode) {
|
||||
return buildComicCollectionSpec(values, mode, "characters");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withComicTeams(List<String> values, String mode) {
|
||||
return buildComicCollectionSpec(values, mode, "teams");
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withComicLocations(List<String> values, String mode) {
|
||||
return buildComicCollectionSpec(values, mode, "locations");
|
||||
}
|
||||
|
||||
private static Specification<BookEntity> buildComicCollectionSpec(
|
||||
List<String> values, String mode, String collectionAttr) {
|
||||
return (root, query, cb) -> {
|
||||
List<String> cleaned = cleanLowerCase(values);
|
||||
if (cleaned.isEmpty()) return cb.conjunction();
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookMetadataEntity> metaRoot = sub.from(BookMetadataEntity.class);
|
||||
Join<?, ?> comicJoin = metaRoot.join("comicMetadata", JoinType.INNER);
|
||||
Join<?, ?> collJoin = comicJoin.join(collectionAttr, JoinType.INNER);
|
||||
sub.select(cb.literal(1L))
|
||||
.where(
|
||||
cb.equal(metaRoot.get("id"), root.get("id")),
|
||||
cb.lower(collJoin.get("name")).in(cleaned)
|
||||
);
|
||||
return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> inShelves(List<String> shelfIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (shelfIds.isEmpty()) return cb.conjunction();
|
||||
List<Long> ids = parseLongList(shelfIds, "shelf");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
|
||||
if ("and".equals(mode)) {
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (Long id : ids) {
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = sub.correlate(root);
|
||||
Join<BookEntity, ShelfEntity> subShelves = subRoot.join("shelves", JoinType.INNER);
|
||||
sub.select(cb.literal(1L)).where(cb.equal(subShelves.get("id"), id));
|
||||
predicates.add(cb.exists(sub));
|
||||
}
|
||||
return cb.and(predicates.toArray(new Predicate[0]));
|
||||
}
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = sub.correlate(root);
|
||||
Join<BookEntity, ShelfEntity> subShelves = subRoot.join("shelves", JoinType.INNER);
|
||||
sub.select(cb.literal(1L)).where(subShelves.get("id").in(ids));
|
||||
return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub);
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> inLibraries(List<String> libraryIds, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (libraryIds.isEmpty()) return cb.conjunction();
|
||||
List<Long> ids = parseLongList(libraryIds, "library");
|
||||
if (ids.isEmpty()) return cb.conjunction();
|
||||
|
||||
if ("and".equals(mode)) {
|
||||
if (ids.size() > 1) return cb.disjunction(); // A book can't be in multiple libraries
|
||||
return cb.equal(root.get("library").get("id"), ids.getFirst());
|
||||
}
|
||||
|
||||
Predicate combined = root.get("library").get("id").in(ids);
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
public static Specification<BookEntity> withComicCreators(List<String> values, String mode) {
|
||||
return (root, query, cb) -> {
|
||||
if (values == null || values.isEmpty()) return cb.conjunction();
|
||||
|
||||
// value is formatted as "name:role" from frontend
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (String val : values) {
|
||||
String[] parts = val.split(":");
|
||||
String name = parts[0].trim().toLowerCase();
|
||||
String roleName = parts.length > 1 ? parts[1].trim() : null;
|
||||
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<ComicCreatorMappingEntity> mappingRoot = sub.from(ComicCreatorMappingEntity.class);
|
||||
Join<?, ?> creatorJoin = mappingRoot.join("creator", JoinType.INNER);
|
||||
Join<?, ?> comicJoin = mappingRoot.join("comicMetadata", JoinType.INNER);
|
||||
|
||||
List<Predicate> where = new ArrayList<>();
|
||||
where.add(cb.equal(comicJoin.get("bookId"), root.get("id")));
|
||||
where.add(cb.equal(cb.lower(creatorJoin.get("name")), name));
|
||||
|
||||
if (roleName != null) {
|
||||
ComicCreatorRole role = parseCreatorRole(roleName);
|
||||
where.add(cb.equal(mappingRoot.get("role"), role));
|
||||
}
|
||||
|
||||
sub.select(cb.literal(1L)).where(where.toArray(new Predicate[0]));
|
||||
predicates.add(cb.exists(sub));
|
||||
}
|
||||
|
||||
Predicate combined = "and".equals(mode)
|
||||
? cb.and(predicates.toArray(new Predicate[0]))
|
||||
: cb.or(predicates.toArray(new Predicate[0]));
|
||||
return "not".equals(mode) ? cb.not(combined) : combined;
|
||||
};
|
||||
}
|
||||
|
||||
private static ComicCreatorRole parseCreatorRole(String roleName) {
|
||||
return switch (roleName.toLowerCase()) {
|
||||
case "penciller" -> ComicCreatorRole.PENCILLER;
|
||||
case "inker" -> ComicCreatorRole.INKER;
|
||||
case "colorist" -> ComicCreatorRole.COLORIST;
|
||||
case "letterer" -> ComicCreatorRole.LETTERER;
|
||||
case "coverartist" -> ComicCreatorRole.COVER_ARTIST;
|
||||
case "editor" -> ComicCreatorRole.EDITOR;
|
||||
default -> throw new APIException("Invalid comic creator role: " + roleName, HttpStatus.BAD_REQUEST);
|
||||
};
|
||||
}
|
||||
|
||||
private static List<String> cleanLowerCase(List<String> values) {
|
||||
if (values == null) return List.of();
|
||||
return values.stream()
|
||||
.filter(s -> s != null && !s.isBlank())
|
||||
.map(s -> s.trim().toLowerCase())
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a specification for a scalar field on BookMetadataEntity (language, seriesName, publisher, narrator).
|
||||
* OR = metadata field IN (values)
|
||||
* AND = impossible for scalar fields with multiple values (treated as OR since a scalar can only be one value)
|
||||
* NOT = metadata field NOT IN (values)
|
||||
*/
|
||||
private static Predicate buildMetadataFieldSpec(
|
||||
Root<BookEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
|
||||
List<String> values, String mode, String fieldName) {
|
||||
|
||||
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
|
||||
Expression<String> fieldExpr = cb.lower(metadataJoin.get(fieldName));
|
||||
|
||||
if ("not".equals(mode)) {
|
||||
return fieldExpr.in(values).not();
|
||||
}
|
||||
// Both "or" and "and" use IN for scalar fields (a single field can only match one value)
|
||||
return fieldExpr.in(values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a specification for a many-to-many collection (authors, categories, tags, moods).
|
||||
* Uses EXISTS subqueries to avoid DISTINCT and cartesian product issues.
|
||||
*
|
||||
* OR = book has at least one related entity whose name is IN (values)
|
||||
* AND = book has ALL of the named entities (one EXISTS per value)
|
||||
* NOT = book has NONE of the named entities
|
||||
*/
|
||||
private static Predicate buildManyToManySpec(
|
||||
Root<BookEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb,
|
||||
List<String> values, String mode,
|
||||
String metadataAttr, String collectionAttr, String nameAttr) {
|
||||
|
||||
if ("and".equals(mode)) {
|
||||
// AND: book must have ALL values one EXISTS subquery per value
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (String value : values) {
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookMetadataEntity> metaRoot = sub.from(BookMetadataEntity.class);
|
||||
Join<?, ?> collJoin = metaRoot.join(collectionAttr, JoinType.INNER);
|
||||
sub.select(cb.literal(1L))
|
||||
.where(
|
||||
cb.equal(metaRoot.get("id"), root.get("id")),
|
||||
cb.equal(cb.lower(collJoin.get(nameAttr)), value)
|
||||
);
|
||||
predicates.add(cb.exists(sub));
|
||||
}
|
||||
return cb.and(predicates.toArray(new Predicate[0]));
|
||||
}
|
||||
|
||||
// OR or NOT: single EXISTS subquery with IN clause
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookMetadataEntity> metaRoot = sub.from(BookMetadataEntity.class);
|
||||
Join<?, ?> collJoin = metaRoot.join(collectionAttr, JoinType.INNER);
|
||||
sub.select(cb.literal(1L))
|
||||
.where(
|
||||
cb.equal(metaRoot.get("id"), root.get("id")),
|
||||
cb.lower(collJoin.get(nameAttr)).in(values)
|
||||
);
|
||||
|
||||
if ("not".equals(mode)) {
|
||||
return cb.not(cb.exists(sub));
|
||||
}
|
||||
return cb.exists(sub);
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public static Specification<BookEntity> combine(Specification<BookEntity>... specs) {
|
||||
Specification<BookEntity> result = (root, query, cb) -> cb.conjunction();
|
||||
for (Specification<BookEntity> spec : specs) {
|
||||
if (spec != null) {
|
||||
result = result.and(spec);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "app")
|
||||
@Getter
|
||||
@Setter
|
||||
public class AppProperties {
|
||||
private String pathConfig;
|
||||
private String bookdropFolder;
|
||||
private String version;
|
||||
private RemoteAuth remoteAuth;
|
||||
private Boolean forceDisableOidc = false;
|
||||
|
||||
/**
|
||||
* Type of disk storage where library files are stored.
|
||||
* Defaults to LOCAL. Set to NETWORK if using NFS, SMB/CIFS, or other network-mounted storage.
|
||||
* Some features like file move/reorganization are disabled on network storage due to
|
||||
* unreliable atomic operations that can cause data corruption or loss.
|
||||
*/
|
||||
private String diskType = "LOCAL";
|
||||
|
||||
public boolean isLocalStorage() {
|
||||
return "LOCAL".equalsIgnoreCase(diskType);
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class RemoteAuth {
|
||||
private boolean enabled;
|
||||
private boolean createNewUsers;
|
||||
private String headerName;
|
||||
private String headerUser;
|
||||
private String headerEmail;
|
||||
private String headerGroups;
|
||||
private String adminGroup;
|
||||
private String groupsDelimiter = "\\s+"; // Default to whitespace for backward compatibility
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.booklore.model.enums.AuthorMetadataSource;
|
||||
import org.booklore.service.metadata.parser.AudnexusAuthorParser;
|
||||
import org.booklore.service.metadata.parser.AuthorParser;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
public class AuthorParserConfig {
|
||||
|
||||
@Bean
|
||||
public Map<AuthorMetadataSource, AuthorParser> authorParserMap(AudnexusAuthorParser audnexusAuthorParser) {
|
||||
return Map.of(
|
||||
AuthorMetadataSource.AUDNEXUS, audnexusAuthorParser
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.booklore.model.enums.MetadataProvider;
|
||||
import org.booklore.service.metadata.parser.*;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
public class BookParserConfig {
|
||||
|
||||
@Bean
|
||||
public Map<MetadataProvider, BookParser> parserMap(GoogleParser googleParser, AmazonBookParser amazonBookParser,
|
||||
GoodReadsParser goodReadsParser, HardcoverParser hardcoverParser, ComicvineBookParser comicvineBookParser, DoubanBookParser doubanBookParser, RanobeDbParser ranobedbParser, LubimyCzytacParser lubimyczytacParser, AudibleParser audibleParser) {
|
||||
return Map.of(
|
||||
MetadataProvider.Amazon, amazonBookParser,
|
||||
MetadataProvider.GoodReads, goodReadsParser,
|
||||
MetadataProvider.Google, googleParser,
|
||||
MetadataProvider.Hardcover, hardcoverParser,
|
||||
MetadataProvider.Comicvine, comicvineBookParser,
|
||||
MetadataProvider.Douban, doubanBookParser,
|
||||
MetadataProvider.Lubimyczytac, lubimyczytacParser,
|
||||
MetadataProvider.Ranobedb, ranobedbParser,
|
||||
MetadataProvider.Audible, audibleParser
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "bookmarks")
|
||||
@Data
|
||||
public class BookmarkProperties {
|
||||
private int defaultPriority = 3;
|
||||
private int minPriority = 1;
|
||||
private int maxPriority = 5;
|
||||
private int maxNotesLength = 2000;
|
||||
private int maxTitleLength = 255;
|
||||
private int maxCfiLength = 500;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.caffeine.CaffeineCacheManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
public class CacheConfig {
|
||||
|
||||
@Bean
|
||||
public CacheManager cacheManager() {
|
||||
CaffeineCacheManager cacheManager = new CaffeineCacheManager("publicSettings", "appSettings");
|
||||
cacheManager.setCaffeine(Caffeine.newBuilder()
|
||||
.expireAfterWrite(Duration.ofHours(24))
|
||||
.maximumSize(100));
|
||||
return cacheManager;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.flywaydb.core.api.exception.FlywayValidateException;
|
||||
import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class FlywayConfig {
|
||||
|
||||
@Bean
|
||||
FlywayMigrationStrategy flywayMigrationStrategy() {
|
||||
return flyway -> {
|
||||
try {
|
||||
flyway.migrate();
|
||||
} catch (FlywayValidateException e) {
|
||||
flyway.repair();
|
||||
flyway.migrate();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.net.http.HttpClient;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@Configuration
|
||||
public class HttpClientConfig {
|
||||
|
||||
@Bean
|
||||
public HttpClient httpClient() {
|
||||
return HttpClient.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.executor(Executors.newVirtualThreadPerTaskExecutor())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ExecutorService regexExecutor() {
|
||||
return Executors.newVirtualThreadPerTaskExecutor();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.databind.ser.BeanPropertyWriter;
|
||||
import tools.jackson.databind.ser.ValueSerializerModifier;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Jackson configuration for Komga API clean mode.
|
||||
*/
|
||||
@Configuration
|
||||
public class JacksonConfig {
|
||||
|
||||
public static final String KOMGA_CLEAN_OBJECT_MAPPER = "komgaCleanObjectMapper";
|
||||
|
||||
@Bean(name = KOMGA_CLEAN_OBJECT_MAPPER)
|
||||
public ObjectMapper komgaCleanObjectMapper() {
|
||||
return JsonMapper.builder()
|
||||
.findAndAddModules()
|
||||
.serializerFactory(
|
||||
tools.jackson.databind.ser.BeanSerializerFactory.instance
|
||||
.withSerializerModifier(new ValueSerializerModifier() {
|
||||
@Override
|
||||
public List<BeanPropertyWriter> changeProperties(
|
||||
tools.jackson.databind.SerializationConfig config,
|
||||
tools.jackson.databind.BeanDescription.Supplier beanDescSupplier,
|
||||
List<BeanPropertyWriter> beanProperties) {
|
||||
|
||||
return beanProperties.stream()
|
||||
.map(KomgaCleanBeanPropertyWriter::new)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
})
|
||||
)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.booklore.context.KomgaCleanContext;
|
||||
import tools.jackson.core.JsonGenerator;
|
||||
import tools.jackson.databind.SerializationContext;
|
||||
import tools.jackson.databind.ser.BeanPropertyWriter;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* Custom BeanPropertyWriter that handles clean mode filtering.
|
||||
* When clean mode is enabled:
|
||||
* - Fields ending with "Lock" are excluded
|
||||
* - Null values are excluded
|
||||
* - Empty arrays/collections are excluded
|
||||
*/
|
||||
public class KomgaCleanBeanPropertyWriter extends BeanPropertyWriter {
|
||||
|
||||
protected KomgaCleanBeanPropertyWriter(BeanPropertyWriter base) {
|
||||
super(base);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serializeAsProperty(Object bean, JsonGenerator gen, SerializationContext prov) throws Exception {
|
||||
if (KomgaCleanContext.isCleanMode()) {
|
||||
String propertyName = getName();
|
||||
|
||||
// Exclude properties ending with "Lock"
|
||||
if (propertyName.endsWith("Lock")) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Exclude null values
|
||||
Object value = get(bean);
|
||||
if (value == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Exclude empty collections/arrays
|
||||
if (value instanceof Collection && ((Collection<?>) value).isEmpty()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Default behavior
|
||||
super.serializeAsProperty(bean, gen, prov);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.http.client.JdkClientHttpRequestFactory;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestClient;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.net.http.HttpClient;
|
||||
import java.time.Duration;
|
||||
|
||||
@Configuration
|
||||
public class RestClientConfig {
|
||||
|
||||
@Bean
|
||||
public RestClient restClient() {
|
||||
return RestClient.builder()
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public RestTemplate restTemplate(HttpClient httpClient) {
|
||||
JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(httpClient);
|
||||
factory.setReadTimeout(Duration.ofSeconds(15));
|
||||
return new RestTemplate(factory);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestTemplate oidcRestTemplate() {
|
||||
var factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout(Duration.ofSeconds(10));
|
||||
factory.setReadTimeout(Duration.ofSeconds(10));
|
||||
return new RestTemplate(factory);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.task.AsyncTaskExecutor;
|
||||
import org.springframework.core.task.VirtualThreadTaskExecutor;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextExecutor;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextRunnable;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
public class TaskExecutorConfig {
|
||||
|
||||
@Bean(name = "taskExecutor")
|
||||
public AsyncTaskExecutor taskExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setThreadNamePrefix("async-");
|
||||
executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
|
||||
executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
|
||||
executor.setQueueCapacity(500);
|
||||
executor.setTaskDecorator(DelegatingSecurityContextRunnable::new);
|
||||
executor.setWaitForTasksToCompleteOnShutdown(true);
|
||||
executor.setAwaitTerminationSeconds(60);
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TaskScheduler taskScheduler() {
|
||||
var scheduler = new SimpleAsyncTaskScheduler();
|
||||
scheduler.setVirtualThreads(true);
|
||||
scheduler.setThreadNamePrefix("scheduler-");
|
||||
return scheduler;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.booklore.service.task.TaskService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.event.EventListener;
|
||||
|
||||
@Configuration
|
||||
@AllArgsConstructor
|
||||
@Slf4j
|
||||
public class TaskSchedulerConfig {
|
||||
|
||||
private final TaskService taskService;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void initializeScheduledTasks() {
|
||||
log.info("Application ready, initializing scheduled tasks");
|
||||
taskService.initializeScheduledTasks();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.interceptor.KomgaCleanInterceptor;
|
||||
import org.booklore.interceptor.KomgaEnabledInterceptor;
|
||||
import org.booklore.interceptor.OpdsEnabledInterceptor;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.task.VirtualThreadTaskExecutor;
|
||||
import org.springframework.data.web.config.EnableSpringDataWebSupport;
|
||||
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.resource.PathResourceResolver;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.springframework.data.web.config.EnableSpringDataWebSupport.PageSerializationMode.VIA_DTO;
|
||||
|
||||
@Configuration
|
||||
@EnableSpringDataWebSupport(pageSerializationMode = VIA_DTO)
|
||||
@RequiredArgsConstructor
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
private final OpdsEnabledInterceptor opdsEnabledInterceptor;
|
||||
private final KomgaEnabledInterceptor komgaEnabledInterceptor;
|
||||
private final KomgaCleanInterceptor komgaCleanInterceptor;
|
||||
|
||||
@Override
|
||||
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
|
||||
configurer.setTaskExecutor(new VirtualThreadTaskExecutor("mvc-async-"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/**")
|
||||
.addResourceLocations("classpath:/static/")
|
||||
.resourceChain(true)
|
||||
.addResolver(new PathResourceResolver() {
|
||||
@Override
|
||||
protected Resource getResource(String resourcePath, Resource location) throws IOException {
|
||||
Resource resource = location.createRelative(resourcePath);
|
||||
if (resource.exists() && resource.isReadable()) {
|
||||
return resource;
|
||||
}
|
||||
|
||||
Resource index = new ClassPathResource("/static/index.html");
|
||||
return index.exists() && index.isReadable() ? index : null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(opdsEnabledInterceptor)
|
||||
.addPathPatterns("/api/v1/opds/**", "/api/v2/opds/**");
|
||||
registry.addInterceptor(komgaEnabledInterceptor)
|
||||
.addPathPatterns("/komga/api/**");
|
||||
registry.addInterceptor(komgaCleanInterceptor)
|
||||
.addPathPatterns("/komga/api/**");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.booklore.config.security.interceptor.WebSocketAuthInterceptor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.messaging.simp.config.ChannelRegistration;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
import org.springframework.web.socket.config.WebSocketMessageBrokerStats;
|
||||
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 org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
|
||||
private final WebSocketAuthInterceptor webSocketAuthInterceptor;
|
||||
private final Environment env;
|
||||
|
||||
public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor, Environment env) {
|
||||
this.webSocketAuthInterceptor = webSocketAuthInterceptor;
|
||||
this.env = env;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void suppressStatsLogging(ApplicationReadyEvent event) {
|
||||
var stats = event.getApplicationContext().getBean(WebSocketMessageBrokerStats.class);
|
||||
stats.setLoggingPeriod(30 * 24 * 60 * 60 * 1000L); // 30 days
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry registry) {
|
||||
registry.enableSimpleBroker("/queue", "/topic")
|
||||
.setHeartbeatValue(new long[]{10_000, 10_000})
|
||||
.setTaskScheduler(wsHeartbeatScheduler());
|
||||
registry.setApplicationDestinationPrefixes("/app");
|
||||
registry.setUserDestinationPrefix("/user");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TaskScheduler wsHeartbeatScheduler() {
|
||||
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setPoolSize(1);
|
||||
scheduler.setThreadNamePrefix("ws-heartbeat-");
|
||||
scheduler.setDaemon(true);
|
||||
return scheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||
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()) {
|
||||
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
|
||||
public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
|
||||
registration.setSendTimeLimit(15_000)
|
||||
.setSendBufferSizeLimit(512 * 1024)
|
||||
.setMessageSizeLimit(128 * 1024)
|
||||
.setTimeToFirstMessage(30_000);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureClientInboundChannel(ChannelRegistration registration) {
|
||||
registration.interceptors(webSocketAuthInterceptor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package org.booklore.config.logging;
|
||||
|
||||
import org.booklore.config.logging.filter.RequestLoggingFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.filter.GenericFilterBean;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@Configuration
|
||||
public class RequestLoggingFilterConfig {
|
||||
private static final Set<String> EXCLUDED_PATHS = Set.of(
|
||||
"/api/v1/healthcheck",
|
||||
"/ws"
|
||||
);
|
||||
|
||||
private static final Set<String> EXCLUDED_HEADERS = Set.of(
|
||||
"authorization",
|
||||
"cookie",
|
||||
"set-cookie",
|
||||
"x-api-key",
|
||||
"x-forwarded-access-token"
|
||||
);
|
||||
|
||||
@Bean
|
||||
public GenericFilterBean logFilter() {
|
||||
RequestLoggingFilter filter = new RequestLoggingFilter();
|
||||
|
||||
filter.setIncludeQueryString(true);
|
||||
filter.setIncludePayload(true);
|
||||
filter.setMaxPayloadLength(10000);
|
||||
filter.setIncludeHeaders(true);
|
||||
|
||||
filter.setHeaderPredicate((header) -> !EXCLUDED_HEADERS.contains(header.toLowerCase()));
|
||||
filter.setPathPredicate((path) -> !EXCLUDED_PATHS.contains(path));
|
||||
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.booklore.config.logging.filter;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.springframework.web.filter.CommonsRequestLoggingFilter;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class RequestLoggingFilter extends CommonsRequestLoggingFilter {
|
||||
private Predicate<String> pathPredicate = null;
|
||||
|
||||
public void setPathPredicate(@Nullable Predicate<String> pathPredicate) {
|
||||
this.pathPredicate = pathPredicate;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldLog(HttpServletRequest request) {
|
||||
if (pathPredicate != null && !pathPredicate.test(request.getRequestURI())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return super.shouldLog(request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.booklore.config.openapi;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Contact;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.info.License;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.config.AppProperties;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(name = "app.api-docs.enabled", havingValue = "true", matchIfMissing = false)
|
||||
public class OpenApiConfig {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
|
||||
@Bean
|
||||
public OpenAPI openApi() {
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("Grimmory API")
|
||||
.description("REST API documentation for managing libraries, readers, metadata, and device integrations in Grimmory.")
|
||||
.version(appProperties.getVersion())
|
||||
.contact(new Contact()
|
||||
.name("Grimmory")
|
||||
.url("https://github.com/grimmory-tools/grimmory"))
|
||||
.license(new License()
|
||||
.name("AGPL-3.0")
|
||||
.url("https://www.gnu.org/licenses/agpl-3.0.html")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.booklore.config.security;
|
||||
|
||||
import org.booklore.config.security.filter.ImageCachingFilter;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.Ordered;
|
||||
|
||||
@Configuration
|
||||
public class ImageCacheConfig {
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<ImageCachingFilter> imageCachingFilterRegistration() {
|
||||
FilterRegistrationBean<ImageCachingFilter> registrationBean = new FilterRegistrationBean<>();
|
||||
registrationBean.setFilter(new ImageCachingFilter());
|
||||
registrationBean.addUrlPatterns(
|
||||
"/api/v1/media/book/*/cover",
|
||||
"/api/v1/media/book/*/thumbnail",
|
||||
"/api/v1/media/book/*/backup-cover"
|
||||
);
|
||||
registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE);
|
||||
return registrationBean;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package org.booklore.config.security;
|
||||
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.service.security.JwtSecretService;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.ExpiredJwtException;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class JwtUtils {
|
||||
|
||||
private final JwtSecretService jwtSecretService;
|
||||
@Getter
|
||||
public static final long accessTokenExpirationMs = 1000L * 60 * 60 * 2; // 2 hours
|
||||
@Getter
|
||||
public static final long refreshTokenExpirationMs = 1000L * 60 * 60 * 24 * 30; // 30 days
|
||||
|
||||
private SecretKey getSigningKey() {
|
||||
String secretKey = jwtSecretService.getSecret();
|
||||
return Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public String generateToken(BookLoreUserEntity user, boolean isRefreshToken) {
|
||||
long expirationTime = isRefreshToken ? refreshTokenExpirationMs : accessTokenExpirationMs;
|
||||
Instant now = Instant.now();
|
||||
return Jwts.builder()
|
||||
.issuer("booklore")
|
||||
.subject(user.getUsername())
|
||||
.claim("userId", user.getId())
|
||||
.claim("isDefaultPassword", user.isDefaultPassword())
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(now.plusMillis(expirationTime)))
|
||||
.signWith(getSigningKey(), Jwts.SIG.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public String generateAccessToken(BookLoreUserEntity user) {
|
||||
return generateToken(user, false);
|
||||
}
|
||||
|
||||
public String generateRefreshToken(BookLoreUserEntity user) {
|
||||
return generateToken(user, true);
|
||||
}
|
||||
|
||||
public boolean validateToken(String token) {
|
||||
try {
|
||||
extractClaims(token);
|
||||
return true;
|
||||
} catch (ExpiredJwtException e) {
|
||||
log.debug("Token expired: {}", e.getMessage());
|
||||
} catch (JwtException e) {
|
||||
log.debug("Invalid token: {}", e.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Claims extractClaims(String token) {
|
||||
Claims claims = Jwts.parser()
|
||||
.verifyWith(getSigningKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
|
||||
// Graceful issuer enforcement: reject tokens with a wrong issuer,
|
||||
// but allow legacy tokens that have no issuer claim (issued before this check).
|
||||
// After a full token rotation cycle (~30 days), switch to hard .requireIssuer().
|
||||
String issuer = claims.getIssuer();
|
||||
if (issuer != null && !"booklore".equals(issuer)) {
|
||||
throw new JwtException("Invalid issuer: " + issuer);
|
||||
}
|
||||
|
||||
return claims;
|
||||
}
|
||||
|
||||
public String extractUsername(String token) {
|
||||
return extractClaims(token).getSubject();
|
||||
}
|
||||
|
||||
public Long extractUserId(String token) {
|
||||
Object userIdClaim = extractClaims(token).get("userId");
|
||||
if (userIdClaim instanceof Number) {
|
||||
return ((Number) userIdClaim).longValue();
|
||||
}
|
||||
throw new IllegalArgumentException("Invalid userId claim type");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package org.booklore.config.security;
|
||||
|
||||
import org.booklore.config.security.filter.*;
|
||||
import org.booklore.config.security.service.OpdsUserDetailsService;
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
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.http.server.PathContainer;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
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.JdkClientHttpRequestFactory;
|
||||
|
||||
import java.net.http.HttpClient;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.util.pattern.PathPattern;
|
||||
import org.springframework.web.util.pattern.PathPatternParser;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@EnableMethodSecurity
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
private static final Pattern ALLOWED = Pattern.compile("\\s*,\\s*");
|
||||
private final OpdsUserDetailsService opdsUserDetailsService;
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
private final AuthenticationCheckFilter authenticationCheckFilter;
|
||||
private final Environment env;
|
||||
|
||||
private static final String[] COMMON_PUBLIC_ENDPOINTS = {
|
||||
"/ws/**", // WebSocket connections (auth handled in WebSocketAuthInterceptor)
|
||||
"/kobo/**", // Kobo API requests (auth handled in KoboAuthFilter)
|
||||
"/api/docs", // API documentation UI
|
||||
"/api/openapi.json", // OpenAPI spec (used by API documentation UI)
|
||||
"/api/v1/auth/login", // Login endpoint (must remain public)
|
||||
"/api/v1/auth/refresh", // Token refresh endpoint (must remain public)
|
||||
"/api/v1/auth/remote", // Remote auth endpoint (must remain public)
|
||||
"/api/v1/auth/oidc/**", // OIDC authentication endpoints
|
||||
"/api/v1/public-settings", // Public endpoint for checking OIDC or other app settings
|
||||
"/api/v1/setup/**", // Setup wizard endpoints (must remain accessible before initial setup)
|
||||
"/api/v1/healthcheck/**" // Healthcheck endpoints (must remain accessible for Docker healthchecks)
|
||||
};
|
||||
|
||||
private static final String[] COMMON_UNAUTHENTICATED_ENDPOINTS = {
|
||||
"/api/v1/opds/search.opds",
|
||||
"/api/v2/opds/search.opds"
|
||||
};
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(1)
|
||||
public SecurityFilterChain opdsBasicAuthSecurityChain(HttpSecurity http) throws Exception {
|
||||
List<String> unauthenticatedEndpoints = new ArrayList<>(Arrays.asList(COMMON_UNAUTHENTICATED_ENDPOINTS));
|
||||
http
|
||||
.securityMatcher("/api/v1/opds/**", "/api/v2/opds/**")
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers(unauthenticatedEndpoints.toArray(new String[0])).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.httpBasic(basic -> basic
|
||||
.realmName("Booklore OPDS")
|
||||
.authenticationEntryPoint((request, response, authException) -> {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setHeader("WWW-Authenticate", "Basic realm=\"Booklore OPDS\"");
|
||||
response.getWriter().write("HTTP Status 401 - " + authException.getMessage());
|
||||
})
|
||||
);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(2)
|
||||
public SecurityFilterChain komgaBasicAuthSecurityChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.securityMatcher("/komga/api/v1/**", "/komga/api/v2/**")
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.httpBasic(basic -> basic
|
||||
.realmName("Booklore Komga API")
|
||||
.authenticationEntryPoint((request, response, authException) -> {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setHeader("WWW-Authenticate", "Basic realm=\"Booklore Komga API\"");
|
||||
response.getWriter().write("HTTP Status 401 - " + authException.getMessage());
|
||||
})
|
||||
);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(3)
|
||||
public SecurityFilterChain koreaderSecurityChain(HttpSecurity http, KoreaderAuthFilter koreaderAuthFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/koreader/**")
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
|
||||
.addFilterBefore(koreaderAuthFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(3)
|
||||
public SecurityFilterChain koboSecurityChain(HttpSecurity http, KoboAuthFilter koboAuthFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/kobo/**")
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
|
||||
.addFilterBefore(koboAuthFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(4)
|
||||
public SecurityFilterChain coverJwtApiSecurityChain(HttpSecurity http, QueryParameterJwtFilter queryParameterJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/media/**")
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.headers(headers -> headers
|
||||
.cacheControl(HeadersConfigurer.CacheControlConfig::disable)
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(queryParameterJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(5)
|
||||
public SecurityFilterChain customFontSecurityChain(HttpSecurity http, QueryParameterJwtFilter queryParameterJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/custom-fonts/*/file")
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(queryParameterJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(6)
|
||||
public SecurityFilterChain epubStreamingSecurityChain(HttpSecurity http, QueryParameterJwtFilter queryParameterJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/epub/*/file/**")
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(queryParameterJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(7)
|
||||
public SecurityFilterChain audiobookStreamingSecurityChain(HttpSecurity http, QueryParameterJwtFilter queryParameterJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/audiobooks/*/stream/**", "/api/v1/audiobooks/*/track/*/stream/**", "/api/v1/audiobooks/*/cover")
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(queryParameterJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(8)
|
||||
public SecurityFilterChain wsSecurityChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.securityMatcher("/ws/**")
|
||||
.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))
|
||||
.contentTypeOptions(contentType -> {})
|
||||
.frameOptions(HeadersConfigurer.FrameOptionsConfig::deny)
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(9)
|
||||
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
|
||||
var parser = new PathPatternParser();
|
||||
final List<PathPattern> matchPatterns = Stream.of(
|
||||
"/api/**",
|
||||
"/komga/**"
|
||||
).map(parser::parse).toList();
|
||||
final List<PathPattern> whitelistedPatterns = Stream.concat(
|
||||
Arrays.stream(COMMON_PUBLIC_ENDPOINTS),
|
||||
Stream.of(
|
||||
"/api/v1/opds",
|
||||
"/api/v1/opds/**",
|
||||
"/api/v2/opds",
|
||||
"/api/v2/opds/**",
|
||||
"/api/kobo",
|
||||
"/api/kobo/**",
|
||||
"/api/v1/auth/refresh",
|
||||
"/api/v1/setup"
|
||||
)
|
||||
).map(parser::parse).toList();
|
||||
|
||||
http
|
||||
.securityMatcher(request -> {
|
||||
var pathContainer = PathContainer.parsePath(request.getRequestURI());
|
||||
if (matchPatterns.parallelStream().noneMatch(p -> p.matches(pathContainer))) {
|
||||
return false;
|
||||
}
|
||||
if (whitelistedPatterns.parallelStream().anyMatch(p -> p.matches(pathContainer))) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.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))
|
||||
.contentTypeOptions(contentType -> {})
|
||||
.frameOptions(HeadersConfigurer.FrameOptionsConfig::deny)
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(10)
|
||||
public SecurityFilterChain staticResourcesSecurityChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.headers(headers -> headers
|
||||
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
|
||||
.referrerPolicy(referrer -> referrer.policy(
|
||||
ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
|
||||
.contentTypeOptions(contentType -> {})
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
|
||||
AuthenticationManagerBuilder auth = http.getSharedObject(AuthenticationManagerBuilder.class);
|
||||
auth.userDetailsService(opdsUserDetailsService).passwordEncoder(passwordEncoder());
|
||||
return auth.build();
|
||||
}
|
||||
|
||||
@Bean("noRedirectRestTemplate")
|
||||
public RestTemplate noRedirectRestTemplate() {
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.NEVER)
|
||||
.build();
|
||||
return new RestTemplate(new JdkClientHttpRequestFactory(httpClient));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
|
||||
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", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
||||
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type", "Range", "If-None-Match", "If-Modified-Since"));
|
||||
configuration.setExposedHeaders(List.of("Content-Disposition", "Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Date", "Last-Modified"));
|
||||
configuration.setAllowCredentials(true);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package org.booklore.config.security;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.repository.ShelfRepository;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component("securityUtil")
|
||||
public class SecurityUtil {
|
||||
|
||||
private final ShelfRepository shelfRepository;
|
||||
|
||||
private BookLoreUser getCurrentUser() {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isAdmin() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isAdmin();
|
||||
}
|
||||
|
||||
public boolean isSelf(Long userId) {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getId().equals(userId);
|
||||
}
|
||||
|
||||
public boolean canUpload() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanUpload();
|
||||
}
|
||||
|
||||
public boolean canDownload() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanDownload();
|
||||
}
|
||||
|
||||
public boolean canManageLibrary() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanManageLibrary();
|
||||
}
|
||||
|
||||
public boolean canManageIcons() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanManageIcons();
|
||||
}
|
||||
|
||||
public boolean canManageFonts() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanManageFonts();
|
||||
}
|
||||
|
||||
public boolean canSyncKoReader() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanSyncKoReader();
|
||||
}
|
||||
|
||||
public boolean canSyncKobo() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanSyncKobo();
|
||||
}
|
||||
|
||||
public boolean canEditMetadata() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanEditMetadata();
|
||||
}
|
||||
|
||||
public boolean canBulkEditMetadata() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanBulkEditMetadata();
|
||||
}
|
||||
|
||||
public boolean canBulkLockUnlockMetadata() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanBulkLockUnlockMetadata();
|
||||
}
|
||||
|
||||
public boolean canBulkRegenerateCover() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanBulkRegenerateCover();
|
||||
}
|
||||
|
||||
public boolean canEmailBook() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanEmailBook();
|
||||
}
|
||||
|
||||
public boolean canDeleteBook() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanDeleteBook();
|
||||
}
|
||||
public boolean canAccessOpds() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanAccessOpds();
|
||||
}
|
||||
|
||||
|
||||
public boolean canViewUserProfile(Long userId) {
|
||||
var user = getCurrentUser();
|
||||
return user != null && (user.getPermissions().isAdmin() || user.getId().equals(userId));
|
||||
}
|
||||
|
||||
public boolean isShelfOwner(Long shelfId) {
|
||||
var user = getCurrentUser();
|
||||
if (user != null) {
|
||||
return shelfRepository.findByIdWithUser(shelfId)
|
||||
.map(shelf -> shelf.getUser().getId().equals(user.getId()))
|
||||
.orElse(false);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean canAccessBookdrop() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanAccessBookdrop();
|
||||
}
|
||||
|
||||
public boolean canAccessUserStats() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanAccessUserStats();
|
||||
}
|
||||
|
||||
public boolean canAccessTaskManager() {
|
||||
var user = getCurrentUser();
|
||||
return user != null && user.getPermissions().isCanAccessTaskManager();
|
||||
}
|
||||
|
||||
public boolean canReadShelf(Long shelfId) {
|
||||
var user = getCurrentUser();
|
||||
if (user != null) {
|
||||
return shelfRepository.findByIdWithUser(shelfId)
|
||||
.map(shelf -> shelf.isPublic() || shelf.getUser().getId().equals(user.getId()))
|
||||
.orElse(false);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package org.booklore.config.security.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface CheckBookAccess {
|
||||
String bookIdParam();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.booklore.config.security.annotation;
|
||||
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface CheckLibraryAccess {
|
||||
String libraryIdParam();
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package org.booklore.config.security.aspect;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.booklore.config.security.annotation.CheckBookAccess;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.restriction.ContentRestrictionService;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BookAccessAspect {
|
||||
|
||||
private static final Pattern NUMERIC_PATTERN = Pattern.compile("\\d+");
|
||||
private final AuthenticationService authenticationService;
|
||||
private final BookRepository bookRepository;
|
||||
private final ContentRestrictionService contentRestrictionService;
|
||||
|
||||
@Before("@annotation(org.booklore.config.security.annotation.CheckBookAccess)")
|
||||
public void checkBookAccess(JoinPoint joinPoint) {
|
||||
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = methodSignature.getMethod();
|
||||
CheckBookAccess annotation = method.getAnnotation(CheckBookAccess.class);
|
||||
|
||||
if (annotation == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Long bookId = extractBookId(joinPoint.getArgs(), methodSignature.getParameterNames(), annotation.bookIdParam());
|
||||
if (bookId == null) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Missing or invalid book ID in method parameters.");
|
||||
}
|
||||
|
||||
BookEntity bookEntity = bookRepository.findByIdWithMetadata(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
if (user == null) {
|
||||
throw ApiError.FORBIDDEN.createException("Authentication required.");
|
||||
}
|
||||
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean hasLibraryAccess = user.getAssignedLibraries().stream().anyMatch(library -> library.getId().equals(bookEntity.getLibrary().getId()));
|
||||
|
||||
if (!hasLibraryAccess) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not authorized to access this book.");
|
||||
}
|
||||
|
||||
List<BookEntity> filteredBooks = contentRestrictionService.applyRestrictions(List.of(bookEntity), user.getId());
|
||||
if (filteredBooks.isEmpty()) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not authorized to access this book.");
|
||||
}
|
||||
}
|
||||
|
||||
private Long extractBookId(Object[] args, String[] paramNames, String targetParamName) {
|
||||
for (int i = 0; i < paramNames.length; i++) {
|
||||
if (Objects.equals(paramNames[i], targetParamName)) {
|
||||
Object arg = args[i];
|
||||
if (arg instanceof Long) {
|
||||
return (Long) arg;
|
||||
} else if (arg instanceof String str && NUMERIC_PATTERN.matcher(str).matches()) {
|
||||
return Long.valueOf(str);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package org.booklore.config.security.aspect;
|
||||
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.config.security.annotation.CheckLibraryAccess;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class LibraryAccessAspect {
|
||||
|
||||
private static final Pattern NUMERIC_PATTERN = Pattern.compile("\\d+");
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@Before("@annotation(org.booklore.config.security.annotation.CheckLibraryAccess)")
|
||||
public void checkLibraryAccess(JoinPoint joinPoint) {
|
||||
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = methodSignature.getMethod();
|
||||
CheckLibraryAccess annotation = method.getAnnotation(CheckLibraryAccess.class);
|
||||
|
||||
if (annotation == null) return;
|
||||
|
||||
Long libraryId = extractLibraryId(methodSignature.getParameterNames(), joinPoint.getArgs(), annotation.libraryIdParam());
|
||||
|
||||
if (libraryId == null) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Library ID not found in method parameters.");
|
||||
}
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
if (user == null) {
|
||||
throw ApiError.FORBIDDEN.createException("Authentication required.");
|
||||
}
|
||||
|
||||
if (user.getPermissions().isAdmin()) return;
|
||||
|
||||
boolean hasAccess = user.getAssignedLibraries().stream().anyMatch(lib -> lib.getId().equals(libraryId));
|
||||
|
||||
if (!hasAccess) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not authorized to access this library.");
|
||||
}
|
||||
}
|
||||
|
||||
private Long extractLibraryId(String[] paramNames, Object[] args, String targetParam) {
|
||||
for (int i = 0; i < paramNames.length; i++) {
|
||||
if (Objects.equals(paramNames[i], targetParam)) {
|
||||
Object arg = args[i];
|
||||
if (arg instanceof Long) {
|
||||
return (Long) arg;
|
||||
} else if (arg instanceof String str && NUMERIC_PATTERN.matcher(str).matches()) {
|
||||
return Long.parseLong(str);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.boot.web.servlet.FilterRegistration;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
@FilterRegistration(enabled = false)
|
||||
public class AuthenticationCheckFilter extends OncePerRequestFilter {
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
|
||||
var auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (auth == null || !auth.isAuthenticated()) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
return;
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class ImageCachingFilter extends OncePerRequestFilter {
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||
String uri = request.getRequestURI();
|
||||
if (uri.startsWith("/api/v1/media/book/") &&
|
||||
(uri.contains("/cover") || uri.contains("/thumbnail") || uri.contains("/backup-cover") ||
|
||||
uri.contains("/cbx/pages/"))) {
|
||||
response.setHeader(HttpHeaders.CACHE_CONTROL, "public, max-age=3600");
|
||||
response.setHeader(HttpHeaders.EXPIRES, String.valueOf(System.currentTimeMillis() + 3600_000));
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import org.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import org.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.springframework.boot.web.servlet.FilterRegistration;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
@FilterRegistration(enabled = false)
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
private final JwtUtils jwtUtils;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
if (SecurityContextHolder.getContext().getAuthentication() != null &&
|
||||
SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
String token = extractToken(request);
|
||||
|
||||
if (token == null) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateUser(token, request);
|
||||
} else {
|
||||
log.debug("Invalid token. Rejecting request.");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.error("Authentication error: {}", ex.getMessage(), ex);
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private void authenticateUser(String token, HttpServletRequest request) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
BookLoreUserEntity entity = userRepository.findByIdWithDetails(userId).orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
|
||||
private String extractToken(HttpServletRequest request) {
|
||||
String bearer = request.getHeader("Authorization");
|
||||
return (bearer != null && bearer.startsWith("Bearer ")) ? bearer.substring(7) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import org.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.UserPermissionsEntity;
|
||||
import org.booklore.repository.KoboUserSettingsRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.springframework.boot.web.servlet.FilterRegistration;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Component
|
||||
@FilterRegistration(enabled = false)
|
||||
public class KoboAuthFilter extends OncePerRequestFilter {
|
||||
|
||||
private final KoboUserSettingsRepository koboUserSettingsRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||
|
||||
String path = request.getRequestURI();
|
||||
String[] parts = path.split("/");
|
||||
if (parts.length < 4) {
|
||||
log.warn("KOBO token missing in path");
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "KOBO token missing");
|
||||
return;
|
||||
}
|
||||
|
||||
String token = parts[3];
|
||||
|
||||
var userTokenOpt = koboUserSettingsRepository.findByToken(token);
|
||||
if (userTokenOpt.isEmpty()) {
|
||||
log.warn("Invalid KOBO token");
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid KOBO token");
|
||||
return;
|
||||
}
|
||||
|
||||
var userToken = userTokenOpt.get();
|
||||
var userOpt = userRepository.findByIdWithDetails(userToken.getUserId());
|
||||
|
||||
if (userOpt.isEmpty()) {
|
||||
log.warn("User not found for KOBO token");
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User not found");
|
||||
return;
|
||||
}
|
||||
|
||||
var entity = userOpt.get();
|
||||
if (entity.getPermissions() == null || !entity.getPermissions().isPermissionSyncKobo()) {
|
||||
log.warn("User {} does not have syncKobo permission", entity.getId());
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Insufficient permissions");
|
||||
return;
|
||||
}
|
||||
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
List<GrantedAuthority> authorities = getAuthorities(entity.getPermissions());
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, authorities);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private List<GrantedAuthority> getAuthorities(UserPermissionsEntity permissions) {
|
||||
List<GrantedAuthority> authorities = new ArrayList<>();
|
||||
if (permissions != null) {
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_UPLOAD", permissions.isPermissionUpload());
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_DOWNLOAD", permissions.isPermissionDownload());
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_EDIT_METADATA", permissions.isPermissionEditMetadata());
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_MANAGE_LIBRARY", permissions.isPermissionManageLibrary());
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_ADMIN", permissions.isPermissionAdmin());
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_SYNC_KOBO", permissions.isPermissionSyncKobo());
|
||||
}
|
||||
return authorities;
|
||||
}
|
||||
|
||||
private void addAuthorityIfPermissionGranted(List<GrantedAuthority> authorities, String role, boolean permissionGranted) {
|
||||
if (permissionGranted) {
|
||||
authorities.add(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import org.booklore.config.security.userdetails.KoreaderUserDetails;
|
||||
import org.booklore.repository.KoreaderUserRepository;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.web.servlet.FilterRegistration;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Component
|
||||
@Slf4j
|
||||
@FilterRegistration(enabled = false)
|
||||
public class KoreaderAuthFilter extends OncePerRequestFilter {
|
||||
|
||||
private final KoreaderUserRepository koreaderUserRepository;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
|
||||
String username = request.getHeader("x-auth-user");
|
||||
String key = request.getHeader("x-auth-key");
|
||||
|
||||
if (username == null || key == null) {
|
||||
log.info("Missing KOReader headers");
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
var user = koreaderUserRepository.findByUsername(username).orElse(null);
|
||||
if (user == null) {
|
||||
log.info("KOReader user not found");
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!user.getPasswordMD5().equalsIgnoreCase(key)) {
|
||||
log.info("KOReader user password not match");
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
Long bookLoreUserId = null;
|
||||
if (user.getBookLoreUser() != null) {
|
||||
bookLoreUserId = user.getBookLoreUser().getId();
|
||||
}
|
||||
|
||||
UserDetails userDetails = new KoreaderUserDetails(
|
||||
user.getUsername(),
|
||||
user.getPasswordMD5(),
|
||||
user.isSyncEnabled(),
|
||||
user.isSyncWithBookloreReader(),
|
||||
bookLoreUserId,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER"))
|
||||
);
|
||||
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import org.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import org.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.springframework.boot.web.servlet.FilterRegistration;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
@FilterRegistration(enabled = false)
|
||||
public class QueryParameterJwtFilter extends OncePerRequestFilter {
|
||||
|
||||
protected final JwtUtils jwtUtils;
|
||||
protected final UserRepository userRepository;
|
||||
protected final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
if (SecurityContextHolder.getContext().getAuthentication() != null &&
|
||||
SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
String token = request.getParameter("token");
|
||||
|
||||
if (token == null || token.isEmpty()) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateUser(token, request);
|
||||
} else {
|
||||
log.debug("Invalid token. Rejecting request.");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.error("Authentication error: {}", ex.getMessage(), ex);
|
||||
}
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
protected void authenticateUser(String token, HttpServletRequest request) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
BookLoreUserEntity entity = userRepository.findByIdWithDetails(userId)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Enables SharedArrayBuffer by setting Cross-Origin isolation headers.
|
||||
* Required by pdfium WASM (Emscripten-compiled with thread support) used by EmbedPDF.
|
||||
* Without these headers the WASM module stalls on instantiation.
|
||||
*/
|
||||
@Component
|
||||
@Order(1)
|
||||
public class SharedArrayBufferHeaderFilter extends OncePerRequestFilter {
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
response.setHeader("Cross-Origin-Opener-Policy", "same-origin");
|
||||
response.setHeader("Cross-Origin-Embedder-Policy", "credentialless");
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package org.booklore.config.security.interceptor;
|
||||
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.MessageChannel;
|
||||
import org.springframework.messaging.MessagingException;
|
||||
import org.springframework.messaging.simp.stomp.StompCommand;
|
||||
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
|
||||
import org.springframework.messaging.support.ChannelInterceptor;
|
||||
import org.springframework.messaging.support.MessageHeaderAccessor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
|
||||
@RequiredArgsConstructor
|
||||
public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
|
||||
private static final String BEARER_PREFIX = "Bearer ";
|
||||
private static final Set<String> ALLOWED_DEST_PREFIXES = Set.of("/topic/", "/user/queue/");
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
|
||||
@Override
|
||||
public Message<?> preSend(Message<?> message, MessageChannel channel) {
|
||||
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
|
||||
if (accessor == null || accessor.getCommand() == null) {
|
||||
return message;
|
||||
}
|
||||
|
||||
switch (accessor.getCommand()) {
|
||||
case CONNECT -> handleConnect(accessor);
|
||||
case SUBSCRIBE -> validateSubscription(accessor);
|
||||
case SEND -> rejectSend(accessor);
|
||||
case DISCONNECT -> log.debug("Client disconnected: {}", accessor.getUser());
|
||||
default -> { /* pass through */ }
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private void handleConnect(StompHeaderAccessor accessor) {
|
||||
List<String> authHeaders = accessor.getNativeHeader("Authorization");
|
||||
if (authHeaders == null || authHeaders.isEmpty()) {
|
||||
throw new MessagingException("Missing Authorization header");
|
||||
}
|
||||
|
||||
String raw = authHeaders.getFirst().trim();
|
||||
if (!raw.startsWith(BEARER_PREFIX)) {
|
||||
throw new MessagingException("Malformed Authorization header");
|
||||
}
|
||||
|
||||
String token = raw.substring(BEARER_PREFIX.length());
|
||||
Authentication auth = authenticateToken(token);
|
||||
if (auth == null) {
|
||||
throw new MessagingException("Invalid or expired token");
|
||||
}
|
||||
|
||||
accessor.setUser(auth);
|
||||
log.debug("WebSocket authenticated: {}", auth.getName());
|
||||
}
|
||||
|
||||
private void validateSubscription(StompHeaderAccessor accessor) {
|
||||
requireAuthenticated(accessor);
|
||||
|
||||
String destination = accessor.getDestination();
|
||||
if (destination == null || destination.contains("..")) {
|
||||
throw new MessagingException("Invalid subscription destination");
|
||||
}
|
||||
|
||||
boolean allowed = ALLOWED_DEST_PREFIXES.stream().anyMatch(destination::startsWith);
|
||||
if (!allowed) {
|
||||
log.warn("Subscription rejected: user={} dest='{}'", accessor.getUser(), destination);
|
||||
throw new MessagingException("Destination '" + destination + "' is not allowed");
|
||||
}
|
||||
}
|
||||
|
||||
private void rejectSend(StompHeaderAccessor accessor) {
|
||||
log.warn("SEND rejected: user={} dest='{}'", accessor.getUser(), accessor.getDestination());
|
||||
throw new MessagingException("Client SEND is not permitted");
|
||||
}
|
||||
|
||||
private void requireAuthenticated(StompHeaderAccessor accessor) {
|
||||
if (accessor.getUser() == null) {
|
||||
throw new MessagingException("Not authenticated");
|
||||
}
|
||||
}
|
||||
|
||||
private Authentication authenticateToken(String token) {
|
||||
if (token == null || token.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
String username = jwtUtils.extractUsername(token);
|
||||
if (username != null && !username.isBlank()) {
|
||||
return new UsernamePasswordAuthenticationToken(username, null, List.of());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Token validation failed: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package org.booklore.config.security.oidc;
|
||||
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import org.booklore.model.entity.OidcSessionEntity;
|
||||
import org.booklore.model.enums.AuditAction;
|
||||
import org.booklore.model.websocket.Topic;
|
||||
import org.booklore.repository.OidcSessionRepository;
|
||||
import org.booklore.repository.RefreshTokenRepository;
|
||||
import org.booklore.service.NotificationService;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class BackchannelLogoutService {
|
||||
|
||||
private static final Cache<String, Instant> PROCESSED_JTIS = Caffeine.newBuilder()
|
||||
.expireAfterWrite(Duration.ofHours(1))
|
||||
.maximumSize(1_000)
|
||||
.build();
|
||||
|
||||
private final AppSettingService appSettingService;
|
||||
private final OidcTokenValidator oidcTokenValidator;
|
||||
private final OidcSessionRepository oidcSessionRepository;
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final NotificationService notificationService;
|
||||
private final AuditService auditService;
|
||||
|
||||
public void handleLogoutToken(String logoutToken) {
|
||||
if (!appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("OIDC is not enabled");
|
||||
}
|
||||
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
if (providerDetails == null || providerDetails.getIssuerUri() == null) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("OIDC is not configured");
|
||||
}
|
||||
|
||||
JWTClaimsSet claims = oidcTokenValidator.validateLogoutToken(
|
||||
logoutToken, providerDetails.getIssuerUri(), providerDetails.getClientId()
|
||||
);
|
||||
|
||||
String jti = claims.getJWTID();
|
||||
if (jti == null || jti.isBlank()) {
|
||||
throw ApiError.OIDC_LOGOUT_MISSING_JTI.createException();
|
||||
}
|
||||
if (PROCESSED_JTIS.getIfPresent(jti) != null) {
|
||||
throw ApiError.OIDC_LOGOUT_REPLAY.createException();
|
||||
}
|
||||
PROCESSED_JTIS.put(jti, Instant.now());
|
||||
|
||||
String sid = null;
|
||||
String sub = null;
|
||||
try {
|
||||
sid = claims.getStringClaim("sid");
|
||||
sub = claims.getSubject();
|
||||
} catch (ParseException e) {
|
||||
log.debug("Failed to parse sid claim: {}", e.getMessage());
|
||||
}
|
||||
|
||||
if (sid == null && sub == null) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Logout token must contain either 'sub' or 'sid' claim");
|
||||
}
|
||||
|
||||
List<OidcSessionEntity> sessions;
|
||||
if (sid != null) {
|
||||
sessions = oidcSessionRepository.findByOidcSessionIdAndRevokedFalse(sid);
|
||||
} else {
|
||||
sessions = oidcSessionRepository.findByOidcSubjectAndOidcIssuerAndRevokedFalse(sub, providerDetails.getIssuerUri());
|
||||
}
|
||||
|
||||
for (OidcSessionEntity session : sessions) {
|
||||
session.setRevoked(true);
|
||||
oidcSessionRepository.save(session);
|
||||
|
||||
var user = session.getUser();
|
||||
refreshTokenRepository.findAllByUserAndRevokedFalse(user).forEach(token -> {
|
||||
token.setRevoked(true);
|
||||
token.setRevocationDate(Instant.now());
|
||||
refreshTokenRepository.save(token);
|
||||
});
|
||||
|
||||
notificationService.sendMessageToUser(
|
||||
user.getUsername(),
|
||||
Topic.SESSION_REVOKED,
|
||||
Map.of("reason", "backchannel_logout")
|
||||
);
|
||||
|
||||
auditService.log(AuditAction.BACKCHANNEL_LOGOUT, "User", user.getId(),
|
||||
"Back-channel logout for user: " + user.getUsername());
|
||||
|
||||
log.info("Back-channel logout: revoked session for user '{}'", user.getUsername());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package org.booklore.config.security.oidc;
|
||||
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.settings.OidcAutoProvisionDetails;
|
||||
import org.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.OidcSessionEntity;
|
||||
import org.booklore.model.enums.AuditAction;
|
||||
import org.booklore.model.enums.ProvisioningMethod;
|
||||
import org.booklore.repository.OidcSessionRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
import org.booklore.service.oidc.OidcGroupMappingService;
|
||||
import org.booklore.service.user.UserProvisioningService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import java.net.URI;
|
||||
import java.text.ParseException;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class OidcAuthService {
|
||||
|
||||
private static final String MOBILE_SCHEME = "booklore://";
|
||||
private static final String OAUTH2_CALLBACK_PATH = "/oauth2-callback";
|
||||
|
||||
private final AppSettingService appSettingService;
|
||||
private final OidcTokenClient oidcTokenClient;
|
||||
private final OidcTokenValidator oidcTokenValidator;
|
||||
private final OidcClaimExtractor oidcClaimExtractor;
|
||||
private final UserRepository userRepository;
|
||||
private final UserProvisioningService userProvisioningService;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final OidcSessionRepository oidcSessionRepository;
|
||||
private final OidcGroupMappingService oidcGroupMappingService;
|
||||
private final AuditService auditService;
|
||||
|
||||
private static final ConcurrentMap<String, ReentrantLock> userLocks = new ConcurrentHashMap<>();
|
||||
|
||||
@Transactional
|
||||
public ResponseEntity<Map<String, String>> exchangeCodeForTokens(
|
||||
String code,
|
||||
String codeVerifier,
|
||||
String redirectUri,
|
||||
String nonce,
|
||||
HttpServletRequest httpRequest
|
||||
) {
|
||||
if (!appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
throw ApiError.FORBIDDEN.createException("OIDC is not enabled");
|
||||
}
|
||||
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
if (providerDetails == null || providerDetails.getIssuerUri() == null) {
|
||||
throw ApiError.FORBIDDEN.createException("OIDC is not properly configured");
|
||||
}
|
||||
|
||||
validateRedirectUri(redirectUri, httpRequest);
|
||||
|
||||
var tokenResponse = oidcTokenClient.exchangeAuthorizationCode(code, codeVerifier, redirectUri, providerDetails);
|
||||
|
||||
String idToken = tokenResponse.idToken();
|
||||
if (idToken == null) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("No ID token received from OIDC provider");
|
||||
}
|
||||
|
||||
var claims = oidcTokenValidator.validateIdToken(
|
||||
idToken,
|
||||
providerDetails.getIssuerUri(),
|
||||
providerDetails.getClientId(),
|
||||
nonce,
|
||||
tokenResponse.accessToken()
|
||||
);
|
||||
|
||||
Map<String, Object> userInfo = Map.of();
|
||||
if (tokenResponse.accessToken() != null) {
|
||||
userInfo = oidcTokenClient.fetchUserInfo(tokenResponse.accessToken(), providerDetails.getIssuerUri());
|
||||
}
|
||||
|
||||
var userClaims = oidcClaimExtractor.extractClaims(claims, providerDetails.getClaimMapping(), userInfo);
|
||||
log.info("OIDC login: authenticating user '{}'", userClaims.username());
|
||||
|
||||
BookLoreUserEntity user = findOrProvisionUser(userClaims, providerDetails.getIssuerUri());
|
||||
|
||||
persistOidcSession(user, userClaims.subject(), providerDetails.getIssuerUri(), tokenResponse, idToken, claims);
|
||||
|
||||
String durationStr = appSettingService.getSettingValue("oidc_session_duration_hours");
|
||||
ResponseEntity<Map<String, String>> response;
|
||||
if (durationStr != null && !durationStr.isBlank()) {
|
||||
try {
|
||||
long durationMs = Long.parseLong(durationStr) * 3_600_000L;
|
||||
response = authenticationService.loginUser(user, durationMs);
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("Invalid OIDC session duration setting: {}", durationStr);
|
||||
response = authenticationService.loginUser(user);
|
||||
}
|
||||
} else {
|
||||
response = authenticationService.loginUser(user);
|
||||
}
|
||||
|
||||
auditService.log(AuditAction.OIDC_LOGIN_SUCCESS, "User", user.getId(), "OIDC login successful for user: " + user.getUsername());
|
||||
return response;
|
||||
}
|
||||
|
||||
private void validateRedirectUri(String redirectUri, HttpServletRequest httpRequest) {
|
||||
if (redirectUri == null || redirectUri.isBlank()) {
|
||||
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
||||
}
|
||||
|
||||
if (redirectUri.startsWith(MOBILE_SCHEME)) {
|
||||
if (!redirectUri.equals(MOBILE_SCHEME + "oauth2-callback")) {
|
||||
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
URI uri = URI.create(redirectUri);
|
||||
String scheme = uri.getScheme();
|
||||
if (!"https".equals(scheme) && !"http".equals(scheme)) {
|
||||
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
||||
}
|
||||
if (uri.getPath() == null || !uri.getPath().endsWith(OAUTH2_CALLBACK_PATH)) {
|
||||
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
||||
}
|
||||
|
||||
String redirectOrigin = scheme + "://" + uri.getHost()
|
||||
+ (uri.getPort() != -1 && uri.getPort() != 443 && uri.getPort() != 80
|
||||
? ":" + uri.getPort() : "");
|
||||
String requestOrigin = resolveRequestOrigin(httpRequest);
|
||||
if (requestOrigin != null && !requestOrigin.equals(redirectOrigin)) {
|
||||
log.warn("OIDC redirect URI origin mismatch: redirect={}, request={}", redirectOrigin, requestOrigin);
|
||||
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveRequestOrigin(HttpServletRequest request) {
|
||||
String origin = request.getHeader("Origin");
|
||||
if (origin != null && !origin.isBlank()) {
|
||||
return origin.replaceAll("/+$", "");
|
||||
}
|
||||
String scheme = request.getScheme();
|
||||
String host = request.getServerName();
|
||||
int port = request.getServerPort();
|
||||
if ((port == 80 && "http".equals(scheme)) || (port == 443 && "https".equals(scheme))) {
|
||||
return scheme + "://" + host;
|
||||
}
|
||||
return scheme + "://" + host + ":" + port;
|
||||
}
|
||||
|
||||
public void validateAppRedirectUri(String appRedirectUri) {
|
||||
if (appRedirectUri == null || !appRedirectUri.startsWith(MOBILE_SCHEME)) {
|
||||
throw ApiError.OIDC_INVALID_REDIRECT_URI.createException();
|
||||
}
|
||||
}
|
||||
|
||||
private void persistOidcSession(BookLoreUserEntity user, String subject, String issuer,
|
||||
OidcTokenClient.TokenResponse tokenResponse, String rawIdToken,
|
||||
JWTClaimsSet claims) {
|
||||
String sessionId = null;
|
||||
try {
|
||||
sessionId = claims.getStringClaim("sid");
|
||||
} catch (ParseException e) {
|
||||
log.debug("No 'sid' claim in ID token");
|
||||
}
|
||||
|
||||
var session = OidcSessionEntity.builder()
|
||||
.user(user)
|
||||
.oidcSubject(subject)
|
||||
.oidcIssuer(issuer)
|
||||
.oidcSessionId(sessionId)
|
||||
.idTokenHint(rawIdToken)
|
||||
.build();
|
||||
|
||||
oidcSessionRepository.save(session);
|
||||
log.debug("Persisted OIDC session for user '{}' (subject: {})", user.getUsername(), subject);
|
||||
}
|
||||
|
||||
private BookLoreUserEntity findOrProvisionUser(OidcClaimExtractor.OidcUserClaims userClaims, String issuerUri) {
|
||||
OidcAutoProvisionDetails provisionDetails = appSettingService.getAppSettings().getOidcAutoProvisionDetails();
|
||||
boolean autoProvision = provisionDetails != null && provisionDetails.isEnableAutoProvisioning();
|
||||
boolean allowLocalLinking = provisionDetails != null && provisionDetails.isAllowLocalAccountLinking();
|
||||
|
||||
return userRepository.findByOidcIssuerAndOidcSubject(issuerUri, userClaims.subject())
|
||||
.map(user -> syncExistingUser(user, userClaims, issuerUri))
|
||||
.or(() -> userRepository.findByUsername(userClaims.username())
|
||||
.filter(user -> user.getProvisioningMethod() == ProvisioningMethod.OIDC || allowLocalLinking)
|
||||
.map(user -> linkExistingUser(user, userClaims, issuerUri)))
|
||||
.orElseGet(() -> {
|
||||
if (!autoProvision) {
|
||||
log.warn("OIDC user '{}' not found and auto-provisioning is disabled", userClaims.username());
|
||||
throw ApiError.OIDC_USER_NOT_PROVISIONED.createException(userClaims.username());
|
||||
}
|
||||
|
||||
ReentrantLock lock = userLocks.computeIfAbsent(userClaims.username(), _ -> new ReentrantLock());
|
||||
lock.lock();
|
||||
try {
|
||||
return userRepository.findByOidcIssuerAndOidcSubject(issuerUri, userClaims.subject())
|
||||
.or(() -> userRepository.findByUsername(userClaims.username()))
|
||||
.orElseGet(() -> {
|
||||
log.info("OIDC: provisioning new user '{}'", userClaims.username());
|
||||
BookLoreUserEntity newUser = userProvisioningService.provisionOidcUser(
|
||||
userClaims.username(),
|
||||
userClaims.email(),
|
||||
userClaims.name(),
|
||||
userClaims.subject(),
|
||||
issuerUri,
|
||||
userClaims.pictureUrl(),
|
||||
provisionDetails
|
||||
);
|
||||
oidcGroupMappingService.syncUserGroups(newUser, userClaims.groups());
|
||||
auditService.log(AuditAction.OIDC_USER_PROVISIONED, "User", newUser.getId(),
|
||||
"OIDC auto-provisioned user: " + newUser.getUsername());
|
||||
return newUser;
|
||||
});
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private BookLoreUserEntity linkExistingUser(BookLoreUserEntity user, OidcClaimExtractor.OidcUserClaims userClaims, String issuerUri) {
|
||||
if (user.getProvisioningMethod() != ProvisioningMethod.OIDC) {
|
||||
log.info("OIDC login: linking local user '{}' (was {}) to OIDC identity",
|
||||
user.getUsername(), user.getProvisioningMethod());
|
||||
user.setProvisioningMethod(ProvisioningMethod.OIDC);
|
||||
auditService.log(AuditAction.OIDC_ACCOUNT_LINKED, "User", user.getId(),
|
||||
"Local account linked to OIDC for user: " + user.getUsername());
|
||||
}
|
||||
return syncExistingUser(user, userClaims, issuerUri);
|
||||
}
|
||||
|
||||
private BookLoreUserEntity syncExistingUser(BookLoreUserEntity user, OidcClaimExtractor.OidcUserClaims userClaims, String issuerUri) {
|
||||
boolean changed = false;
|
||||
|
||||
if (userClaims.email() != null && !userClaims.email().equals(user.getEmail())) {
|
||||
user.setEmail(userClaims.email());
|
||||
changed = true;
|
||||
}
|
||||
if (userClaims.name() != null && !userClaims.name().equals(user.getName())) {
|
||||
user.setName(userClaims.name());
|
||||
changed = true;
|
||||
}
|
||||
if (userClaims.pictureUrl() != null && !userClaims.pictureUrl().equals(user.getAvatarUrl())) {
|
||||
user.setAvatarUrl(userClaims.pictureUrl());
|
||||
changed = true;
|
||||
}
|
||||
if ((user.getOidcSubject() == null || user.getOidcSubject().isBlank()) && userClaims.subject() != null) {
|
||||
user.setOidcSubject(userClaims.subject());
|
||||
changed = true;
|
||||
}
|
||||
if ((user.getOidcIssuer() == null || user.getOidcIssuer().isBlank()) && issuerUri != null) {
|
||||
user.setOidcIssuer(issuerUri);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
log.info("OIDC sync: saving updated user '{}'", user.getUsername());
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
oidcGroupMappingService.syncUserGroups(user, userClaims.groups());
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.booklore.config.security.oidc;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record OidcCallbackRequest(
|
||||
@NotBlank String code,
|
||||
@NotBlank String codeVerifier,
|
||||
@NotBlank String redirectUri,
|
||||
@NotBlank String nonce,
|
||||
@NotBlank String state
|
||||
) {}
|
||||
@@ -0,0 +1,109 @@
|
||||
package org.booklore.config.security.oidc;
|
||||
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class OidcClaimExtractor {
|
||||
|
||||
public record OidcUserClaims(
|
||||
String username,
|
||||
String email,
|
||||
String name,
|
||||
String subject,
|
||||
String pictureUrl,
|
||||
List<String> groups
|
||||
) {}
|
||||
|
||||
public OidcUserClaims extractClaims(JWTClaimsSet claims, OidcProviderDetails.ClaimMapping mapping, Map<String, Object> userInfo) {
|
||||
String username = getStringClaim(claims, userInfo, mapping.getUsername(), "preferred_username");
|
||||
String email = getStringClaim(claims, userInfo, mapping.getEmail(), "email");
|
||||
String name = getStringClaim(claims, userInfo, mapping.getName(), "name");
|
||||
String subject = claims.getSubject();
|
||||
String pictureUrl = getStringClaim(claims, userInfo, null, "picture");
|
||||
List<String> groups = getListClaim(claims, userInfo, mapping.getGroups(), "groups");
|
||||
|
||||
if (username == null || username.isBlank()) {
|
||||
username = email != null ? email : subject;
|
||||
}
|
||||
|
||||
return new OidcUserClaims(username, email, name, subject, pictureUrl, groups);
|
||||
}
|
||||
|
||||
private List<String> getListClaim(JWTClaimsSet claims, Map<String, Object> userInfo, String primaryClaim, String fallbackClaim) {
|
||||
List<String> value = tryGetListClaim(claims, primaryClaim);
|
||||
if (value == null && fallbackClaim != null && !fallbackClaim.equals(primaryClaim)) {
|
||||
value = tryGetListClaim(claims, fallbackClaim);
|
||||
}
|
||||
if (value == null) {
|
||||
value = tryGetUserInfoListClaim(userInfo, primaryClaim);
|
||||
}
|
||||
if (value == null && fallbackClaim != null && !fallbackClaim.equals(primaryClaim)) {
|
||||
value = tryGetUserInfoListClaim(userInfo, fallbackClaim);
|
||||
}
|
||||
return value != null ? value : List.of();
|
||||
}
|
||||
|
||||
private List<String> tryGetListClaim(JWTClaimsSet claims, String claimName) {
|
||||
if (claimName == null || claimName.isBlank()) return null;
|
||||
try {
|
||||
List<String> list = claims.getStringListClaim(claimName);
|
||||
return list != null && !list.isEmpty() ? list : null;
|
||||
} catch (ParseException e) {
|
||||
log.debug("Failed to parse list claim '{}': {}", claimName, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<String> tryGetUserInfoListClaim(Map<String, Object> userInfo, String claimName) {
|
||||
if (claimName == null || claimName.isBlank() || userInfo == null) return null;
|
||||
Object value = userInfo.get(claimName);
|
||||
if (value instanceof List<?> list) {
|
||||
List<String> result = new ArrayList<>();
|
||||
for (Object item : list) {
|
||||
if (item instanceof String s) result.add(s);
|
||||
}
|
||||
return result.isEmpty() ? null : result;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String getStringClaim(JWTClaimsSet claims, Map<String, Object> userInfo, String primaryClaim, String fallbackClaim) {
|
||||
String value = tryGetClaim(claims, primaryClaim);
|
||||
if (value == null && fallbackClaim != null && !fallbackClaim.equals(primaryClaim)) {
|
||||
value = tryGetClaim(claims, fallbackClaim);
|
||||
}
|
||||
if (value == null) {
|
||||
value = tryGetUserInfoClaim(userInfo, primaryClaim);
|
||||
}
|
||||
if (value == null && fallbackClaim != null && !fallbackClaim.equals(primaryClaim)) {
|
||||
value = tryGetUserInfoClaim(userInfo, fallbackClaim);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private String tryGetClaim(JWTClaimsSet claims, String claimName) {
|
||||
if (claimName == null || claimName.isBlank()) return null;
|
||||
try {
|
||||
return claims.getStringClaim(claimName);
|
||||
} catch (ParseException e) {
|
||||
log.debug("Failed to parse claim '{}': {}", claimName, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String tryGetUserInfoClaim(Map<String, Object> userInfo, String claimName) {
|
||||
if (claimName == null || claimName.isBlank() || userInfo == null) return null;
|
||||
Object value = userInfo.get(claimName);
|
||||
return value instanceof String s ? s : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package org.booklore.config.security.oidc;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class OidcDiscoveryService {
|
||||
|
||||
private static final Pattern TRAILING_SLASH = Pattern.compile("/+$");
|
||||
private static final long CACHE_TTL_MS = 3_600_000; // 1 hour
|
||||
private static final int CONNECT_TIMEOUT_MS = 10_000;
|
||||
private static final int READ_TIMEOUT_MS = 10_000;
|
||||
|
||||
private final ConcurrentMap<String, CachedDiscovery> cache = new ConcurrentHashMap<>();
|
||||
|
||||
public record DiscoveryDocument(
|
||||
String issuer,
|
||||
String authorizationEndpoint,
|
||||
String tokenEndpoint,
|
||||
URI jwksUri,
|
||||
String userinfoEndpoint,
|
||||
String endSessionEndpoint,
|
||||
List<String> scopesSupported,
|
||||
List<String> responseTypesSupported,
|
||||
List<String> codeChallengeMethodsSupported,
|
||||
Boolean backchannelLogoutSupported
|
||||
) {}
|
||||
|
||||
private record CachedDiscovery(DiscoveryDocument document, Instant fetchedAt) {
|
||||
boolean isExpired() {
|
||||
return Instant.now().isAfter(fetchedAt.plusMillis(CACHE_TTL_MS));
|
||||
}
|
||||
}
|
||||
|
||||
public DiscoveryDocument discover(String issuerUri) {
|
||||
String normalizedIssuer = TRAILING_SLASH.matcher(issuerUri).replaceAll("");
|
||||
|
||||
return cache.compute(normalizedIssuer, (key, cached) -> {
|
||||
if (cached != null && !cached.isExpired()) {
|
||||
return cached;
|
||||
}
|
||||
return new CachedDiscovery(fetchDiscoveryDocument(key), Instant.now());
|
||||
}).document();
|
||||
}
|
||||
|
||||
public void invalidate(String issuerUri) {
|
||||
cache.remove(TRAILING_SLASH.matcher(issuerUri).replaceAll(""));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private DiscoveryDocument fetchDiscoveryDocument(String issuerUri) {
|
||||
String discoveryUrl = issuerUri + "/.well-known/openid-configuration";
|
||||
log.info("Fetching OIDC discovery document from {}", discoveryUrl);
|
||||
|
||||
var factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout(CONNECT_TIMEOUT_MS);
|
||||
factory.setReadTimeout(READ_TIMEOUT_MS);
|
||||
|
||||
var restClient = RestClient.builder().requestFactory(factory).build();
|
||||
|
||||
Map<String, Object> doc = restClient.get()
|
||||
.uri(discoveryUrl)
|
||||
.retrieve()
|
||||
.body(Map.class);
|
||||
|
||||
if (doc == null) {
|
||||
throw new IllegalStateException("Failed to fetch OIDC discovery document from " + discoveryUrl);
|
||||
}
|
||||
|
||||
String jwksUriStr = (String) doc.get("jwks_uri");
|
||||
if (jwksUriStr == null || jwksUriStr.isBlank()) {
|
||||
throw new IllegalStateException("jwks_uri not found in discovery document");
|
||||
}
|
||||
|
||||
return new DiscoveryDocument(
|
||||
(String) doc.get("issuer"),
|
||||
(String) doc.get("authorization_endpoint"),
|
||||
(String) doc.get("token_endpoint"),
|
||||
URI.create(jwksUriStr),
|
||||
(String) doc.get("userinfo_endpoint"),
|
||||
(String) doc.get("end_session_endpoint"),
|
||||
(List<String>) doc.get("scopes_supported"),
|
||||
(List<String>) doc.get("response_types_supported"),
|
||||
(List<String>) doc.get("code_challenge_methods_supported"),
|
||||
doc.get("backchannel_logout_supported") instanceof Boolean b ? b : null
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package org.booklore.config.security.oidc;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
|
||||
@Service
|
||||
public class OidcStateService {
|
||||
|
||||
private static final Cache<String, Boolean> STATE_CACHE = Caffeine.newBuilder()
|
||||
.expireAfterWrite(Duration.ofMinutes(5))
|
||||
.maximumSize(500)
|
||||
.build();
|
||||
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
public String generateState() {
|
||||
byte[] bytes = new byte[32];
|
||||
SECURE_RANDOM.nextBytes(bytes);
|
||||
String state = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
STATE_CACHE.put(state, Boolean.TRUE);
|
||||
return state;
|
||||
}
|
||||
|
||||
public void validateAndConsume(String state) {
|
||||
if (state == null || state.isBlank()) {
|
||||
throw ApiError.OIDC_INVALID_STATE.createException();
|
||||
}
|
||||
Boolean valid = STATE_CACHE.getIfPresent(state);
|
||||
if (valid == null) {
|
||||
throw ApiError.OIDC_INVALID_STATE.createException();
|
||||
}
|
||||
STATE_CACHE.invalidate(state);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package org.booklore.config.security.oidc;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class OidcTokenClient {
|
||||
|
||||
private final OidcDiscoveryService discoveryService;
|
||||
private final RestTemplate oidcRestTemplate;
|
||||
|
||||
public record TokenResponse(
|
||||
String accessToken,
|
||||
String idToken,
|
||||
String refreshToken,
|
||||
String tokenType,
|
||||
Integer expiresIn
|
||||
) {}
|
||||
|
||||
public TokenResponse exchangeAuthorizationCode(String code, String codeVerifier, String redirectUri, OidcProviderDetails providerDetails) {
|
||||
var discovery = discoveryService.discover(providerDetails.getIssuerUri());
|
||||
String tokenEndpoint = discovery.tokenEndpoint();
|
||||
|
||||
if (tokenEndpoint == null || tokenEndpoint.isBlank()) {
|
||||
throw ApiError.OIDC_PROVIDER_UNREACHABLE.createException("Token endpoint not found in discovery document");
|
||||
}
|
||||
|
||||
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
|
||||
body.add("grant_type", "authorization_code");
|
||||
body.add("client_id", providerDetails.getClientId());
|
||||
if (providerDetails.getClientSecret() != null && !providerDetails.getClientSecret().isBlank()) {
|
||||
body.add("client_secret", providerDetails.getClientSecret());
|
||||
}
|
||||
body.add("code", code);
|
||||
body.add("redirect_uri", redirectUri);
|
||||
body.add("code_verifier", codeVerifier);
|
||||
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> response = oidcRestTemplate
|
||||
.postForObject(tokenEndpoint, new HttpEntity<>(body, headers), Map.class);
|
||||
|
||||
if (response == null) {
|
||||
throw ApiError.OIDC_TOKEN_EXCHANGE_FAILED.createException("Empty response from token endpoint");
|
||||
}
|
||||
|
||||
if (response.containsKey("error")) {
|
||||
String error = (String) response.get("error");
|
||||
String description = (String) response.getOrDefault("error_description", "");
|
||||
log.error("OIDC token exchange error: {} - {}", error, description);
|
||||
throw ApiError.OIDC_TOKEN_EXCHANGE_FAILED.createException(error + " " + description);
|
||||
}
|
||||
|
||||
return new TokenResponse(
|
||||
(String) response.get("access_token"),
|
||||
(String) response.get("id_token"),
|
||||
(String) response.get("refresh_token"),
|
||||
(String) response.get("token_type"),
|
||||
response.get("expires_in") instanceof Number n ? n.intValue() : null
|
||||
);
|
||||
} catch (org.springframework.web.client.RestClientException e) {
|
||||
log.error("OIDC token exchange failed: {}", e.getMessage());
|
||||
throw ApiError.OIDC_PROVIDER_UNREACHABLE.createException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String, Object> fetchUserInfo(String accessToken, String issuerUri) {
|
||||
var discovery = discoveryService.discover(issuerUri);
|
||||
String userinfoEndpoint = discovery.userinfoEndpoint();
|
||||
|
||||
if (userinfoEndpoint == null || userinfoEndpoint.isBlank()) {
|
||||
log.debug("No userinfo endpoint available, skipping userinfo fetch");
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setBearerAuth(accessToken);
|
||||
|
||||
var response = oidcRestTemplate
|
||||
.exchange(userinfoEndpoint, HttpMethod.GET, new HttpEntity<>(headers), Map.class);
|
||||
|
||||
return response.getBody() != null ? response.getBody() : Map.of();
|
||||
} catch (org.springframework.web.client.RestClientException e) {
|
||||
log.warn("Failed to fetch userinfo: {}", e.getMessage());
|
||||
return Map.of();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package org.booklore.config.security.oidc;
|
||||
|
||||
import com.nimbusds.jose.JOSEObjectType;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.jwk.source.DefaultJWKSetCache;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
|
||||
import com.nimbusds.jose.proc.JWSKeySelector;
|
||||
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
|
||||
import com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import com.nimbusds.jose.util.DefaultResourceRetriever;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
|
||||
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.util.FileUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class OidcTokenValidator {
|
||||
|
||||
private static final int CLOCK_SKEW_SECONDS = 30;
|
||||
private static final int MAX_IAT_AGE_SECONDS = 300;
|
||||
private static final long JWKS_CACHE_TTL_MS = 21_600_000; // 6 hours
|
||||
private static final long JWKS_REFRESH_MS = 3_600_000; // 1 hour
|
||||
|
||||
private final OidcDiscoveryService discoveryService;
|
||||
|
||||
private final ConcurrentMap<String, ConfigurableJWTProcessor<SecurityContext>> processorCache = new ConcurrentHashMap<>();
|
||||
|
||||
public JWTClaimsSet validateIdToken(String idTokenStr, String issuerUri, String clientId, String expectedNonce, String accessToken) {
|
||||
try {
|
||||
var processor = getOrCreateProcessor(issuerUri);
|
||||
JWTClaimsSet claims = processor.process(idTokenStr, null);
|
||||
|
||||
validateIssuer(claims, issuerUri);
|
||||
validateAudience(claims, clientId);
|
||||
validateAuthorizedParty(claims, clientId);
|
||||
validateExpiration(claims);
|
||||
validateIssuedAt(claims);
|
||||
validateNonce(claims, expectedNonce);
|
||||
validateAccessTokenHash(claims, accessToken, idTokenStr);
|
||||
|
||||
return claims;
|
||||
} catch (org.booklore.exception.APIException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.warn("OIDC ID token validation failed: {}", e.getMessage());
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("Invalid OIDC ID token");
|
||||
}
|
||||
}
|
||||
|
||||
public JWTClaimsSet validateIdToken(String idTokenStr, String issuerUri, String clientId, String expectedNonce) {
|
||||
return validateIdToken(idTokenStr, issuerUri, clientId, expectedNonce, null);
|
||||
}
|
||||
|
||||
public void invalidateProcessor(String issuerUri) {
|
||||
processorCache.remove(issuerUri);
|
||||
}
|
||||
|
||||
private ConfigurableJWTProcessor<SecurityContext> getOrCreateProcessor(String issuerUri) {
|
||||
return processorCache.computeIfAbsent(issuerUri, this::buildProcessor);
|
||||
}
|
||||
|
||||
private ConfigurableJWTProcessor<SecurityContext> buildProcessor(String issuerUri) {
|
||||
var discovery = discoveryService.discover(issuerUri);
|
||||
URI jwksUri = discovery.jwksUri();
|
||||
|
||||
var resourceRetriever = new DefaultResourceRetriever(10_000, 10_000);
|
||||
var jwkSetCache = new DefaultJWKSetCache(JWKS_CACHE_TTL_MS, JWKS_REFRESH_MS, TimeUnit.MILLISECONDS);
|
||||
JWKSource<SecurityContext> jwkSource = new RemoteJWKSet<>(uriToUrl(jwksUri), resourceRetriever, jwkSetCache);
|
||||
|
||||
Set<JWSAlgorithm> jwsAlgs = new HashSet<>();
|
||||
jwsAlgs.addAll(JWSAlgorithm.Family.RSA);
|
||||
jwsAlgs.addAll(JWSAlgorithm.Family.EC);
|
||||
|
||||
JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(jwsAlgs, jwkSource);
|
||||
ConfigurableJWTProcessor<SecurityContext> processor = new DefaultJWTProcessor<>();
|
||||
processor.setJWSKeySelector(keySelector);
|
||||
processor.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(
|
||||
JOSEObjectType.JWT, new JOSEObjectType("logout+jwt"), null));
|
||||
|
||||
return processor;
|
||||
}
|
||||
|
||||
private void validateIssuer(JWTClaimsSet claims, String expectedIssuer) {
|
||||
String issuer = claims.getIssuer();
|
||||
String normalizedExpected = FileUtils.trimTrailingSlashes(expectedIssuer);
|
||||
String normalizedActual = issuer != null ? FileUtils.trimTrailingSlashes(issuer) : "";
|
||||
|
||||
if (!normalizedExpected.equals(normalizedActual)) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("ID token issuer mismatch");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateAudience(JWTClaimsSet claims, String clientId) {
|
||||
if (claims.getAudience() == null || !claims.getAudience().contains(clientId)) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("ID token audience does not contain client_id");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateAuthorizedParty(JWTClaimsSet claims, String clientId) {
|
||||
if (claims.getAudience() != null && claims.getAudience().size() > 1) {
|
||||
try {
|
||||
String azp = claims.getStringClaim("azp");
|
||||
if (azp != null && !azp.equals(clientId)) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("ID token authorized party mismatch");
|
||||
}
|
||||
} catch (java.text.ParseException e) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("Failed to parse azp claim");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateExpiration(JWTClaimsSet claims) {
|
||||
if (claims.getExpirationTime() == null) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("ID token missing expiration claim");
|
||||
}
|
||||
Instant exp = claims.getExpirationTime().toInstant().plusSeconds(CLOCK_SKEW_SECONDS);
|
||||
if (Instant.now().isAfter(exp)) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("ID token has expired");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateIssuedAt(JWTClaimsSet claims) {
|
||||
if (claims.getIssueTime() == null) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("ID token missing iat claim");
|
||||
}
|
||||
Instant iat = claims.getIssueTime().toInstant();
|
||||
if (Instant.now().isAfter(iat.plusSeconds(MAX_IAT_AGE_SECONDS + CLOCK_SKEW_SECONDS))) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("ID token was issued too long ago");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateNonce(JWTClaimsSet claims, String expectedNonce) {
|
||||
try {
|
||||
String tokenNonce = claims.getStringClaim("nonce");
|
||||
if (!expectedNonce.equals(tokenNonce)) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("ID token nonce mismatch");
|
||||
}
|
||||
} catch (java.text.ParseException e) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("Failed to parse nonce claim");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateAccessTokenHash(JWTClaimsSet claims, String accessToken, String idTokenStr) {
|
||||
try {
|
||||
String atHash = claims.getStringClaim("at_hash");
|
||||
if (atHash == null || accessToken == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
SignedJWT signedJWT = SignedJWT.parse(idTokenStr);
|
||||
String alg = signedJWT.getHeader().getAlgorithm().getName();
|
||||
String hashAlgorithm = mapAlgToHashAlgorithm(alg);
|
||||
|
||||
MessageDigest digest = MessageDigest.getInstance(hashAlgorithm);
|
||||
byte[] hash = digest.digest(accessToken.getBytes(StandardCharsets.US_ASCII));
|
||||
byte[] leftHalf = new byte[hash.length / 2];
|
||||
System.arraycopy(hash, 0, leftHalf, 0, leftHalf.length);
|
||||
|
||||
String computed = Base64.getUrlEncoder().withoutPadding().encodeToString(leftHalf);
|
||||
if (!computed.equals(atHash)) {
|
||||
throw ApiError.OIDC_INVALID_TOKEN.createException("ID token at_hash mismatch");
|
||||
}
|
||||
} catch (org.booklore.exception.APIException e) {
|
||||
throw e;
|
||||
} catch (java.text.ParseException | NoSuchAlgorithmException e) {
|
||||
log.warn("Failed to validate at_hash: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private String mapAlgToHashAlgorithm(String alg) {
|
||||
return switch (alg) {
|
||||
case "RS256", "ES256", "PS256" -> "SHA-256";
|
||||
case "RS384", "ES384", "PS384" -> "SHA-384";
|
||||
case "RS512", "ES512", "PS512" -> "SHA-512";
|
||||
default -> "SHA-256";
|
||||
};
|
||||
}
|
||||
|
||||
public JWTClaimsSet validateLogoutToken(String logoutTokenStr, String issuerUri, String clientId) {
|
||||
try {
|
||||
var processor = getOrCreateProcessor(issuerUri);
|
||||
JWTClaimsSet claims = processor.process(logoutTokenStr, null);
|
||||
|
||||
validateIssuer(claims, issuerUri);
|
||||
validateAudience(claims, clientId);
|
||||
validateIssuedAt(claims);
|
||||
if (claims.getExpirationTime() != null) {
|
||||
validateExpiration(claims);
|
||||
}
|
||||
|
||||
var events = claims.getJSONObjectClaim("events");
|
||||
if (events == null || !events.containsKey("http://schemas.openid.net/event/backchannel-logout")) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Logout token missing backchannel-logout event claim");
|
||||
}
|
||||
|
||||
if (claims.getClaim("nonce") != null) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Logout token must not contain a nonce claim");
|
||||
}
|
||||
|
||||
return claims;
|
||||
} catch (org.booklore.exception.APIException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.warn("OIDC logout token validation failed: {}", e.getMessage());
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid OIDC logout token");
|
||||
}
|
||||
}
|
||||
|
||||
private static java.net.URL uriToUrl(URI uri) {
|
||||
try {
|
||||
return uri.toURL();
|
||||
} catch (java.net.MalformedURLException e) {
|
||||
throw new IllegalStateException("Invalid JWKS URI: " + uri, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package org.booklore.config.security.service;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.enums.AuditAction;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class AuthRateLimitService {
|
||||
|
||||
private static final int MAX_ATTEMPTS = 5;
|
||||
|
||||
private final Cache<String, AtomicInteger> attemptCache;
|
||||
private final AuditService auditService;
|
||||
|
||||
public AuthRateLimitService(AuditService auditService) {
|
||||
this.auditService = auditService;
|
||||
this.attemptCache = Caffeine.newBuilder()
|
||||
.maximumSize(1000)
|
||||
.expireAfterWrite(Duration.ofMinutes(15))
|
||||
.build();
|
||||
}
|
||||
|
||||
// --- Login rate limiting ---
|
||||
|
||||
public void checkLoginRateLimit(String 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:" + ip);
|
||||
}
|
||||
|
||||
public void recordFailedLoginAttemptByUsername(String username) {
|
||||
String normalizedUsername = normalizeUsername(username);
|
||||
recordFailedAttempt("login:user:" + normalizedUsername);
|
||||
}
|
||||
|
||||
public void resetLoginAttempts(String ip) {
|
||||
resetAttempts("login:ip:" + ip);
|
||||
}
|
||||
|
||||
public void resetLoginAttemptsByUsername(String username) {
|
||||
String normalizedUsername = normalizeUsername(username);
|
||||
resetAttempts("login:user:" + normalizedUsername);
|
||||
}
|
||||
|
||||
// --- Refresh token rate limiting ---
|
||||
|
||||
public void checkRefreshRateLimit(String ip) {
|
||||
checkRateLimit("refresh:" + ip, AuditAction.REFRESH_RATE_LIMITED, "Refresh rate limited for IP: " + ip);
|
||||
}
|
||||
|
||||
public void recordFailedRefreshAttempt(String ip) {
|
||||
recordFailedAttempt("refresh:" + ip);
|
||||
}
|
||||
|
||||
public void resetRefreshAttempts(String ip) {
|
||||
resetAttempts("refresh:" + ip);
|
||||
}
|
||||
|
||||
// --- Shared internals ---
|
||||
|
||||
private void checkRateLimit(String key, AuditAction action, String message) {
|
||||
AtomicInteger attempts = attemptCache.getIfPresent(key);
|
||||
if (attempts != null && attempts.get() >= MAX_ATTEMPTS) {
|
||||
auditService.log(action, message);
|
||||
throw ApiError.RATE_LIMITED.createException();
|
||||
}
|
||||
}
|
||||
|
||||
private void recordFailedAttempt(String key) {
|
||||
attemptCache.get(key, k -> new AtomicInteger(0)).incrementAndGet();
|
||||
}
|
||||
|
||||
private void resetAttempts(String key) {
|
||||
attemptCache.invalidate(key);
|
||||
}
|
||||
|
||||
private String normalizeUsername(String username) {
|
||||
return username != null ? username.trim().toLowerCase() : "";
|
||||
}
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
package org.booklore.config.security.service;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.booklore.config.AppProperties;
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import org.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.request.UserLoginRequest;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.RefreshTokenEntity;
|
||||
import org.booklore.model.enums.ProvisioningMethod;
|
||||
import org.booklore.model.enums.UserPermission;
|
||||
import org.booklore.repository.RefreshTokenRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.service.user.DefaultSettingInitializer;
|
||||
import org.booklore.service.user.UserProvisioningService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.booklore.model.enums.AuditAction;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
import org.booklore.util.RequestUtils;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class AuthenticationService {
|
||||
|
||||
private String dummyPasswordHash;
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final UserRepository userRepository;
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final UserProvisioningService userProvisioningService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtUtils jwtUtils;
|
||||
private final DefaultSettingInitializer defaultSettingInitializer;
|
||||
private final AuditService auditService;
|
||||
private final AuthRateLimitService authRateLimitService;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public AuthenticationService(
|
||||
AppProperties appProperties,
|
||||
UserRepository userRepository,
|
||||
RefreshTokenRepository refreshTokenRepository,
|
||||
UserProvisioningService userProvisioningService,
|
||||
PasswordEncoder passwordEncoder,
|
||||
JwtUtils jwtUtils,
|
||||
DefaultSettingInitializer defaultSettingInitializer,
|
||||
AuditService auditService,
|
||||
AuthRateLimitService authRateLimitService,
|
||||
@Lazy AppSettingService appSettingService
|
||||
) {
|
||||
this.appProperties = appProperties;
|
||||
this.userRepository = userRepository;
|
||||
this.refreshTokenRepository = refreshTokenRepository;
|
||||
this.userProvisioningService = userProvisioningService;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.jwtUtils = jwtUtils;
|
||||
this.defaultSettingInitializer = defaultSettingInitializer;
|
||||
this.auditService = auditService;
|
||||
this.authRateLimitService = authRateLimitService;
|
||||
this.appSettingService = appSettingService;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void initDummyHash() {
|
||||
this.dummyPasswordHash = passwordEncoder.encode("_dummy_placeholder_for_timing_equalization_");
|
||||
}
|
||||
|
||||
public BookLoreUser getAuthenticatedUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null) {
|
||||
return null;
|
||||
}
|
||||
Object principal = authentication.getPrincipal();
|
||||
if (principal instanceof BookLoreUser user) {
|
||||
if (user.getId() != null && user.getId() != -1L) {
|
||||
defaultSettingInitializer.ensureDefaultSettings(user);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
throw new IllegalStateException("Authenticated principal is not of type BookLoreUser");
|
||||
}
|
||||
|
||||
public BookLoreUser getSystemUser() {
|
||||
return createSystemUser();
|
||||
}
|
||||
|
||||
private BookLoreUser createSystemUser() {
|
||||
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
|
||||
for (UserPermission permission : UserPermission.values()) {
|
||||
permission.setInDto(permissions, true);
|
||||
}
|
||||
|
||||
return BookLoreUser.builder()
|
||||
.id(-1L)
|
||||
.username("system")
|
||||
.name("System User")
|
||||
.email("system@booklore.internal")
|
||||
.provisioningMethod(ProvisioningMethod.LOCAL)
|
||||
.isDefaultPassword(false)
|
||||
.permissions(permissions)
|
||||
.assignedLibraries(List.of())
|
||||
.userSettings(new BookLoreUser.UserSettings())
|
||||
.build();
|
||||
}
|
||||
|
||||
public OpdsUserDetails getOpdsUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof OpdsUserDetails opdsUser) {
|
||||
return opdsUser;
|
||||
}
|
||||
throw new IllegalStateException("No OPDS user authenticated");
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
|
||||
if (appSettingService.getAppSettings().isOidcForceOnlyMode()) {
|
||||
BookLoreUserEntity oidcCheckUser = userRepository.findByUsername(loginRequest.getUsername()).orElse(null);
|
||||
if (oidcCheckUser == null || !oidcCheckUser.getPermissions().isPermissionAdmin()) {
|
||||
throw ApiError.OIDC_ONLY_MODE.createException();
|
||||
}
|
||||
}
|
||||
|
||||
String ip = RequestUtils.getCurrentRequest().getRemoteAddr();
|
||||
String username = loginRequest.getUsername();
|
||||
authRateLimitService.checkLoginRateLimit(ip);
|
||||
authRateLimitService.checkLoginRateLimitByUsername(username);
|
||||
|
||||
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);
|
||||
authRateLimitService.recordFailedLoginAttemptByUsername(username);
|
||||
throw ApiError.INVALID_CREDENTIALS.createException();
|
||||
}
|
||||
|
||||
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
|
||||
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);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ResponseEntity<Map<String, String>> loginRemote(String name, String username, String email, String groups) {
|
||||
if (username == null || username.isEmpty()) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Remote-User header is missing");
|
||||
}
|
||||
|
||||
Optional<BookLoreUserEntity> user = userRepository.findByUsername(username);
|
||||
if (user.isEmpty() && appProperties.getRemoteAuth().isCreateNewUsers()) {
|
||||
user = Optional.of(userProvisioningService.provisionRemoteUserFromHeaders(name, username, email, groups));
|
||||
}
|
||||
|
||||
if (user.isEmpty()) {
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("User not found and remote user creation is disabled");
|
||||
}
|
||||
|
||||
return loginUser(user.get());
|
||||
}
|
||||
|
||||
public ResponseEntity<Map<String, String>> loginUser(BookLoreUserEntity user) {
|
||||
return loginUser(user, null);
|
||||
}
|
||||
|
||||
public ResponseEntity<Map<String, String>> loginUser(BookLoreUserEntity user, Long customRefreshTokenExpirationMs) {
|
||||
String accessToken = jwtUtils.generateAccessToken(user);
|
||||
String refreshToken = jwtUtils.generateRefreshToken(user);
|
||||
|
||||
long expirationMs = customRefreshTokenExpirationMs != null ? customRefreshTokenExpirationMs : jwtUtils.getRefreshTokenExpirationMs();
|
||||
|
||||
RefreshTokenEntity refreshTokenEntity = RefreshTokenEntity.builder()
|
||||
.user(user)
|
||||
.token(refreshToken)
|
||||
.expiryDate(Instant.now().plusMillis(expirationMs))
|
||||
.revoked(false)
|
||||
.build();
|
||||
|
||||
refreshTokenRepository.save(refreshTokenEntity);
|
||||
auditService.log(AuditAction.LOGIN_SUCCESS, "User", user.getId(), "Login successful for user: " + user.getUsername());
|
||||
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"accessToken", accessToken,
|
||||
"refreshToken", refreshTokenEntity.getToken(),
|
||||
"isDefaultPassword", String.valueOf(user.isDefaultPassword())
|
||||
));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ResponseEntity<Map<String, String>> refreshToken(String token) {
|
||||
String ip = RequestUtils.getCurrentRequest().getRemoteAddr();
|
||||
authRateLimitService.checkRefreshRateLimit(ip);
|
||||
|
||||
RefreshTokenEntity storedToken = refreshTokenRepository.findByToken(token).orElseThrow(() -> {
|
||||
authRateLimitService.recordFailedRefreshAttempt(ip);
|
||||
return ApiError.INVALID_CREDENTIALS.createException("Refresh token not found");
|
||||
});
|
||||
|
||||
if (storedToken.isRevoked() || storedToken.getExpiryDate().isBefore(Instant.now()) || !jwtUtils.validateToken(token)) {
|
||||
authRateLimitService.recordFailedRefreshAttempt(ip);
|
||||
throw ApiError.INVALID_CREDENTIALS.createException("Invalid or expired refresh token");
|
||||
}
|
||||
|
||||
BookLoreUserEntity user = storedToken.getUser();
|
||||
|
||||
storedToken.setRevoked(true);
|
||||
storedToken.setRevocationDate(Instant.now());
|
||||
refreshTokenRepository.save(storedToken);
|
||||
|
||||
String newRefreshToken = jwtUtils.generateRefreshToken(user);
|
||||
RefreshTokenEntity newRefreshTokenEntity = RefreshTokenEntity.builder()
|
||||
.user(user)
|
||||
.token(newRefreshToken)
|
||||
.expiryDate(Instant.now().plusMillis(jwtUtils.getRefreshTokenExpirationMs()))
|
||||
.revoked(false)
|
||||
.build();
|
||||
|
||||
refreshTokenRepository.save(newRefreshTokenEntity);
|
||||
|
||||
authRateLimitService.resetRefreshAttempts(ip);
|
||||
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"accessToken", jwtUtils.generateAccessToken(user),
|
||||
"refreshToken", newRefreshToken
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package org.booklore.config.security.service;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.enums.AuditAction;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class LoginRateLimitService {
|
||||
|
||||
private static final int MAX_ATTEMPTS = 5;
|
||||
|
||||
private final Cache<String, AtomicInteger> attemptCache;
|
||||
private final AuditService auditService;
|
||||
|
||||
public LoginRateLimitService(AuditService auditService) {
|
||||
this.auditService = auditService;
|
||||
this.attemptCache = Caffeine.newBuilder()
|
||||
.maximumSize(1000)
|
||||
.expireAfterWrite(Duration.ofMinutes(15))
|
||||
.build();
|
||||
}
|
||||
|
||||
public void checkRateLimit(String ip) {
|
||||
AtomicInteger attempts = attemptCache.getIfPresent(ip);
|
||||
if (attempts != null && attempts.get() >= MAX_ATTEMPTS) {
|
||||
auditService.log(AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for IP: " + ip);
|
||||
throw ApiError.RATE_LIMITED.createException();
|
||||
}
|
||||
}
|
||||
|
||||
public void recordFailedAttempt(String ip) {
|
||||
attemptCache.get(ip, k -> new AtomicInteger(0)).incrementAndGet();
|
||||
}
|
||||
|
||||
public void resetAttempts(String ip) {
|
||||
attemptCache.invalidate(ip);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package org.booklore.config.security.service;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.oidc.OidcDiscoveryService;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.response.LogoutResponse;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.OidcSessionEntity;
|
||||
import org.booklore.model.entity.RefreshTokenEntity;
|
||||
import org.booklore.model.enums.AuditAction;
|
||||
import org.booklore.model.enums.ProvisioningMethod;
|
||||
import org.booklore.repository.OidcSessionRepository;
|
||||
import org.booklore.repository.RefreshTokenRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class LogoutService {
|
||||
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final OidcSessionRepository oidcSessionRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
private final OidcDiscoveryService discoveryService;
|
||||
private final AuditService auditService;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@Transactional
|
||||
public LogoutResponse logout(Authentication auth, String refreshToken, String origin) {
|
||||
BookLoreUserEntity user = resolveUser(auth, refreshToken);
|
||||
|
||||
revokeRefreshToken(user);
|
||||
|
||||
String logoutUrl = null;
|
||||
if (user.getProvisioningMethod() == ProvisioningMethod.OIDC && appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
logoutUrl = buildOidcLogoutUrl(user, origin);
|
||||
}
|
||||
|
||||
auditService.log(AuditAction.LOGOUT, "User", user.getId(), "User logged out: " + user.getUsername());
|
||||
return new LogoutResponse(logoutUrl);
|
||||
}
|
||||
|
||||
private BookLoreUserEntity resolveUser(Authentication auth, String refreshToken) {
|
||||
if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getPrincipal())) {
|
||||
var bookLoreUser = authenticationService.getAuthenticatedUser();
|
||||
return userRepository.findByUsername(bookLoreUser.getUsername())
|
||||
.orElseThrow(() -> ApiError.GENERIC_UNAUTHORIZED.createException("User not found"));
|
||||
}
|
||||
|
||||
if (refreshToken != null && !refreshToken.isBlank()) {
|
||||
RefreshTokenEntity tokenEntity = refreshTokenRepository.findByToken(refreshToken)
|
||||
.orElseThrow(() -> ApiError.GENERIC_UNAUTHORIZED.createException("Invalid refresh token"));
|
||||
return tokenEntity.getUser();
|
||||
}
|
||||
|
||||
throw ApiError.GENERIC_UNAUTHORIZED.createException("No authentication context or refresh token provided");
|
||||
}
|
||||
|
||||
private void revokeRefreshToken(BookLoreUserEntity user) {
|
||||
List<RefreshTokenEntity> tokens = refreshTokenRepository.findAllByUserAndRevokedFalse(user);
|
||||
tokens.forEach(token -> {
|
||||
token.setRevoked(true);
|
||||
token.setRevocationDate(Instant.now());
|
||||
});
|
||||
refreshTokenRepository.saveAll(tokens);
|
||||
}
|
||||
|
||||
private String buildOidcLogoutUrl(BookLoreUserEntity user, String origin) {
|
||||
try {
|
||||
var providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
var session = oidcSessionRepository.findFirstByUserIdAndRevokedFalseOrderByCreatedAtDesc(user.getId());
|
||||
|
||||
if (session.isPresent()) {
|
||||
OidcSessionEntity oidcSession = session.get();
|
||||
oidcSession.setRevoked(true);
|
||||
oidcSessionRepository.save(oidcSession);
|
||||
|
||||
var discovery = discoveryService.discover(providerDetails.getIssuerUri());
|
||||
if (discovery.endSessionEndpoint() != null) {
|
||||
String postLogoutRedirectUri = (origin != null && !origin.isBlank() ? origin : "") + "/login";
|
||||
|
||||
var builder = UriComponentsBuilder.fromUriString(discovery.endSessionEndpoint())
|
||||
.queryParam("client_id", providerDetails.getClientId())
|
||||
.queryParam("id_token_hint", oidcSession.getIdTokenHint());
|
||||
|
||||
if (!postLogoutRedirectUri.equals("/login")) {
|
||||
builder.queryParam("post_logout_redirect_uri", postLogoutRedirectUri);
|
||||
}
|
||||
|
||||
return builder.build().toUriString();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to build OIDC logout URL: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package org.booklore.config.security.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.mapper.OpdsUserV2Mapper;
|
||||
import org.booklore.model.dto.OpdsUserV2;
|
||||
import org.booklore.model.entity.OpdsUserV2Entity;
|
||||
import org.booklore.repository.OpdsUserV2Repository;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsUserDetailsService implements UserDetailsService {
|
||||
|
||||
private final OpdsUserV2Repository opdsUserV2Repository;
|
||||
private final OpdsUserV2Mapper opdsUserV2Mapper;
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public OpdsUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
OpdsUserV2Entity userV2 = opdsUserV2Repository.findByUsername(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("Invalid credentials"));
|
||||
OpdsUserV2 mappedCredential = opdsUserV2Mapper.toDto(userV2);
|
||||
return new OpdsUserDetails(mappedCredential);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package org.booklore.config.security.userdetails;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public class KoreaderUserDetails implements UserDetails {
|
||||
|
||||
private final String username;
|
||||
private final String password;
|
||||
@Getter
|
||||
private final boolean syncEnabled;
|
||||
@Getter
|
||||
private final boolean syncWithBookloreReader;
|
||||
@Getter
|
||||
private final Long bookLoreUserId;
|
||||
private final Collection<? extends GrantedAuthority> authorities;
|
||||
|
||||
public KoreaderUserDetails(String username, String password, boolean syncEnabled, boolean syncWithBookloreReader, Long bookLoreUserId, Collection<? extends GrantedAuthority> authorities) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.syncEnabled = syncEnabled;
|
||||
this.syncWithBookloreReader = syncWithBookloreReader;
|
||||
this.bookLoreUserId = bookLoreUserId;
|
||||
this.authorities = authorities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return authorities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package org.booklore.config.security.userdetails;
|
||||
|
||||
import org.booklore.model.dto.OpdsUserV2;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsUserDetails implements UserDetails {
|
||||
|
||||
private final OpdsUserV2 opdsUserV2;
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return opdsUserV2.getUsername();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return opdsUserV2.getPasswordHash();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package org.booklore.config.security.userdetails;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.Getter;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetails;
|
||||
|
||||
@Getter
|
||||
public class UserAuthenticationDetails extends WebAuthenticationDetails {
|
||||
|
||||
private final Long userId;
|
||||
|
||||
public UserAuthenticationDetails(HttpServletRequest request, Long userId) {
|
||||
super(request);
|
||||
this.userId = userId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.booklore.context;
|
||||
|
||||
/**
|
||||
* ThreadLocal context to track whether the Komga API "clean" mode is enabled.
|
||||
* When clean mode is enabled:
|
||||
* - Fields ending with "Lock" are excluded from JSON serialization
|
||||
* - Null values are excluded from JSON serialization
|
||||
* - Metadata fields (language, summary, etc.) are allowed to be null
|
||||
*/
|
||||
public class KomgaCleanContext {
|
||||
private static final ThreadLocal<Boolean> cleanModeEnabled = ThreadLocal.withInitial(() -> false);
|
||||
|
||||
public static void setCleanMode(boolean enabled) {
|
||||
cleanModeEnabled.set(enabled);
|
||||
}
|
||||
|
||||
public static boolean isCleanMode() {
|
||||
return cleanModeEnabled.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
cleanModeEnabled.remove();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package org.booklore.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.booklore.config.security.annotation.CheckBookAccess;
|
||||
import org.booklore.model.dto.BookFile;
|
||||
import org.booklore.model.dto.request.DetachBookFileRequest;
|
||||
import org.booklore.model.dto.response.DetachBookFileResponse;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.service.book.BookFileDetachmentService;
|
||||
import org.booklore.service.file.AdditionalFileService;
|
||||
import org.booklore.service.upload.FileUploadService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@RequestMapping("/api/v1/books/{bookId}/files")
|
||||
@RestController
|
||||
@AllArgsConstructor
|
||||
@Tag(name = "Book Files", description = "Endpoints for managing additional files attached to books")
|
||||
public class AdditionalFileController {
|
||||
|
||||
private final AdditionalFileService additionalFileService;
|
||||
private final FileUploadService fileUploadService;
|
||||
private final BookFileDetachmentService bookFileDetachmentService;
|
||||
|
||||
@Operation(
|
||||
summary = "List additional book files",
|
||||
description = "Retrieve additional files for a specific book.",
|
||||
operationId = "additionalFileGetAdditionalFiles"
|
||||
)
|
||||
@GetMapping
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<List<BookFile>> getAdditionalFiles(@PathVariable Long bookId) {
|
||||
List<BookFile> files = additionalFileService.getAdditionalFilesByBookId(bookId);
|
||||
return ResponseEntity.ok(files);
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "List additional files by type",
|
||||
description = "Retrieve additional files for a specific book filtered by whether they are primary book files.",
|
||||
operationId = "additionalFileGetFilesByIsBook"
|
||||
)
|
||||
@GetMapping(params = "isBook")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<List<BookFile>> getFilesByIsBook(
|
||||
@PathVariable Long bookId,
|
||||
@RequestParam boolean isBook) {
|
||||
List<BookFile> files = additionalFileService.getAdditionalFilesByBookIdAndIsBook(bookId, isBook);
|
||||
return ResponseEntity.ok(files);
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Upload additional book file",
|
||||
description = "Upload and attach a new additional file to a specific book.",
|
||||
operationId = "additionalFileUploadAdditionalFile"
|
||||
)
|
||||
@PostMapping(consumes = "multipart/form-data")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
@PreAuthorize("@securityUtil.canUpload() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<BookFile> uploadAdditionalFile(
|
||||
@PathVariable Long bookId,
|
||||
@RequestParam("file") MultipartFile file,
|
||||
@RequestParam boolean isBook,
|
||||
@RequestParam(required = false) BookFileType bookType,
|
||||
@RequestParam(required = false) String description) {
|
||||
BookFile additionalFile = fileUploadService.uploadAdditionalFile(bookId, file, isBook, bookType, description);
|
||||
return ResponseEntity.ok(additionalFile);
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Download additional book file",
|
||||
description = "Download a specific additional file attached to a book.",
|
||||
operationId = "additionalFileDownloadAdditionalFile"
|
||||
)
|
||||
@GetMapping("/{fileId}/download")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<Resource> downloadAdditionalFile(
|
||||
@PathVariable Long bookId,
|
||||
@PathVariable Long fileId) throws IOException {
|
||||
return additionalFileService.downloadAdditionalFile(bookId, fileId);
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Delete additional book file",
|
||||
description = "Delete a specific additional file attached to a book.",
|
||||
operationId = "additionalFileDeleteAdditionalFile"
|
||||
)
|
||||
@DeleteMapping("/{fileId}")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
@PreAuthorize("@securityUtil.canDeleteBook() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Void> deleteAdditionalFile(
|
||||
@PathVariable Long bookId,
|
||||
@PathVariable Long fileId) {
|
||||
additionalFileService.deleteAdditionalFile(bookId, fileId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Detach additional book file",
|
||||
description = "Detach a specific additional file from a book and optionally copy metadata.",
|
||||
operationId = "additionalFileDetachFile"
|
||||
)
|
||||
@PostMapping("/{fileId}/detach")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<DetachBookFileResponse> detachFile(
|
||||
@PathVariable Long bookId,
|
||||
@PathVariable Long fileId,
|
||||
@RequestBody DetachBookFileRequest request) {
|
||||
return ResponseEntity.ok(bookFileDetachmentService.detachBookFile(bookId, fileId, request.copyMetadata()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package org.booklore.controller;
|
||||
|
||||
import org.booklore.model.dto.Annotation;
|
||||
import org.booklore.model.dto.CreateAnnotationRequest;
|
||||
import org.booklore.model.dto.UpdateAnnotationRequest;
|
||||
import org.booklore.service.book.AnnotationService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/annotations")
|
||||
@Tag(name = "Annotations", description = "Endpoints for managing book annotations (highlights, underlines, etc.)")
|
||||
public class AnnotationController {
|
||||
|
||||
private final AnnotationService annotationService;
|
||||
|
||||
@Operation(summary = "Get annotations for a book", description = "Retrieve all annotations for a specific book.")
|
||||
@ApiResponse(responseCode = "200", description = "Annotations returned successfully")
|
||||
@GetMapping("/book/{bookId}")
|
||||
public List<Annotation> getAnnotationsForBook(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return annotationService.getAnnotationsForBook(bookId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get a specific annotation", description = "Retrieve a specific annotation by its ID.")
|
||||
@ApiResponse(responseCode = "200", description = "Annotation returned successfully")
|
||||
@GetMapping("/{annotationId}")
|
||||
public Annotation getAnnotationById(
|
||||
@Parameter(description = "ID of the annotation") @PathVariable Long annotationId) {
|
||||
return annotationService.getAnnotationById(annotationId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Create an annotation", description = "Create a new annotation (highlight, underline, etc.) for a book.")
|
||||
@ApiResponse(responseCode = "200", description = "Annotation created successfully")
|
||||
@PostMapping
|
||||
public Annotation createAnnotation(
|
||||
@Parameter(description = "Annotation creation request") @Valid @RequestBody CreateAnnotationRequest request) {
|
||||
return annotationService.createAnnotation(request);
|
||||
}
|
||||
|
||||
@Operation(summary = "Update an annotation", description = "Update an existing annotation's properties (color, style, note).")
|
||||
@ApiResponse(responseCode = "200", description = "Annotation updated successfully")
|
||||
@PutMapping("/{annotationId}")
|
||||
public Annotation updateAnnotation(
|
||||
@Parameter(description = "ID of the annotation to update") @PathVariable Long annotationId,
|
||||
@Parameter(description = "Annotation update request") @Valid @RequestBody UpdateAnnotationRequest request) {
|
||||
return annotationService.updateAnnotation(annotationId, request);
|
||||
}
|
||||
|
||||
@Operation(summary = "Delete an annotation", description = "Delete a specific annotation by its ID.")
|
||||
@ApiResponse(responseCode = "204", description = "Annotation deleted successfully")
|
||||
@DeleteMapping("/{annotationId}")
|
||||
public ResponseEntity<Void> deleteAnnotation(
|
||||
@Parameter(description = "ID of the annotation to delete") @PathVariable Long annotationId) {
|
||||
annotationService.deleteAnnotation(annotationId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package org.booklore.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.model.dto.settings.AppSettingKey;
|
||||
import org.booklore.model.dto.settings.AppSettings;
|
||||
import org.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import org.booklore.model.dto.settings.SettingRequest;
|
||||
import org.booklore.model.enums.AuditAction;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
import org.booklore.service.oidc.OidcDiagnosticService;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import tools.jackson.core.JacksonException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "App Settings", description = "Endpoints for retrieving and updating application settings")
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/settings")
|
||||
public class AppSettingController {
|
||||
|
||||
private final AppSettingService appSettingService;
|
||||
private final OidcDiagnosticService oidcDiagnosticService;
|
||||
private final AuditService auditService;
|
||||
|
||||
@Operation(summary = "Get application settings", description = "Retrieve all application settings.")
|
||||
@ApiResponse(responseCode = "200", description = "Application settings returned successfully")
|
||||
@GetMapping
|
||||
public AppSettings getAppSettings() {
|
||||
return appSettingService.getAppSettings();
|
||||
}
|
||||
|
||||
@Operation(summary = "Update application settings", description = "Update one or more application settings.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Settings updated successfully"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request")
|
||||
})
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
@PutMapping
|
||||
public void updateSettings(@Parameter(description = "List of settings to update") @RequestBody List<SettingRequest> settingRequests) throws JacksonException {
|
||||
for (SettingRequest settingRequest : settingRequests) {
|
||||
AppSettingKey key = AppSettingKey.valueOf(settingRequest.getName());
|
||||
appSettingService.updateSetting(key, settingRequest.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/oidc/test")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public OidcDiagnosticService.OidcTestResult testOidcConnection(@RequestBody OidcProviderDetails providerDetails) {
|
||||
var result = oidcDiagnosticService.testConnection(providerDetails);
|
||||
auditService.log(AuditAction.OIDC_CONNECTION_TEST, "OIDC connection test: " + (result.success() ? "passed" : "failed"));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user